diff --git a/ASSETS.md b/ASSETS.md index 029a978153..ffa455079d 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -115,6 +115,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-anchor-smooth.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-appearance.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-arc.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-arc-three-point.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Three-Point Arc tool: an arc through its two ends and a third point | | `assets/icons/dc-arrow-down.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-arrow-extend.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-arrow-fill.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | The Selection and Direct Selection arrows' fill, painted black or white under their outline | diff --git a/Cargo.lock b/Cargo.lock index fa3b9166e7..65cc426291 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=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "crc32fast", "flate2", @@ -1012,12 +1012,12 @@ dependencies = [ [[package]] name = "craft-codepage" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" [[package]] name = "craft-dds" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "rayon", ] @@ -1025,12 +1025,12 @@ dependencies = [ [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" [[package]] name = "craft-dxf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "craft-codepage", "encoding_rs", @@ -1042,12 +1042,12 @@ dependencies = [ [[package]] name = "craft-eps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" [[package]] name = "craft-font-catalog" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "harfrust 0.13.3", "kurbo 0.13.1", @@ -1061,12 +1061,12 @@ dependencies = [ [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" [[package]] name = "craft-gif" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "gif", ] @@ -1074,7 +1074,7 @@ dependencies = [ [[package]] name = "craft-gzip" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "flate2", ] @@ -1082,7 +1082,7 @@ dependencies = [ [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1105,7 +1105,7 @@ dependencies = [ [[package]] name = "craft-image-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "craft-dds", "craft-jpeg", @@ -1132,7 +1132,7 @@ dependencies = [ [[package]] name = "craft-jpeg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "thiserror 2.0.21", ] @@ -1140,8 +1140,9 @@ dependencies = [ [[package]] name = "craft-jxl" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ + "brotli-decompressor 5.0.3", "jixel", "jxl-oxide", "thiserror 2.0.21", @@ -1150,7 +1151,7 @@ dependencies = [ [[package]] name = "craft-keymap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "egui", "serde", @@ -1160,7 +1161,7 @@ dependencies = [ [[package]] name = "craft-metadata" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "brotli-decompressor 6.3.2", "chrono", @@ -1172,7 +1173,7 @@ dependencies = [ [[package]] name = "craft-metafile" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "encoding_rs", "image", @@ -1183,7 +1184,7 @@ dependencies = [ [[package]] name = "craft-mime" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "chrono", "craft-codepage", @@ -1193,7 +1194,7 @@ dependencies = [ [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "hayro-interpret", "hayro-syntax", @@ -1204,15 +1205,16 @@ dependencies = [ [[package]] name = "craft-plotter" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57#a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ + "kurbo 0.13.1", "thiserror 2.0.21", ] [[package]] name = "craft-print" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "craft-winprint-gdi", "log", @@ -1226,7 +1228,7 @@ dependencies = [ [[package]] name = "craft-proof" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "log", "miniz_oxide 0.9.1", @@ -1237,7 +1239,7 @@ dependencies = [ [[package]] name = "craft-ps" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "flate2", "kurbo 0.13.1", @@ -1246,7 +1248,7 @@ dependencies = [ [[package]] name = "craft-psd" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "encoding_rs", "flate2", @@ -1257,7 +1259,7 @@ dependencies = [ [[package]] name = "craft-stream-codecs" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "fax", "hayro-ccitt", @@ -1268,12 +1270,14 @@ dependencies = [ [[package]] name = "craft-svg" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "craft-image-codecs", "craft-xml", "data-url", "flate2", + "gif", + "image-webp", "kurbo 0.13.1", "quick-xml 0.41.0", "resvg 0.48.1", @@ -1287,7 +1291,7 @@ dependencies = [ [[package]] name = "craft-tiff" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "serde", "thiserror 2.0.21", @@ -1296,7 +1300,7 @@ dependencies = [ [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1317,7 +1321,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "chrono", "dunce", @@ -1344,7 +1348,7 @@ dependencies = [ [[package]] name = "craft-vectorcraft-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "flate2", "serde", @@ -1355,7 +1359,7 @@ dependencies = [ [[package]] name = "craft-web-api" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "js-sys", "serde_json", @@ -1366,7 +1370,7 @@ dependencies = [ [[package]] name = "craft-window" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "egui", "objc2 0.6.5", @@ -1385,7 +1389,7 @@ dependencies = [ [[package]] name = "craft-xml" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "quick-xml 0.41.0", "serde", @@ -2492,7 +2496,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-cmap" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "brotli", "hayro-postscript", @@ -2501,7 +2505,7 @@ dependencies = [ [[package]] name = "hayro-interpret" version = "0.7.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "bitflags 2.13.2", "hayro-cmap", @@ -2519,7 +2523,7 @@ dependencies = [ [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "fearless_simd", "hayro-ccitt", @@ -2537,12 +2541,12 @@ dependencies = [ [[package]] name = "hayro-postscript" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "flate2", "hayro-ccitt", @@ -3342,7 +3346,7 @@ dependencies = [ [[package]] name = "krilla" version = "0.8.2" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "base64 0.22.1", "bumpalo", @@ -3451,7 +3455,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "linesweeper" version = "0.5.0" -source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" dependencies = [ "arrayvec", "kurbo 0.13.1", diff --git a/Cargo.toml b/Cargo.toml index e334f3e9e3..fea9cdda55 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,40 +11,40 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["interpret", "write"] } -craft-print = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } -craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["serde"] } -craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } -craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +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" } # 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 = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["egui"] } +craft-window = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", 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 = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } -craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } +craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } # 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 = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } # SVG parsing, limits, SVGZ and writer (craft-libs#778). -craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["tree"] } -craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", features = ["tree"] } +craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). -craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } # DXF tags, reader and writer (craft-libs#778, #926, #927). -craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" } -craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } +craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } # WMF, EMF and EMF+ reader (craft-libs#778). -craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } -craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } -craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } -craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } -craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } -craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", default-features = false, features = ["write"] } -craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } -craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } -craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["egui"] } +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"] } # internal vectorcraft-geom = { path = "crates/geom" } vectorcraft-color = { path = "crates/color" } @@ -185,13 +185,13 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } -hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } -hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } -hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } -krilla = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } -linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" } +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" } 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 c4a6edc8fb..ef05d5dc9a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -128,6 +128,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged. - 2026-11-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), headline numbers unchanged. +- 2026-11-18: Built-in Paint brush library: Flat Sweep, Dry Drag, Loaded Stroke and Fan Sweep, original art brushes generated in code that take the stroke color as tints. Thirteen built-in brush libraries; headline numbers unchanged. - 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged. - 2026-11-17: The canvas's left edge docks a floating Tools panel whichever way Keep Tools Beside the Canvas is set: a drop there, right of panels docked on the left, turns the setting on, and a drop on the window's left edge turns it off (#7837). Headline numbers unchanged. @@ -162,6 +163,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-17: Tangent Circle Tool joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools, and the All Tools drawer): click a path segment, then another, to draw the circle tangent to the first where it was clicked that touches the second; Shift uses the tool's radius and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it. The circle shows with its center and radii before the click, one undo step (`tangentCircle`). A VectorCraft addition: headline numbers unchanged. - 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged. +- 2026-11-17: Three-Point Arc tool, in the Line Segment tool's group after the Arc tool: two ends placed by a drag or two clicks, then a third point the open circular arc passes through, or with Third Point Sets Direction (Tool Options, or `]` while drawing) the direction the arc leaves an end in; it previews the arc, its center and, with Measurement Labels on, its radius, and draws it in one undo step (`shape.threePointArc`). Points with no arc are refused with a message. A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged. - 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 74f2095669..5dfe7386f6 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -246,6 +246,7 @@ fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_script_data(&mut h.session); prefs_dir::attach_metadata_templates_dir(&mut h.session); prefs_dir::attach_new_doc_profiles(&mut h.session); + prefs_dir::attach_proof_setups(&mut h.session); prefs_dir::attach_profile_store(&mut h.session); prefs_dir::attach_color_settings(&mut h.session); prefs_dir::attach_plugin_store(&mut h.session); diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index f86996f075..9569d2b3f3 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -17,7 +17,7 @@ path = "src/main.rs" vectorcraft-engine = { workspace = true, features = ["bundled-fonts", "heif"] } vectorcraft-ui-egui = { workspace = true } # The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft. -craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", version = "0.1.0" } +craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", version = "0.1.0" } vectorcraft-format = { workspace = true } vectorcraft-text = { workspace = true } egui = { workspace = true } diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 1778503201..aa62211500 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -554,6 +554,7 @@ fn main() -> std::process::ExitCode { // File Info's metadata templates live in their own folder next to the preferences. prefs_dir::attach_metadata_templates_dir(&mut session); prefs_dir::attach_new_doc_profiles(&mut session); + prefs_dir::attach_proof_setups(&mut session); prefs_dir::attach_script_data(&mut session); let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone())); app.set_startup_update_check(true); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index d9defc5686..f863a6eba3 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -81,6 +81,14 @@ pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) { } } +/// Have View › Proof Setup list the proof setups saved in the `Proof Setups` folder, which +/// `view.proofSetup.save` makes when it saves a setup by name. +pub fn attach_proof_setups(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("Proof Setups") { + session.attach_proof_setups(dir); + } +} + /// Keep each script's `Folder.userData` in the `Script Data` folder, and the file access people /// allow scripts with Always in `Script Grants.json` beside it. Both are made when a script first /// needs them. diff --git a/assets/icons/dc-arc-three-point.svg b/assets/icons/dc-arc-three-point.svg new file mode 100644 index 0000000000..479a9a5930 --- /dev/null +++ b/assets/icons/dc-arc-three-point.svg @@ -0,0 +1 @@ + diff --git a/crates/cad/src/hpgl/write.rs b/crates/cad/src/hpgl/write.rs index 06ddc09b93..4e08fb3f5e 100644 --- a/crates/cad/src/hpgl/write.rs +++ b/crates/cad/src/hpgl/write.rs @@ -534,47 +534,13 @@ fn plain(by_pen: &[Vec>]) -> Vec { /// HP-GL/2: `IN;`, the palette, each pen's paths as one `PE`, `PU;SP0;`. fn encoded(by_pen: &[Vec>], pens: &[[u8; 3]]) -> Vec { - let mut out = b"IN;".to_vec(); - if !pens.is_empty() { - // Pens 1 to n on a plotter, and on a raster device (whose pens are 0 to NP − 1) too. - let np = (pens.len() + 1).next_power_of_two().max(2); - out.extend(format!("NP{np};").bytes()); - for (i, [r, g, b]) in pens.iter().enumerate() { - out.extend(format!("PC{},{r},{g},{b};", i + 1).bytes()); - } - } - let mut at: Option<(i64, i64)> = None; - for (i, paths) in by_pen.iter().enumerate().filter(|(_, p)| !p.is_empty()) { - out.extend(format!("PU;SP{};PE", i + 1).bytes()); - for path in paths { - for (k, &p) in path.iter().enumerate() { - if k == 0 { - out.push(b'<'); - } - // The first move of the plot is absolute, and so is one longer than the range a - // device takes for each number; every other is relative. - match at.map(|a| (p.0 - a.0, p.1 - a.1)).filter(|d| d.0.abs() <= MAX_COORD && d.1.abs() <= MAX_COORD) { - None => { - out.push(b'='); - pe_number(&mut out, p.0); - pe_number(&mut out, p.1); - } - Some((dx, dy)) => { - pe_number(&mut out, dx); - pe_number(&mut out, dy); - } - } - at = Some(p); - } - } - out.push(b';'); - } - out.extend(b"PU;SP0;"); - out + let pens: Vec<_> = pens.iter().enumerate().map(|(index, &rgb)| craft_plotter::hpgl::write::Pen { number: index + 1, rgb }).collect(); + craft_plotter::hpgl::write::write_hpgl2(&pens, by_pen) } /// `v` as a base-64 PE number: the sign in the low bit, the low digits from 63 up and the last /// digit from 191 up. +#[cfg(test)] fn pe_number(out: &mut Vec, v: i64) { let mut n = (v.unsigned_abs() << 1) | u64::from(v < 0); while n >= 64 { @@ -973,10 +939,8 @@ impl<'a> Walk<'a> { end(&mut cur, &mut out, false); cur.push(p); } - PathEl::LineTo(p) => { - if cur.last() != Some(&p) { - cur.push(p); - } + PathEl::LineTo(p) if cur.last() != Some(&p) => { + cur.push(p); } PathEl::ClosePath => { let s = cur.first().copied(); diff --git a/crates/cad/src/hpgl/write/tests.rs b/crates/cad/src/hpgl/write/tests.rs index 493e53906c..f04b331696 100644 --- a/crates/cad/src/hpgl/write/tests.rs +++ b/crates/cad/src/hpgl/write/tests.rs @@ -1179,6 +1179,25 @@ fn encoded_numbers_follow_the_reference_guide() { assert_eq!(out, [194, 191]); } +/// The app adapter must preserve raw bytes and position across the one-based pen table. +#[test] +fn hpgl2_shared_writer_preserves_raw_bytes_and_pen_indices() { + let paths = vec![vec![vec![(32, -32)]], vec![], vec![vec![(33, -31)], vec![(34, -30)]]]; + let pens = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; + assert_eq!(encoded(&paths, &pens), b"IN;NP4;PC1,1,2,3;PC2,4,5,6;PC3,7,8,9;PU;SP1;PE<=?\xc0@\xc0;PU;SP3;PE<\xc1\xc1<\xc1\xc1;PU;SP0;"); +} + +#[test] +fn hpgl2_shared_writer_preserves_empty_and_last_admitted_pen() { + assert_eq!(encoded(&[], &[]), b"IN;PU;SP0;"); + let pens = vec![[0, 0, 0]; MAX_PENS]; + let mut paths = vec![vec![]; MAX_PENS]; + paths[MAX_PENS - 1] = vec![vec![(0, 0)]]; + let bytes = encoded(&paths, &pens); + assert!(bytes.starts_with(b"IN;NP256;PC1,0,0,0;")); + assert!(bytes.ends_with(b"PC255,0,0,0;PU;SP255;PE<=\xbf\xbf;PU;SP0;")); +} + #[test] fn hpgl2_writes_the_palette_and_encoded_polylines() { let out = plot(&three(), &HpglOptions { version: Version::Hpgl2, ..opts(&three()) }); diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index a3c35db8ce..a01d174ce7 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -458,6 +458,15 @@ impl Cms { CmykSpace::Generic(g) => g.to_srgb(cmyk, absolute, bpc), CmykSpace::Device => naive_cmyk_to_rgb(cmyk), CmykSpace::Icc(p) => { + // With black-point compensation the profile's black maps onto sRGB black, as + // `cmyk_to_srgb` shows the working space. + if bpc + && !absolute + && let Some(srgb) = builtin_rgb_cache(SRGB) + && let Some(v) = p.to_rgb_of(&srgb, &cmyk, Intent::RelativeColorimetric, true) + { + return v; + } let i = if absolute { Intent::AbsoluteColorimetric } else { Intent::RelativeColorimetric }; p.to_srgb(&cmyk, i).unwrap_or_else(|| naive_cmyk_to_rgb(cmyk)) } @@ -676,32 +685,108 @@ impl Cms { ProofTarget::Tritanopia => TRITANOPIA.simulate(srgb), ProofTarget::WorkingCmyk => { let working = self.working_cms(); - let cmyk = working.srgb_to_cmyk(srgb, proof.intent); - working.cmyk_to_srgb(cmyk, proof.simulate_paper) + let cmyk = if proof.preserve_numbers { self.preserved_cmyk(srgb) } else { working.srgb_to_cmyk(srgb, proof.intent) }; + self.proof_cmyk_to_srgb(cmyk, proof) } ProofTarget::Cmyk(name) => match cmyk_space(name) { Ok(sp) => { - let cmyk = Self::srgb_to_cmyk_in(&sp, srgb, proof.intent, self.settings.bpc); - Self::cmyk_to_srgb_in(&sp, cmyk, proof.simulate_paper, self.settings.bpc) + let cmyk = if proof.preserve_numbers { + self.preserved_cmyk(srgb) + } else { + Self::srgb_to_cmyk_in(&sp, srgb, proof.intent, self.settings.bpc) + }; + self.proof_cmyk_to_srgb(cmyk, proof) + } + Err(_) => srgb, + }, + ProofTarget::Rgb(name) => match rgb_space(canonical_name(name)) { + Ok(RgbSpace::Srgb) if !proof.preserve_numbers => srgb, + Ok(RgbSpace::Srgb) => self.srgb_to_rgb(srgb).map(|v| v.clamp(0.0, 1.0)), + Ok(RgbSpace::Icc(p)) => { + // The device's own numbers for the color: the document's RGB numbers unchanged, + // or the color converted into the device's space with the proof's intent. + let numbers = if proof.preserve_numbers { + self.srgb_to_rgb(srgb) + } else { + p.from_srgb(srgb, proof.intent).and_then(|v| Some([*v.first()?, *v.get(1)?, *v.get(2)?])).unwrap_or(srgb) + }; + p.to_srgb(&numbers, Intent::RelativeColorimetric).unwrap_or(srgb) } Err(_) => srgb, }, } } + /// Display sRGB of color `c` proofed with Preserve Numbers on a CMYK or RGB device: its own + /// numbers go to the device unchanged. A CMYK device takes a CMYK color's inks as they are, a + /// gray as K only and another color's inks in this context's CMYK space (relative + /// colorimetric); an RGB device takes an RGB color's numbers as they are and another color's + /// numbers in this context's RGB space. Other targets proof the color's display sRGB + /// ([`Self::proof_srgb`]). + pub fn proof_color(&self, c: &Color, proof: &ProofSetup) -> [f32; 3] { + if !proof.preserve_numbers { + return self.proof_srgb(self.display_rgb(c), proof); + } + match &proof.target { + // A device whose profile is not loaded leaves the color as it is, as for a pixel. + ProofTarget::Cmyk(name) if cmyk_space(name).is_err() => self.display_rgb(c), + ProofTarget::WorkingCmyk | ProofTarget::Cmyk(_) => self.proof_cmyk_to_srgb(self.to_cmyk(c, Intent::RelativeColorimetric), proof), + ProofTarget::Rgb(name) => { + // A CMYK color converts straight into the RGB space, so a wide space keeps it. + let numbers = match self.convert(c, Model::Rgb, Intent::RelativeColorimetric) { + Color::Rgb { r, g, b } => [r, g, b], + other => self.srgb_to_rgb(self.display_rgb(&other)), + } + .map(|v| v.clamp(0.0, 1.0)); + match rgb_space(canonical_name(name)) { + Ok(RgbSpace::Srgb) => numbers, + Ok(RgbSpace::Icc(p)) => p.to_srgb(&numbers, Intent::RelativeColorimetric).unwrap_or(numbers), + Err(_) => self.display_rgb(c), + } + } + _ => self.proof_srgb(self.display_rgb(c), proof), + } + } + + /// The CMYK numbers display sRGB `srgb` has in this context's CMYK space (relative + /// colorimetric), which Preserve CMYK Numbers sends to the simulated device unchanged: for + /// pixels whose own numbers are not known (an RGB image's pixels, art drawn over other art). + /// A color whose numbers are known proofs through [`Self::proof_color`]. + fn preserved_cmyk(&self, srgb: [f32; 3]) -> [f32; 4] { + self.srgb_to_cmyk(srgb, Intent::RelativeColorimetric) + } + /// Display sRGB of CMYK inks in the proof's CMYK space (this context's CMYK space for RGB - /// targets). + /// targets). Simulate Paper Color shows the paper's color and the press black (absolute + /// colorimetric); else Simulate Black Ink shows the press black as the dark gray it prints + /// (media-relative, without black-point compensation). pub fn proof_cmyk_to_srgb(&self, cmyk: [f32; 4], proof: &ProofSetup) -> [f32; 3] { + let black = proof.simulate_black && !proof.simulate_paper; match &proof.target { ProofTarget::Cmyk(name) => match cmyk_space(name) { + Ok(sp) if black => Self::black_ink_srgb(&sp, cmyk), Ok(sp) => Self::cmyk_to_srgb_in(&sp, cmyk, proof.simulate_paper, self.settings.bpc), Err(_) => self.cmyk_to_srgb(cmyk, proof.simulate_paper), }, + ProofTarget::WorkingCmyk if black => Self::black_ink_srgb(&self.working_cms().cmyk, cmyk), ProofTarget::WorkingCmyk => self.working_cms().cmyk_to_srgb(cmyk, proof.simulate_paper), _ => self.cmyk_to_srgb(cmyk, proof.simulate_paper), } } + /// Display sRGB of `cmyk` in `space`, media-relative and without black-point compensation, so + /// the darkest ink the space prints shows as the gray it is rather than as black. + fn black_ink_srgb(space: &CmykSpace, cmyk: [f32; 4]) -> [f32; 3] { + let cmyk = cmyk.map(|v| v.clamp(0.0, 1.0)); + if let CmykSpace::Icc(p) = space + && let Some(srgb) = builtin_rgb_cache(SRGB) + && let Some(v) = p.to_rgb_of(&srgb, &cmyk, Intent::RelativeColorimetric, false) + { + return v; + } + Self::cmyk_to_srgb_in(space, cmyk, false, false) + } + /// The context of the working settings: the one [`use_document_profiles`] put a document's /// profiles in place of, else this one. fn working_cms(&self) -> &Cms { @@ -711,7 +796,10 @@ impl Cms { /// A cached 3-D lookup table implementing [`Cms::proof_srgb`] for 8-bit pixels. pub fn proof_lut(&self, proof: &ProofSetup) -> Arc { let working = self.working.as_ref().map(|w| &w.settings); - let key = format!("{:?}|{working:?}|{:?}|{:?}|{}", self.settings, proof.target, proof.intent, proof.simulate_paper); + let key = format!( + "{:?}|{working:?}|{:?}|{:?}|{}|{}|{}", + self.settings, proof.target, proof.intent, proof.simulate_paper, proof.preserve_numbers, proof.simulate_black + ); let mut cache = PROOF_CACHE.lock().unwrap_or_else(|e| e.into_inner()); if let Some((_, l)) = cache.iter().find(|(k, _)| *k == key) { return l.clone(); @@ -860,6 +948,8 @@ pub enum ProofTarget { WorkingCmyk, /// A specific CMYK profile (Customize…). Cmyk(String), + /// A specific RGB profile (Customize…): the color as that RGB device shows it. + Rgb(String), /// Legacy Macintosh RGB (Gamma 1.8). LegacyMacRgb, /// Internet Standard RGB (sRGB). @@ -879,6 +969,9 @@ impl ProofTarget { if let Some(p) = s.strip_prefix("cmyk:") { return Some(ProofTarget::Cmyk(p.to_string())); } + if let Some(p) = s.strip_prefix("rgb:") { + return Some(ProofTarget::Rgb(p.to_string())); + } Some(match s { "workingCmyk" | "cmyk" => ProofTarget::WorkingCmyk, "legacyMacRgb" | "macRgb" => ProofTarget::LegacyMacRgb, @@ -894,6 +987,7 @@ impl ProofTarget { match self { ProofTarget::WorkingCmyk => "workingCmyk".into(), ProofTarget::Cmyk(p) => format!("cmyk:{p}"), + ProofTarget::Rgb(p) => format!("rgb:{p}"), ProofTarget::LegacyMacRgb => "legacyMacRgb".into(), ProofTarget::Srgb => "srgb".into(), ProofTarget::MonitorRgb => "monitorRgb".into(), @@ -917,6 +1011,15 @@ pub struct ProofSetup { /// Simulate Paper Color (absolute colorimetric display of the press). #[serde(default)] pub simulate_paper: bool, + /// Preserve CMYK Numbers (a CMYK device) or Preserve RGB Numbers (an RGB device): the colors' + /// numbers go to the device unchanged instead of being converted into its space with + /// `intent`. + #[serde(default)] + pub preserve_numbers: bool, + /// Simulate Black Ink: the press black shows as the dark gray it prints (a CMYK device; implied + /// by `simulate_paper`). + #[serde(default)] + pub simulate_black: bool, /// Separations Preview: names of the visible plates ("Cyan", "Magenta", "Yellow", "Black", /// spot swatch names). `None` = normal composite proof. #[serde(default, skip_serializing_if = "Option::is_none")] diff --git a/crates/color/src/cms/tests.rs b/crates/color/src/cms/tests.rs index 836ff9fdb6..853dfb4637 100644 --- a/crates/color/src/cms/tests.rs +++ b/crates/color/src/cms/tests.rs @@ -194,6 +194,100 @@ fn colour_blindness_proofs() { assert_eq!(ProofTarget::parse(&ProofTarget::Cmyk("X".into()).id()), Some(ProofTarget::Cmyk("X".into()))); } +/// Proof Setup › Customize: Simulate Black Ink shows the press black of a CMYK device as the dark +/// gray it prints, where the proof otherwise shows it as black; Simulate Paper Color shows it so +/// as well, on the paper's color. +#[test] +fn simulate_black_ink_shows_the_press_black_as_gray() { + let c = cms(); + let device = ProofSetup { target: ProofTarget::Cmyk(GENERIC_CMYK.into()), ..Default::default() }; + let black = ProofSetup { simulate_black: true, ..device.clone() }; + let paper = ProofSetup { simulate_paper: true, ..device.clone() }; + let plain = c.proof_srgb([0.0; 3], &device); + let gray = c.proof_srgb([0.0; 3], &black); + assert!(plain.iter().all(|v| *v < 0.02), "black stays black: {plain:?}"); + assert!(gray.iter().all(|v| *v > 0.05), "the press black shows as a gray: {gray:?}"); + assert_eq!(c.proof_srgb([1.0; 3], &black), [1.0; 3], "the paper stays white"); + assert!(c.proof_srgb([0.0; 3], &paper).iter().all(|v| *v > 0.05)); + // The working CMYK target, and the inks Separations Preview shows, follow it too. + let working = ProofSetup { target: ProofTarget::WorkingCmyk, simulate_black: true, ..Default::default() }; + assert_eq!(c.proof_srgb([0.0; 3], &working), gray); + assert!(c.proof_cmyk_to_srgb([0.0, 0.0, 0.0, 1.0], &black)[0] > c.proof_cmyk_to_srgb([0.0, 0.0, 0.0, 1.0], &device)[0] + 0.05); + // The table the canvas draws through is made for each setting. + assert!(de(c.proof_lut(&black).apply([0.0; 3]), gray) < 2.5); + assert!(de(c.proof_lut(&device).apply([0.0; 3]), plain) < 2.5); +} + +/// Preserve CMYK Numbers sends the color's CMYK numbers in the document's space to the simulated +/// device unchanged: with Device CMYK as the working space, K50 shows as the simulated press +/// prints K50 (darker, with its dot gain). Without it the color is converted into the device's +/// space with the intent, and the gray looks as it does on screen. +#[test] +fn preserve_cmyk_numbers_sends_the_numbers_unchanged() { + let dev = Cms::new(&ColorSettings { cmyk: DEVICE_CMYK.into(), ..Default::default() }).unwrap(); + let press = Cms::new(&ColorSettings::default()).unwrap(); + let k50 = [0.0, 0.0, 0.0, 0.5]; + let gray = dev.cmyk_to_srgb(k50, false); + let device = ProofSetup { target: ProofTarget::Cmyk(GENERIC_CMYK.into()), ..Default::default() }; + let preserved = dev.proof_srgb(gray, &ProofSetup { preserve_numbers: true, ..device.clone() }); + let want = press.cmyk_to_srgb(k50, false); + assert!(de(preserved, want) < 0.5, "{preserved:?} vs {want:?}"); + let converted = dev.proof_srgb(gray, &device); + assert!(de(converted, gray) < 1.5, "{converted:?} vs {gray:?}"); + assert!(de(converted, preserved) > 3.0, "{converted:?} vs {preserved:?}"); + // With the numbers preserved the intent is not used. + let perceptual = ProofSetup { intent: Intent::Perceptual, preserve_numbers: true, ..device }; + assert_eq!(dev.proof_srgb(gray, &perceptual), preserved); +} + +/// An RGB profile as the device to simulate: with Preserve RGB Numbers the document's RGB numbers +/// show as that device shows them (sRGB numbers on a Display P3 device look more saturated); +/// without it a color the device can show looks the same, and one it can't show is clipped. +#[test] +fn rgb_device_proofs_show_the_device_numbers() { + let c = cms(); + let p3 = ProofSetup { target: ProofTarget::Rgb(DISPLAY_P3.into()), ..Default::default() }; + assert_eq!(ProofTarget::parse(&p3.target.id()), Some(p3.target.clone())); + assert_eq!(p3.target.id(), format!("rgb:{DISPLAY_P3}")); + assert!(!p3.target.is_cmyk()); + let red = [0.7, 0.3, 0.25]; + let converted = c.proof_srgb(red, &p3); + assert!(de(converted, red) < 1.0, "{converted:?}"); + let preserved = c.proof_srgb(red, &ProofSetup { preserve_numbers: true, ..p3.clone() }); + assert!(preserved[0] > red[0] + 0.02 && preserved[1] < red[1] - 0.02, "{preserved:?}"); + // An RGB color's own numbers give the same proof. + let own = c.proof_color(&Color::rgb(red[0], red[1], red[2]), &ProofSetup { preserve_numbers: true, ..p3.clone() }); + assert!(de(own, preserved) < 0.01, "{own:?} vs {preserved:?}"); + // sRGB numbers on an sRGB device: as they are either way. + let srgb = ProofSetup { target: ProofTarget::Rgb(SRGB.into()), preserve_numbers: true, ..Default::default() }; + assert!(de(c.proof_srgb(red, &srgb), red) < 0.01); + // A wider working space's numbers on an sRGB device: its green clips to sRGB green. + let wide = Cms::new(&ColorSettings { rgb: WIDE_GAMUT_RGB.into(), ..Default::default() }).unwrap(); + let green = wide.rgb_to_srgb([0.2, 0.8, 0.2]); + let shown = wide.proof_srgb(green, &srgb); + assert!(de(shown, green) > 3.0, "the wide space's numbers show as sRGB numbers: {shown:?}"); + // A profile that is gone leaves the colors as they are. + let gone = ProofSetup { target: ProofTarget::Rgb("Nope".into()), ..Default::default() }; + assert_eq!(c.proof_srgb(red, &gone), red); +} + +/// A CMYK device whose profile is not loaded leaves a color as the screen shows it, with Preserve +/// CMYK Numbers on as well as off, the same as for a pixel of that color. +#[test] +fn missing_cmyk_device_leaves_colors_as_they_are() { + let c = cms(); + let gone = ProofSetup { target: ProofTarget::Cmyk("Nope".into()), preserve_numbers: true, ..Default::default() }; + let blue = Color::rgb(0.0, 0.0, 1.0); + let shown = c.display_rgb(&blue); + assert_eq!(c.proof_color(&blue, &gone), shown); + assert_eq!(c.proof_srgb(shown, &gone), shown); + let off = ProofSetup { preserve_numbers: false, ..gone.clone() }; + assert_eq!(c.proof_color(&blue, &off), shown); + // A CMYK color keeps its inks' display color. + let ink = Color::Cmyk { c: 0.2, m: 0.7, y: 0.1, k: 0.05 }; + assert!(de(c.proof_color(&ink, &gone), c.display_rgb(&ink)) < 0.01); +} + /// The expected colors were computed separately with NumPy from the same published inputs (linear /// sRGB to XYZ from IEC 61966-2-1, Smith & Pokorny's XYZ to LMS, Judd-Vos XYZ at 485 nm and 660 nm), /// following Brettel, Viénot & Mollon (1997) with the display's white as the neutral axis. diff --git a/crates/color/src/cms/tests_icc.rs b/crates/color/src/cms/tests_icc.rs index 2c1d96638b..3506bcb856 100644 --- a/crates/color/src/cms/tests_icc.rs +++ b/crates/color/src/cms/tests_icc.rs @@ -187,6 +187,25 @@ fn black_point_compensation_maps_the_darkest_ink_to_rgb_black() { assert_eq!(abs(true), abs(false)); } +/// A loaded ICC CMYK profile as Proof Setup's device shows its darkest ink with the settings' +/// black-point compensation, as the working CMYK proof of the same profile does, and Simulate +/// Black Ink shows it as the lighter gray the press prints. +#[test] +fn simulate_black_ink_shows_a_loaded_cmyk_profiles_black_as_gray() { + let c = icc_cmyk(true); + let k100 = [0.0, 0.0, 0.0, 1.0]; + let device = ProofSetup { target: ProofTarget::Cmyk(c.settings().cmyk.clone()), ..Default::default() }; + let plain = c.proof_cmyk_to_srgb(k100, &device); + let working = c.proof_cmyk_to_srgb(k100, &ProofSetup { target: ProofTarget::WorkingCmyk, ..Default::default() }); + assert!(plain.iter().zip(working).all(|(a, b)| (a - b).abs() < 0.01), "device {plain:?}, working {working:?}"); + let black = c.proof_cmyk_to_srgb(k100, &ProofSetup { simulate_black: true, ..device.clone() }); + assert!(plain.iter().zip(black).all(|(a, b)| b > a + 0.03), "black ink {black:?}, without {plain:?}"); + // Without black-point compensation the device shows the darkest ink as the press prints it. + let off = icc_cmyk(false); + let plain_off = off.proof_cmyk_to_srgb(k100, &ProofSetup { target: ProofTarget::Cmyk(off.settings().cmyk.clone()), ..Default::default() }); + assert!(plain_off.iter().zip(black).all(|(a, b)| (a - b).abs() < 0.02), "without compensation {plain_off:?}, black ink {black:?}"); +} + /// #1584: every built-in profile (RGB, CMYK and gray) has each tag on a 4-byte boundary and a size /// that is a multiple of 4 (ICC.1 §7.1.2), and still reads back as the same space. #[test] diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs index 05b7f4839c..b88253b714 100644 --- a/crates/color/src/gradient.rs +++ b/crates/color/src/gradient.rs @@ -621,7 +621,8 @@ impl Gradient { } /// Stops expanded so that midpoints are represented as explicit stops (for renderers without /// midpoints), and a Perceptual gradient's segments as stops on its curve (for renderers that - /// mix linearly; within [`PERCEPTUAL_TOLERANCE`] of it). + /// mix linearly; within [`PERCEPTUAL_TOLERANCE`] of it). A stop between two stops of the same + /// color is that color, as it is, so paper white or a tint stays exact. pub fn expanded_stops(&self) -> Vec<(f32, Color, f32)> { self.expanded().map(|(t, c, o, _)| (t, c, o)).collect() } @@ -638,6 +639,9 @@ impl Gradient { // Otherwise (repeated or unsorted offsets) each midpoint is looked up as `sample` would // find it, but by binary search: a scan of all the stops per midpoint cost their square. let reach = if increasing || !self.method.is_classic() { None } else { Some(StopReach::new(&self.stops)) }; + // Two stops of the same color mix to that color, as it is: a mix through display RGB or + // OKLab would change its model or round its numbers. + let mix = move |a: &Color, b: &Color, v| if a == b { *a } else { self.method.mix(a, b, v) }; self.stops.iter().enumerate().flat_map(move |(i, s)| { let next = self.stops.get(i + 1); let off_centre = (s.midpoint - 0.5).abs() > 1e-3; @@ -646,7 +650,6 @@ impl Gradient { let t = s.offset + (n.offset - s.offset) * s.midpoint; // Mixed from the two stops it lies between, as `sample` would: searching all the // stops again for each midpoint made many stops cost their square. - let mix = |a: &Color, b: &Color, v| self.method.mix(a, b, v); let (c, o) = match &reach { Some(reach) => reach.sample_with(&self.stops, t, &mix), None => between(s, n, t, &mix), @@ -661,7 +664,7 @@ impl Gradient { let mid = v == 0.5; let t = curve_offset(s, n, v); let o = s.opacity + (n.opacity - s.opacity) * v; - (t, self.method.mix(&s.color, &n.color, v), o, (mid && off_centre).then_some(s.midpoint), None) + (t, mix(&s.color, &n.color, v), o, (mid && off_centre).then_some(s.midpoint), None) }) }); std::iter::once((s.offset, s.color, s.opacity, None, Some(i))).chain(classic).chain(perceptual.into_iter().flatten()) diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index fa8cd564f2..c3d74615ae 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -10,6 +10,7 @@ pub mod freeform; pub mod gradient; pub mod harmony; pub mod libraries; +pub mod oklab; pub mod palette_io; pub mod recolor; pub mod swatch; @@ -340,6 +341,49 @@ pub fn hsb_to_rgb([h, s, v]: [f32; 3]) -> [f32; 3] { [r + m, g + m, b + m] } +/// HSL (hue in degrees 0..360, saturation and lightness 0..1) of RGB numbers 0..1, with no color +/// conversion, as CSS Color 4 converts sRGB to HSL +/// (). The hue is 0 while the saturation is +/// powerless, and a color outside 0..1 that gives a negative saturation turns its hue by 180°. As in +/// the specification's conversion, a lightness of 0.00001 or less, a lightness less than 0.00001 +/// below 1, or a saturation of 0.00001 or less reads as a gray. +pub fn rgb_to_hsl([r, g, b]: [f32; 3]) -> [f32; 3] { + const EPSILON: f32 = 1e-5; + let max = r.max(g).max(b); + let min = r.min(g).min(b); + let d = max - min; + let l = (max + min) / 2.0; + if d <= 0.0 { + return [0.0, 0.0, l]; + } + let mut s = if l.abs() <= EPSILON || (1.0 - l).abs() < EPSILON { 0.0 } else { (max - l) / l.min(1.0 - l) }; + let mut h = rgb_to_hsb([r, g, b])[0]; + if s < 0.0 { + h += 180.0; + s = -s; + } + if s <= EPSILON { + return [0.0, 0.0, l]; + } + let h = h.rem_euclid(360.0); + [if h >= 360.0 { 0.0 } else { h }, s, l] +} + +/// RGB numbers 0..1 of HSL `[h, s, l]` (hue in degrees, saturation and lightness 0..1), as CSS +/// Color 4 converts HSL to sRGB (): the inverse of +/// [`rgb_to_hsl`]. A hue outside 0..360 wraps into that range before the conversion, so -120° +/// gives the color of 240° and a hue of 10,000,000,000° the color of 280°. The specification's +/// sample code uses JavaScript's remainder operator and gives a different color for a negative hue. +pub fn hsl_to_rgb([h, s, l]: [f32; 3]) -> [f32; 3] { + let h = h.rem_euclid(360.0); + let a = s * l.min(1.0 - l); + let f = |n: f32| { + let k = (n + h / 30.0).rem_euclid(12.0); + l - a * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0) + }; + [f(0.0), f(8.0), f(4.0)] +} + /// `new` expressed in the colour model of `orig` ([`Color::in_model`]): results of colour operations /// (harmonies, blends, inversions, recolouring) keep the model of the colour they came from. pub fn keep_model(orig: Color, new: Color) -> Color { @@ -499,6 +543,59 @@ mod tests { } } + /// The HSL examples of CSS Color 4, section 7 (), + /// the first six rows, and two hues outside 0..360 that wrap into that range. + #[test] + fn hsl_follows_css_color_4() { + for (hsl, hex) in [ + ([0.0, 1.0, 0.5], "#ff0000"), + ([120.0, 1.0, 0.5], "#00ff00"), + ([120.0, 1.0, 0.25], "#008000"), + ([120.0, 1.0, 0.75], "#80ff80"), + ([240.0, 1.0, 0.5], "#0000ff"), + ([60.0, 1.0, 0.5], "#ffff00"), + ([360.0, 1.0, 0.5], "#ff0000"), + ([-120.0, 1.0, 0.5], "#0000ff"), + ] { + let [r, g, b] = hsl_to_rgb(hsl); + assert_eq!(Color::rgb(r, g, b).to_hex(), hex, "{hsl:?}"); + } + let [h, s, l] = rgb_to_hsl([1.0, 0.5, 0.0]); + assert!((h - 30.0).abs() < 1e-4 && (s - 1.0).abs() < 1e-6 && (l - 0.5).abs() < 1e-6, "{h} {s} {l}"); + let [h, s, l] = rgb_to_hsl(Color::rgb8(255, 128, 0).to_rgb_uncalibrated()); + assert!((h - 30.0).abs() < 0.2 && (s - 1.0).abs() < 1e-6 && (l - 0.5).abs() < 1e-3, "{h} {s} {l}"); + // A gray has no hue: the hue is 0 and the saturation 0, at any lightness. + for v in [0.0, 0.25, 0.5, 1.0] { + assert_eq!(rgb_to_hsl([v, v, v]), [0.0, 0.0, v]); + } + // Black and white keep any hue and saturation they are given. + assert_eq!(hsl_to_rgb([200.0, 0.7, 0.0]), [0.0, 0.0, 0.0]); + assert_eq!(hsl_to_rgb([200.0, 0.7, 1.0]), [1.0, 1.0, 1.0]); + // A color past the gamut that gives a negative saturation turns its hue by 180°. + let [h, s, _] = rgb_to_hsl([1.2, 1.5, 1.4]); + assert!(s > 0.0 && (h - (160.0 + 180.0)).abs() < 1e-3, "{h} {s}"); + // A huge hue wraps before the channels are worked out: 10,000,000,000° is 280°. + let (huge, wrapped) = (hsl_to_rgb([10_000_000_000.0, 1.0, 0.5]), hsl_to_rgb([280.0, 1.0, 0.5])); + assert!((0..3).all(|i| (huge[i] - wrapped[i]).abs() < 1e-6), "{huge:?} {wrapped:?}"); + } + + /// The 216 web colors go to HSL and back to the same 8-bit color. + #[test] + fn hsl_roundtrip() { + let steps = [0x00, 0x33, 0x66, 0x99, 0xcc, 0xff]; + for r in steps { + for g in steps { + for b in steps { + let c = Color::rgb8(r, g, b); + let [h, s, l] = rgb_to_hsl(c.to_rgb_uncalibrated()); + assert!((0.0..360.0).contains(&h) && (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&l), "{}", c.to_hex()); + let back = hsl_to_rgb([h, s, l]).map(|v| (v * 255.0).round() as u8); + assert_eq!(back, [r, g, b], "{}", c.to_hex()); + } + } + } + } + #[test] fn cmyk_conversions() { assert_eq!(Color::cmyk(0.0, 0.0, 0.0, 1.0).to_rgb_uncalibrated(), [0.0, 0.0, 0.0]); diff --git a/crates/color/src/libraries.rs b/crates/color/src/libraries.rs index 5fc952a061..c2946d92a2 100644 --- a/crates/color/src/libraries.rs +++ b/crates/color/src/libraries.rs @@ -99,18 +99,24 @@ pub fn builtin_library(id: &str) -> Option> { // ---------- colour construction ---------- -/// sRGB (0..=1, gamma encoded) of OKLab `(l, a, b)`, unclamped. +/// sRGB (0..=1, gamma encoded) of OKLab `(l, a, b)`, unclamped. A linear channel below +/// −0.0031308 is encoded with the curve's sign turned, as CSS Color 4's extended sRGB does +/// (). pub(crate) fn oklab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] { + oklab_to_linear_srgb(l, a, b).map(|v| if v.abs() <= 0.003_130_8 { 12.92 * v } else { v.signum() * (1.055 * v.abs().powf(1.0 / 2.4) - 0.055) }) +} + +/// Linear sRGB of OKLab `(l, a, b)`, unclamped. +pub(crate) fn oklab_to_linear_srgb(l: f64, a: f64, b: f64) -> [f64; 3] { let l_ = l + 0.396_337_777_4 * a + 0.215_803_757_3 * b; let m_ = l - 0.105_561_345_8 * a - 0.063_854_172_8 * b; let s_ = l - 0.089_484_177_5 * a - 1.291_485_548_0 * b; let (l3, m3, s3) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_); - let lin = [ + [ 4.076_741_662_1 * l3 - 3.307_711_591_3 * m3 + 0.230_969_929_2 * s3, -1.268_438_004_6 * l3 + 2.609_757_401_1 * m3 - 0.341_319_396_5 * s3, -0.004_196_086_3 * l3 - 0.703_418_614_7 * m3 + 1.707_614_701_0 * s3, - ]; - lin.map(|v| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }) + ] } /// OKLab `[l, a, b]` of a colour's display RGB. @@ -118,11 +124,13 @@ pub fn to_oklab(c: &Color) -> [f64; 3] { srgb_to_oklab(c.to_rgb_uncalibrated()) } -/// OKLab `[l, a, b]` of sRGB `rgb` (0..=1, gamma encoded). +/// OKLab `[l, a, b]` of sRGB `rgb` (0..=1, gamma encoded). A channel below −0.04045 is decoded +/// with the curve's sign turned, as CSS Color 4's extended sRGB does +/// (). pub(crate) fn srgb_to_oklab(rgb: [f32; 3]) -> [f64; 3] { let [r, g, b] = rgb.map(|v| { let v = f64::from(v); - if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + if v.abs() <= 0.040_45 { v / 12.92 } else { v.signum() * ((v.abs() + 0.055) / 1.055).powf(2.4) } }); let l = (0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b).cbrt(); let m = (0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b).cbrt(); diff --git a/crates/color/src/oklab.rs b/crates/color/src/oklab.rs new file mode 100644 index 0000000000..31500d1ac5 --- /dev/null +++ b/crates/color/src/oklab.rs @@ -0,0 +1,266 @@ +//! OKLCH, the polar form of Oklab, as CSS Color 4 defines it +//! (): lightness L from 0 to 1, chroma +//! C (CSS reads 100% as 0.4) and hue H in degrees from the positive `a` axis. The conversions take +//! and give gamma-encoded sRGB through the Oklab matrices of [`crate::libraries`]. + +use crate::libraries::{oklab_to_linear_srgb, oklab_to_srgb, srgb_to_oklab}; + +/// The chroma CSS reads as 100%. +pub const CHROMA_FULL: f64 = 0.4; + +/// Chroma at or below which the hue is powerless (CSS Color 4's ε); [`to_oklch`] gives hue 0 there. +pub const POWERLESS_CHROMA: f64 = 0.000_004; + +/// How far outside 0..=1 an sRGB component may be and still count as inside the gamut. +const GAMUT_SLACK: f64 = 1e-4; + +/// OKLCH `[l, c, h°]` of sRGB `rgb` (gamma encoded). Values outside 0..=1 are converted as they +/// are. The hue is in 0..360, and 0 while the chroma is powerless. +pub fn to_oklch(rgb: [f32; 3]) -> [f64; 3] { + let [l, a, b] = srgb_to_oklab(rgb); + let c = a.hypot(b); + if c <= POWERLESS_CHROMA { + return [l, 0.0, 0.0]; + } + [l, c, b.atan2(a).to_degrees().rem_euclid(360.0)] +} + +/// sRGB (gamma encoded) of OKLCH `(l, c, h°)`, unclamped. +pub fn oklch_to_srgb(l: f64, c: f64, h: f64) -> [f64; 3] { + let (sin, cos) = h.to_radians().sin_cos(); + oklab_to_srgb(l, c * cos, c * sin) +} + +/// Whether sRGB `rgb` lies inside the sRGB gamut. +pub fn in_srgb(rgb: [f64; 3]) -> bool { + rgb.iter().all(|v| (-GAMUT_SLACK..=1.0 + GAMUT_SLACK).contains(v)) +} + +/// The largest chroma sRGB holds at lightness `l` and hue `h°`: 0 at or outside black and white. +pub fn max_chroma(l: f64, h: f64) -> f64 { + largest_fitting_chroma(l, h, f64::INFINITY) +} + +/// The largest chroma no more than `limit` that sRGB holds at lightness `l` and hue `h°`: 0 at or +/// outside black and white. +/// +/// The chromas sRGB holds along the ray can come in several stretches: at the lightness and hue of +/// blue the ray leaves sRGB at a chroma of about 0.266 and comes back at blue itself, about 0.313, +/// and near black the gamut slack opens stretches of its own. Each linear sRGB channel is a cubic +/// in the chroma, so every stretch ends where a channel's cubic meets a bound of the gamut. The +/// search finds each such chroma between the cubic's turning points and takes the largest one that +/// fits. +fn largest_fitting_chroma(l: f64, h: f64, limit: f64) -> f64 { + if !(l > 0.0 && l < 1.0) || !h.is_finite() { + return 0.0; + } + let top = limit.min(0.5); + if top <= 0.0 { + return 0.0; + } + let fits = |c: f64| in_srgb(oklch_to_srgb(l, c, h)); + if fits(top) { + return top; + } + let (sin, cos) = h.to_radians().sin_cos(); + let lin = |c: f64| oklab_to_linear_srgb(l, c * cos, c * sin); + // The linear channels at chromas 0, s, 2s and 3s give each cubic's coefficients in t = c / s. + let s = top / 3.0; + let y = [lin(0.0), lin(s), lin(2.0 * s), lin(3.0 * s)]; + let bounds = [-GAMUT_SLACK / 12.92, ((1.0 + GAMUT_SLACK + 0.055) / 1.055).powf(2.4)]; + let mut ends = vec![0.0]; + for ch in 0..3 { + let [y0, y1, y2, y3] = [y[0][ch], y[1][ch], y[2][ch], y[3][ch]]; + let (d1, d2, d3) = (y1 - y0, y2 - 2.0 * y1 + y0, y3 - 3.0 * y2 + 3.0 * y1 - y0); + let k = [y0, d1 - d2 / 2.0 + d3 / 3.0, d2 / 2.0 - d3 / 2.0, d3 / 6.0]; + let p = |t: f64| ((k[3] * t + k[2]) * t + k[1]) * t + k[0]; + // The cubic rises or falls on each stretch between its turning points. + let mut cuts = vec![0.0, 3.0]; + cuts.extend(turning_points(3.0 * k[3], 2.0 * k[2], k[1]).into_iter().filter(|t| *t > 0.0 && *t < 3.0)); + cuts.sort_by(f64::total_cmp); + ends.extend(cuts.iter().map(|t| t * s)); + for w in cuts.windows(2) { + for bound in bounds { + let (mut a, mut b) = (w[0], w[1]); + let fa = p(a) - bound; + if fa * (p(b) - bound) > 0.0 { + continue; + } + for _ in 0..60 { + let mid = (a + b) / 2.0; + if (p(mid) - bound) * fa > 0.0 { a = mid } else { b = mid } + } + ends.extend([a * s, b * s]); + } + } + } + ends.sort_by(|a, b| b.total_cmp(a)); + ends.into_iter().flat_map(|c| [c, c - 1e-9]).find(|c| (0.0..=top).contains(c) && fits(*c)).unwrap_or(0.0) +} + +/// The real roots of `a t² + b t + c`. +fn turning_points(a: f64, b: f64, c: f64) -> Vec { + if a.abs() < 1e-15 { + return if b.abs() < 1e-15 { Vec::new() } else { vec![-c / b] }; + } + let disc = b * b - 4.0 * a * c; + if disc < 0.0 { + return Vec::new(); + } + let r = disc.sqrt(); + vec![(-b - r) / (2.0 * a), (-b + r) / (2.0 * a)] +} + +/// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered: +/// a color outside sRGB keeps its lightness and hue and takes the largest chroma below it that +/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more. +pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) { + let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) }; + let c = if c.is_nan() { 0.0 } else { c.max(0.0) }; + let h = if h.is_finite() { h } else { 0.0 }; + let exact = oklch_to_srgb(l, c, h); + let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, largest_fitting_chroma(l, h, c), h), true) }; + (rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn eight(rgb: [f32; 3]) -> [u8; 3] { + rgb.map(|v| (v * 255.0).round() as u8) + } + + #[test] + fn red_has_the_oklch_of_the_oklab_matrices_and_converts_back() { + let [l, c, h] = to_oklch([1.0, 0.0, 0.0]); + assert!((l - 0.6280).abs() < 5e-5 && (c - 0.2577).abs() < 5e-5 && (h - 29.23).abs() < 5e-3, "{l} {c} {h}"); + let (rgb, lowered) = from_oklch(l, c, h); + assert_eq!((eight(rgb), lowered), ([255, 0, 0], false)); + } + + /// CSS Color 4's examples convert to the hue its oklab() and oklch() forms give. + #[test] + fn the_polar_form_matches_the_css_examples() { + for ([l, a, b], [cl, cc, ch]) in + [([0.40101, 0.1147, 0.0453], [0.40101, 0.12332, 21.555]), ([0.65125, -0.0320, 0.1274], [0.65125, 0.13138, 104.097])] + { + let rgb = oklab_to_srgb(l, a, b).map(|v| v as f32); + let [ol, oc, oh] = to_oklch(rgb); + assert!((ol - cl).abs() < 1e-4 && (oc - cc).abs() < 1e-4 && (oh - ch).abs() < 0.05, "{ol} {oc} {oh}"); + } + } + + #[test] + fn the_216_web_colors_round_trip() { + let steps = [0u8, 0x33, 0x66, 0x99, 0xcc, 0xff]; + for r in steps { + for g in steps { + for b in steps { + let rgb = [r, g, b].map(|v| f32::from(v) / 255.0); + let [l, c, h] = to_oklch(rgb); + assert_eq!(eight(from_oklch(l, c, h).0), [r, g, b], "{l} {c} {h}"); + } + } + } + } + + #[test] + fn grays_have_no_chroma_and_hue_zero() { + for v in [0.0, 0.5, 1.0] { + let [_, c, h] = to_oklch([v, v, v]); + assert!(c <= POWERLESS_CHROMA && h == 0.0, "{c} {h}"); + } + } + + /// A chroma past the gamut gives a color inside it with the same lightness and hue, and says so. + #[test] + fn a_chroma_past_the_gamut_is_lowered_keeping_lightness_and_hue() { + let (l, h) = (0.7, 150.0); + let max = max_chroma(l, h); + assert!(max > 0.05 && max < CHROMA_FULL, "{max}"); + assert!(in_srgb(oklch_to_srgb(l, max, h)) && !in_srgb(oklch_to_srgb(l, max + 1e-3, h))); + let (rgb, lowered) = from_oklch(l, CHROMA_FULL, h); + assert!(lowered); + let [ol, oc, oh] = to_oklch(rgb); + assert!((ol - l).abs() < 2e-3 && (oh - h).abs() < 1.0 && (oc - max).abs() < 2e-3, "{ol} {oc} {oh}"); + assert!(!from_oklch(l, max * 0.5, h).1); + } + + /// At the lightness and hue of blue the ray leaves sRGB and comes back at blue itself, so the + /// largest chroma is blue's, and a chroma past it gives blue. + #[test] + fn the_largest_chroma_at_blues_hue_is_blues() { + let [l, c, h] = to_oklch([0.0, 0.0, 1.0]); + let max = max_chroma(l, h); + assert!((max - c).abs() < 1e-4 && in_srgb(oklch_to_srgb(l, max, h)), "{max} {c}"); + let (rgb, lowered) = from_oklch(l, CHROMA_FULL, h); + assert_eq!((eight(rgb), lowered), ([0, 0, 255], true)); + // A chroma between the two stretches takes the end of the first one, inside sRGB. + let (rgb, lowered) = from_oklch(l, 0.29, h); + let [_, gc, _] = to_oklch(rgb); + assert!(lowered && gc < 0.27 && in_srgb(oklch_to_srgb(l, gc, h)), "{gc}"); + // A hue just past blue's: a narrow second stretch ends just below the line from black to blue. + let (l, h) = (0.44, 264.06); + let max = max_chroma(l, h); + assert!(max > 0.304 && max < 0.305 && in_srgb(oklch_to_srgb(l, max, h)), "{max}"); + let [_, got, _] = to_oklch(from_oklch(l, 0.35, h).0); + assert!(got > 0.303, "{got}"); + // A darker blue on the line from black to blue. + let [l, c, h] = to_oklch([0.0, 0.0, 0.25]); + assert!((max_chroma(l, h) - c).abs() < 1e-4, "{} {c}", max_chroma(l, h)); + } + + /// Just below blue's lightness the line from black to blue passes a chroma of 0.3125, where a + /// search from 0 to 0.5 lands first. A chroma asked for below that line still gives a color + /// inside sRGB with the lightness and hue asked for. + #[test] + fn a_chroma_below_the_line_from_black_to_blue_stays_inside_srgb() { + let [bl, bc, h] = to_oklch([0.0, 0.0, 1.0]); + let l = bl * 0.3125 / bc; + let (rgb, lowered) = from_oklch(l, 0.29, h); + let [gl, gc, gh] = to_oklch(rgb); + assert!(lowered && gc < 0.29 && in_srgb(oklch_to_srgb(l, gc, h)), "{gc}"); + assert!((gl - l).abs() < 2e-3 && (gh - h).abs() < 1.0, "{gl} {gh}"); + } + + /// sRGB channels below 0 go through the transfer curve with its sign turned, as CSS Color 4's + /// extended sRGB does, in both directions. + #[test] + fn negative_channels_use_the_signed_transfer_curve() { + let linear = -((0.5_f64 + 0.055) / 1.055).powf(2.4); + let [l, c, _] = to_oklch([-0.5; 3]); + assert!((l - linear.cbrt()).abs() < 1e-4 && c <= POWERLESS_CHROMA, "{l} {c}"); + for v in oklch_to_srgb(linear.cbrt(), 0.0, 0.0) { + assert!((v + 0.5).abs() < 1e-4, "{v}"); + } + // Small values near 0 keep the straight part of the curve. + let [l, _, _] = to_oklch([-0.01; 3]); + assert!((l - (-0.01_f64 / 12.92).cbrt()).abs() < 1e-4, "{l}"); + } + + /// The largest chroma fits and is at least the largest one a scan in steps of 0.0005 finds, at + /// every hue and at lightnesses near black too, where the ray can come back into sRGB away from + /// any primary color's hue (L 0.02 and H 242° fit up to about 0.022 after leaving near 0.012). + #[test] + fn the_largest_chroma_is_never_below_a_scan_of_the_ray() { + let scan = |l: f64, h: f64| (0..=1000).map(|i| f64::from(i) * 0.0005).filter(|c| in_srgb(oklch_to_srgb(l, *c, h))).fold(0.0, f64::max); + assert!(max_chroma(0.02, 242.0) > 0.02, "{}", max_chroma(0.02, 242.0)); + for l in [0.005, 0.02, 0.05, 0.1, 0.3, 0.44, 0.6, 0.8, 0.95, 0.99] { + for h in (0..72).map(|i| f64::from(i) * 5.0 + 2.0) { + let max = max_chroma(l, h); + assert!(in_srgb(oklch_to_srgb(l, max, h)) && max >= scan(l, h), "L {l} H {h}: {max} < {}", scan(l, h)); + } + } + } + + #[test] + fn black_white_and_bad_numbers_hold_no_chroma() { + assert_eq!(max_chroma(0.0, 30.0), 0.0); + assert_eq!(max_chroma(1.0, 30.0), 0.0); + assert_eq!(max_chroma(f64::NAN, 30.0), 0.0); + assert_eq!(max_chroma(0.5, f64::INFINITY), 0.0); + assert_eq!(eight(from_oklch(f64::NAN, f64::NAN, f64::NAN).0), [0, 0, 0]); + assert_eq!(eight(from_oklch(2.0, -1.0, 0.0).0), [255, 255, 255]); + } +} diff --git a/crates/doc/src/appearance/layers.rs b/crates/doc/src/appearance/layers.rs index 1728b7e323..11d2b0664d 100644 --- a/crates/doc/src/appearance/layers.rs +++ b/crates/doc/src/appearance/layers.rs @@ -195,12 +195,14 @@ impl StrokeLayer { wheel: None, } } + /// The least weight an arrowhead is drawn at, in points ([`Self::arrow_weight`]). + pub const LEAST_ARROW_WEIGHT: f64 = 0.25; /// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least - /// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide (see + /// [`Self::LEAST_ARROW_WEIGHT`]. A head of weight `hw` fits a box about `4·hw` long and wide (see /// [`Arrowhead::reach`] and [`Arrowhead::half_width`]). pub fn arrow_weight(&self, end: bool) -> f64 { let pct = if end { self.arrow_scale.1 } else { self.arrow_scale.0 }; - (self.width * pct / 100.0).max(0.25) + (self.width * pct / 100.0).max(Self::LEAST_ARROW_WEIGHT) } /// How far the start (`end == false`) or end arrowhead can reach from its end point (0 /// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap. diff --git a/crates/doc/src/appearance/stroke_style.rs b/crates/doc/src/appearance/stroke_style.rs index 18b226c676..7a39d6cbb2 100644 --- a/crates/doc/src/appearance/stroke_style.rs +++ b/crates/doc/src/appearance/stroke_style.rs @@ -68,6 +68,10 @@ pub struct CustomArrowhead { /// across it, positive to the right of the direction the head points. A head is 4 units wide, /// as the built-in heads are, and a unit is the head's weight. pub path: PathData, + /// Where the stroke ends under the head, in head units back from the tip, when the head says + /// so ([`Self::with_stop`]); `None`: halfway along its length ([`Self::stop`]). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stop: Option, } #[derive(Deserialize)] @@ -75,11 +79,17 @@ struct CustomArrowheadData { name: String, #[serde(default)] path: PathData, + #[serde(default)] + stop: Option, } impl From for CustomArrowhead { fn from(d: CustomArrowheadData) -> Self { - CustomArrowhead::new(d.name, d.path) + let head = CustomArrowhead::new(d.name, d.path); + match d.stop { + Some(stop) => head.with_stop(stop), + None => head, + } } } @@ -94,7 +104,17 @@ impl CustomArrowhead { /// than [`Self::MAX_UNITS`] from the tip is dropped: the head then draws nothing. pub fn new(name: String, path: PathData) -> Self { let path = if Self::fits(&path) { path } else { PathData::default() }; - CustomArrowhead { name, path } + CustomArrowhead { name, path, stop: None } + } + /// The head with the stroke ending `stop` head units back from its tip (an arrowhead an + /// Illustrator file defines draws its line to a point of its own). A stop that is not finite, + /// is negative or is farther than [`Self::MAX_UNITS`] is left out: the stroke then ends + /// halfway along the head. + /// A head whose outline was dropped ([`Self::new`]) draws nothing and keeps no stop. + pub fn with_stop(mut self, stop: f64) -> Self { + let fits = !self.path.subpaths.is_empty() && stop.is_finite() && (0.0..=Self::MAX_UNITS).contains(&stop); + self.stop = fits.then_some(stop); + self } /// Whether outline `path` has at most [`Self::MAX_ANCHORS`] anchors and as many subpaths, with /// finite points within [`Self::MAX_UNITS`] only. @@ -116,10 +136,10 @@ impl CustomArrowhead { pub fn half_width(&self) -> f64 { self.bounds().map_or(0.0, |b| b.y0.abs().max(b.y1.abs())) } - /// Where the stroke ends under the head, in head units back from the tip: halfway along the - /// head's length. + /// Where the stroke ends under the head, in head units back from the tip: its own stop + /// ([`Self::with_stop`]), else halfway along the head's length. pub fn stop(&self) -> f64 { - self.bounds().map_or(0.0, |b| b.x1.max(0.0) / 2.0) + self.stop.unwrap_or_else(|| self.bounds().map_or(0.0, |b| b.x1.max(0.0) / 2.0)) } } diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs index caad4f6edc..ab0ba559f0 100644 --- a/crates/doc/src/appearance/tests.rs +++ b/crates/doc/src/appearance/tests.rs @@ -383,6 +383,15 @@ fn custom_arrowheads_carry_their_art_and_measure_it() { assert_eq!(head.half_width(), 2.0); let Arrowhead::Custom(c) = &head else { panic!("custom") }; assert_eq!(c.stop(), 1.5, "the line stops halfway along the head"); + // A head with a stop of its own (an Illustrator file's arrowhead) keeps it, saved and read back. + let stopped = (**c).clone().with_stop(0.5); + assert_eq!(stopped.stop(), 0.5); + let back: CustomArrowhead = serde_json::from_value(serde_json::to_value(&stopped).unwrap()).unwrap(); + assert_eq!(back, stopped); + assert!(!serde_json::to_string(&**c).unwrap().contains("stop"), "a head without one writes none"); + for odd in [f64::NAN, -0.5, CustomArrowhead::MAX_UNITS + 1.0] { + assert_eq!((**c).clone().with_stop(odd).stop(), 1.5, "{odd} is left out"); + } // Saved with the stroke, art and all, beside the built-in heads' names. let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0); (st.start_arrow, st.end_arrow) = (Some(Arrowhead::Triangle), Some(head.clone())); @@ -404,7 +413,7 @@ fn custom_arrowheads_out_of_bounds_draw_nothing() { let mut path = c.path.clone(); path.subpaths[0].anchors[1] = vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(1e9, 0.0)); // A file can hold what `new` drops: reading it drops it too. - let json = serde_json::to_value(CustomArrowhead { name: "Wedge".into(), path }).unwrap(); + let json = serde_json::to_value(CustomArrowhead { name: "Wedge".into(), path, stop: None }).unwrap(); let far: CustomArrowhead = serde_json::from_value(json).unwrap(); assert_eq!((far.name.as_str(), far.path.subpaths.len()), ("Wedge", 0)); assert_eq!((far.reach(), far.half_width(), far.stop()), (0.0, 0.0, 0.0)); @@ -415,7 +424,7 @@ fn custom_arrowheads_out_of_bounds_draw_nothing() { let mut hollow = c.path.clone(); hollow.subpaths.extend(std::iter::repeat_n(vectorcraft_geom::SubPath::new(vec![], false), CustomArrowhead::MAX_ANCHORS)); assert!(!CustomArrowhead::fits(&hollow), "too many subpaths"); - let json = serde_json::to_value(CustomArrowhead { name: "Hollow".into(), path: hollow }).unwrap(); + let json = serde_json::to_value(CustomArrowhead { name: "Hollow".into(), path: hollow, stop: None }).unwrap(); let hollow: CustomArrowhead = serde_json::from_value(json).unwrap(); assert!(hollow.path.subpaths.is_empty(), "too many subpaths, read back"); } diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index 9e78d17d4d..4d66f5d74c 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -124,6 +124,54 @@ impl ArrowStyle { } } +/// `arrowHead`: null, or a built-in stroke arrowhead by its name (`Barbed`, as `stroke.set` takes +/// it). A custom arrowhead and an unknown name are refused. +mod arrow_head { + use crate::Arrowhead; + use serde::de::{Error, IntoDeserializer, Visitor}; + use serde::{Deserialize, Deserializer}; + + pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + deserializer.deserialize_option(Name) + } + + /// Reads the name where it is, without a copy of its own. + struct Name; + + impl<'de> Visitor<'de> for Name { + type Value = Option; + + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a built-in stroke arrowhead name or null") + } + + fn visit_none(self) -> Result { + Ok(None) + } + + fn visit_unit(self) -> Result { + Ok(None) + } + + fn visit_some>(self, deserializer: D) -> Result { + deserializer.deserialize_str(self) + } + + fn visit_str(self, name: &str) -> Result { + // No built-in name is this long, so a longer one is refused without parsing it. + let parsed: Result = + if name.len() > 64 { Err(serde::de::value::Error::custom("too long")) } else { Arrowhead::deserialize(name.into_deserializer()) }; + match parsed { + Ok(head) if !matches!(head, Arrowhead::Custom(_)) => Ok(Some(head)), + _ => { + let shown: String = name.chars().take(64).collect(); + Err(E::custom(format!("Unknown arrowhead {shown}: a built-in stroke arrowhead name or null"))) + } + } + } + } +} + /// Where the label sits across the dimension line. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] @@ -157,6 +205,12 @@ pub struct DimensionOptions { pub line_type: LineType, pub line_color: [u8; 3], pub arrow_style: ArrowStyle, + /// A built-in stroke arrowhead drawn at both ends in place of `arrow_style`'s head. Versions + /// that have the stroke arrowhead but do not read this keep the saved arrows until they draw + /// the dimension again, and then draw `arrow_style`. Versions without the stroke arrowhead do + /// not open the file. + #[serde(deserialize_with = "arrow_head::deserialize", skip_serializing_if = "Option::is_none")] + pub arrow_head: Option, pub arrow_scale: f64, pub extension_weight: f64, pub extension_type: LineType, @@ -186,6 +240,7 @@ impl Default for DimensionOptions { line_type: LineType::Solid, line_color: [0, 0, 0], arrow_style: ArrowStyle::Filled, + arrow_head: None, arrow_scale: 100.0, extension_weight: 0.5, extension_type: LineType::Solid, @@ -209,7 +264,8 @@ impl DimensionOptions { /// tolerantly so a newer version's options don't stop a document opening. pub fn from_params(v: serde_json::Value) -> Result { if let (Some(given), Ok(serde_json::Value::Object(known))) = (v.as_object(), serde_json::to_value(Self::default())) - && let Some(k) = given.keys().find(|k| !known.contains_key(*k)) + // `arrowHead` is left out of the saved options when it is null. + && let Some(k) = given.keys().find(|k| !known.contains_key(*k) && k.as_str() != "arrowHead") { return Err(format!("Unknown dimension option {k}")); } @@ -228,8 +284,16 @@ impl DimensionOptions { } Ok(f) } + /// The stroke arrowhead drawn at each end of the dimension line: `arrow_head`, or else the + /// arrow style's head. + pub fn arrowhead(&self) -> Option { + self.arrow_head.clone().or_else(|| self.arrow_style.arrowhead()) + } pub fn validate(&self) -> Result<(), String> { self.factor()?; + if matches!(self.arrow_head, Some(crate::Arrowhead::Custom(_))) { + return Err("A dimension's arrowhead is a built-in stroke arrowhead".into()); + } if self.precision > 6 { return Err("Choose a precision from 0 to 6".into()); } diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index ba6e4dc428..ba203610d6 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -500,11 +500,73 @@ impl Document { self.patterns.iter_mut().find(|p| p.name == name) } + /// The [`Self::unknown`] key that holds each symbol set's Symbol Set Density, `{set id: density}`. + /// [`Self::reid`] gives a copy of a set in this document the density recorded for its source, and + /// [`Self::carry_set_densities`] gives a pasted set the density recorded for it at Copy. + pub const SYMBOL_SET_DENSITY_KEY: &'static str = "symbolSetDensity"; + + /// The Symbol Set Densities recorded for `nodes` and their descendants, by id. + pub fn set_densities_of(&self, nodes: &[Node]) -> std::collections::BTreeMap { + let Some(serde_json::Value::Object(record)) = self.unknown.get(Self::SYMBOL_SET_DENSITY_KEY) else { return Default::default() }; + let mut out = std::collections::BTreeMap::new(); + let mut stack: Vec<&Node> = nodes.iter().collect(); + while let Some(n) = stack.pop() { + if let Some(v) = record.get(&n.id.0.to_string()) { + out.insert(n.id, v.clone()); + } + stack.extend(n.children().into_iter().flatten().map(|c| &**c)); + } + out + } + + /// Record for `copy`, a [`Self::reid`] copy of `source`, and its descendants the Symbol Set + /// Densities that `densities` holds for `source` and its descendants, and none for those it + /// holds none for (whatever [`Self::reid`] recorded). + pub fn carry_set_densities(&mut self, source: &Node, copy: &Node, densities: &std::collections::BTreeMap) { + if densities.is_empty() && !self.unknown.contains_key(Self::SYMBOL_SET_DENSITY_KEY) { + return; + } + let mut pairs = vec![(source, copy)]; + while let Some((s, c)) = pairs.pop() { + match densities.get(&s.id) { + Some(v) => { + if let serde_json::Value::Object(m) = + self.unknown.entry(Self::SYMBOL_SET_DENSITY_KEY).or_insert_with(|| serde_json::Value::Object(Default::default())) + { + m.insert(c.id.0.to_string(), v.clone()); + } + } + None => { + if let Some(serde_json::Value::Object(m)) = self.unknown.get_mut(Self::SYMBOL_SET_DENSITY_KEY) { + m.remove(&c.id.0.to_string()); + } + } + } + if let (Some(sc), Some(cc)) = (s.children(), c.children()) { + pairs.extend(sc.iter().zip(cc.iter()).map(|(a, b)| (&**a, &**b))); + } + } + } + /// Deep-clone `node` with fresh ids for it and all descendants, its images' own pixels taken /// in ([`Self::adopt_pixels`]). pub fn reid(&mut self, node: &Node) -> Node { let mut n = node.clone(); n.id = self.alloc_id(); + // A copy of a symbol set keeps the Symbol Set Density recorded for its source, when the source + // is this document's node with that id; a node from another document may share the id of an + // unrelated set here. + let density = self + .unknown + .get(Self::SYMBOL_SET_DENSITY_KEY) + .and_then(|m| m.get(node.id.0.to_string())) + .filter(|_| self.node(node.id) == Some(node)) + .cloned(); + if let Some(v) = density + && let Some(serde_json::Value::Object(m)) = self.unknown.get_mut(Self::SYMBOL_SET_DENSITY_KEY) + { + m.insert(n.id.0.to_string(), v); + } if let NodeKind::Image(im) = &mut n.kind { self.adopt_image_pixels(im); } diff --git a/crates/doc/src/node/live_shape.rs b/crates/doc/src/node/live_shape.rs index a384836442..0a17301331 100644 --- a/crates/doc/src/node/live_shape.rs +++ b/crates/doc/src/node/live_shape.rs @@ -144,10 +144,36 @@ impl LiveShape { /// from straight up (the Rotate field's sense). None for other shapes. pub fn polygon_angle(&self) -> Option { let LiveShape::Polygon { .. } = self else { return None }; - // No −0° or 360° from rounding: a polygon drawn upright reads 0°. + self.shape_angle() + } + /// A rectangle's, ellipse's or polygon's angle (Rectangle, Ellipse and Polygon Angle): the + /// counterclockwise degrees in [0, 360) it is turned by (the Rotate field's sense). A rectangle or + /// ellipse drawn level reads 0°, as does a polygon drawn with its first vertex straight up. None for + /// other shapes. + pub fn shape_angle(&self) -> Option { + let (LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. }) = self else { return None }; + // No −0° or 360° from rounding: a shape drawn level reads 0°. let a = (-self.angle_deg()).rem_euclid(360.0); Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 }) } + /// Turn a rectangle, ellipse or polygon about its center to `angle` (degrees, as + /// [`LiveShape::shape_angle`]), keeping its size, corners and pie. Nothing changes for other + /// shapes or an angle that isn't finite. + pub fn set_shape_angle(&mut self, angle: f64) { + let Some(now) = self.shape_angle() else { return }; + if !angle.is_finite() { + return; + } + // Brought into [0, 360) first: `now - angle` loses `now` for a very large angle. + let angle = angle.rem_euclid(360.0); + let (xf, local) = match self { + LiveShape::Rectangle { w, h, xf, .. } | LiveShape::Ellipse { w, h, xf, .. } => (xf, Point::new(*w / 2.0, *h / 2.0)), + LiveShape::Polygon { xf, .. } => (xf, Point::ZERO), + LiveShape::Line { .. } | LiveShape::Path { .. } => return, + }; + let center = *xf * local; + *xf = Affine::rotate_about((now - angle).to_radians(), center) * *xf; + } /// Whether a polygon's sides are all as long: `xf` scales it evenly and doesn't shear it. True /// for other shapes. pub fn polygon_sides_equal(&self) -> bool { @@ -171,12 +197,8 @@ impl LiveShape { } /// Turn a polygon about its centre to `angle` (degrees, as [`LiveShape::polygon_angle`]). pub fn set_polygon_angle(&mut self, angle: f64) { - let Some(now) = self.polygon_angle() else { return }; - if let LiveShape::Polygon { xf, .. } = self - && angle.is_finite() - { - let centre = *xf * Point::ZERO; - *xf = Affine::rotate_about((now - angle).to_radians(), centre) * *xf; + if let LiveShape::Polygon { .. } = self { + self.set_shape_angle(angle); } } /// A line's length in the document, from its first end to its second. None for other shapes. diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs index 789e0f66b2..cdcbf2cf85 100644 --- a/crates/doc/src/node/tests.rs +++ b/crates/doc/src/node/tests.rs @@ -184,6 +184,20 @@ fn a_polygon_reports_and_takes_its_radius_angle_and_equal_sides() { assert_eq!((e.polygon_radius(), e.polygon_angle()), (None, None)); } +/// A very large angle turns a rectangle to that angle modulo 360, whatever angle it had before. +#[test] +fn a_shape_takes_a_very_large_angle() { + let close = |a: f64, b: f64| (a - b).abs() < 1e-6; + let want = 1e20f64.rem_euclid(360.0); + for turned in [0.0, 90.0] { + let xf = Affine::translate((50.0, 50.0)) * Affine::rotate(-f64::to_radians(turned)); + let mut r = LiveShape::Rectangle { w: 100.0, h: 50.0, radii: [0.0; 4], kinds: Default::default(), radii_relative: false, xf }; + assert!(close(r.shape_angle().unwrap(), turned), "{:?}", r.shape_angle()); + r.set_shape_angle(1e20); + assert!(close(r.shape_angle().unwrap(), want), "from {turned}°: {:?}, not {want}", r.shape_angle()); + } +} + /// A node holding a live rectangle (`w` × `h`, all radii `r`, placed by `xf`) and its path. fn live_rect(w: f64, h: f64, r: f64, xf: Affine) -> Node { let live = LiveShape::Rectangle { w, h, radii: [r; 4], kinds: Default::default(), radii_relative: false, xf }; diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index dcbcd87028..0801187b6d 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -686,6 +686,43 @@ fn reid_gives_fresh_ids() { assert!(!ids.contains(&a) && !ids.contains(&b)); } +/// A copy of a node in the document takes the Symbol Set Density recorded for it; a node from +/// another document with the same id does not. +#[test] +fn reid_copies_the_set_density_of_the_documents_own_node() { + let (mut d, a, _) = doc_with_rects(); + d.unknown.insert(Document::SYMBOL_SET_DENSITY_KEY.into(), serde_json::json!({ a.0.to_string(): 2.0 })); + let density = |d: &Document, id: NodeId| d.unknown[Document::SYMBOL_SET_DENSITY_KEY].get(id.0.to_string()).cloned(); + let own = d.node(a).cloned().unwrap(); + let copy = d.reid(&own); + assert_eq!(density(&d, copy.id), Some(serde_json::json!(2.0))); + let foreign = Node::group(a, vec![]); + let copy = d.reid(&foreign); + assert_eq!(density(&d, copy.id), None); +} + +/// A pasted copy and its descendants take the densities recorded at Copy, and none where Copy +/// recorded none, whatever [`Document::reid`] found for an identical node in the document. +#[test] +fn carry_set_densities_gives_the_densities_recorded_at_copy() { + let (mut d, a, b) = doc_with_rects(); + d.unknown.insert(Document::SYMBOL_SET_DENSITY_KEY.into(), serde_json::json!({ a.0.to_string(): 2.0 })); + let density = |d: &Document, id: NodeId| d.unknown[Document::SYMBOL_SET_DENSITY_KEY].get(id.0.to_string()).cloned(); + let (na, nb) = (d.node(a).cloned().unwrap(), d.node(b).cloned().unwrap()); + // Copy recorded nothing for `a`: the copy reid gave a density loses it. + let copy = d.reid(&na); + assert_eq!(density(&d, copy.id), Some(serde_json::json!(2.0))); + d.carry_set_densities(&na, ©, &Default::default()); + assert_eq!(density(&d, copy.id), None); + // Copy recorded 7 for `b` inside a group: the group's copy has none, and `b`'s copy has 7. + let g = d.alloc_id(); + let group = Node::group(g, vec![Arc::new(nb)]); + let copy = d.reid(&group); + d.carry_set_densities(&group, ©, &[(b, serde_json::json!(7.0))].into_iter().collect()); + let inner = copy.children().unwrap()[0].id; + assert_eq!((density(&d, copy.id), density(&d, inner)), (None, Some(serde_json::json!(7.0)))); +} + #[test] fn setup_round_trips_and_old_files_load() { let (mut d, _, _) = doc_with_rects(); diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index 746c0b69d5..c0e305aeeb 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -451,12 +451,25 @@ impl TextObject { /// fractions of the path. False, changing nothing, for other type, when the anchor doesn't /// exist, a degenerate `xf` or a path that would not be finite. pub fn set_path_handle(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool) -> bool { + self.set_path_handle_with_symmetry((si, ai), out, pos, independent, false) + } + /// [`Self::set_path_handle`] with an optional mirror of the opposite handle about the anchor + /// in document space, preserving the anchor kind. `independent` takes precedence, and at an + /// open end of the path, where no segment leaves the anchor on that side, the handle moves as + /// it would without `symmetric`. Both handles are edited in one reshape, using the same validated + /// document-to-text map. + pub fn set_path_handle_with_symmetry(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool, symmetric: bool) -> bool { let xf = self.xf; matches!(self.kind, TextKind::OnPath { .. }) && self.reshape_local(|path, to_text| { + let mirror = symmetric && !independent && path.subpaths.get(si).is_some_and(|sp| sp.has_segment(ai, !out)); let Some(a) = path.anchor_mut(si, ai) else { return false }; let mut drawn = a.transform(xf); drawn.set_handle(out, pos, independent); + if mirror { + let opposite = drawn.p - (pos - drawn.p); + if out { drawn.h_in = opposite } else { drawn.h_out = opposite } + } *a = drawn.transform(to_text); true }) diff --git a/crates/effects/src/stroke/arrow.rs b/crates/effects/src/stroke/arrow.rs index d188bcafd6..1047e4d0dd 100644 --- a/crates/effects/src/stroke/arrow.rs +++ b/crates/effects/src/stroke/arrow.rs @@ -5,7 +5,8 @@ //! corner. With [`ArrowAlign::Tip`] the tip sits on the end point and the stroke is shortened by //! the inset; with [`ArrowAlign::Extend`] the path keeps its length and the tip sits the inset //! past the end point. Heads added after the first ten are drawn in local units ([`local`]), as are -//! custom heads, whose stroke ends halfway along their length. +//! custom heads, whose stroke ends at their own stop or else halfway along their length +//! ([`vectorcraft_doc::CustomArrowhead::stop`]). use std::borrow::Cow; diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index e2f6b7624f..9a1531ede9 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -907,7 +907,7 @@ pub use gradpresets::{GradientPreset, GradientPresetEntry}; pub use buildcmds::{TracePreset, TracePresetChange}; /// An Image Trace made off the UI thread, and what it traced (#3098). -pub use buildcmds::{TraceRun, Traced}; +pub use buildcmds::{TraceRun, Traced, image_trace_target}; /// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them). pub(crate) use buildcmds::TracePresetChanges; diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 2d31c5af6e..c16d8c312d 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -175,6 +175,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs }, BuiltinBrushLibrary { id: "pressure-sensitive", name: "Pressure Sensitive", make: pressure_sensitive }, BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes }, + BuiltinBrushLibrary { id: "paint", name: "Paint", make: paint }, BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders }, BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes }, BuiltinBrushLibrary { id: "stipple", name: "Stipple", make: stipple }, @@ -182,8 +183,10 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams }, BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media }, BuiltinBrushLibrary { id: "tech-circuit", name: "Tech Circuit", make: tech_circuit }, + BuiltinBrushLibrary { id: "engraving", name: "Engraving", make: engraving }, BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows }, BuiltinBrushLibrary { id: "image-brush", name: "Image Brush", make: image_brush }, + BuiltinBrushLibrary { id: "artistic", name: "Artistic Brushes", make: artistic }, ]; /// Built-in library `id`, made once. @@ -237,6 +240,85 @@ fn art(name: &str, art: Node, colorization: Colorization) -> Brush { Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) } } +/// Artistic: four original vector compositions that stretch along a path and take its color. +fn artistic() -> BrushLibrary { + let orbit = group(vec![ + black(band(100.0, 1.4, 64, |x| 3.0 * (x * std::f64::consts::TAU / 40.0).sin())), + black(band(100.0, 1.4, 64, |x| -3.0 * (x * std::f64::consts::TAU / 40.0).sin())), + ]); + let mut petals = vec![black(band(100.0, 0.8, 4, |_| 0.0))]; + for i in 0..6 { + let x = 9.0 + 16.0 * i as f64; + let side = if i % 2 == 0 { 1.0 } else { -1.0 }; + petals.push(black(polygon(&[(x - 6.0, 0.0), (x - 2.0, 5.0 * side), (x + 5.0, 7.0 * side), (x + 2.0, 2.0 * side)]))); + } + let mut lattice = vec![black(band(100.0, 0.9, 4, |_| 0.0))]; + for i in 0..5 { + let x = 20.0 * i as f64; + lattice.push(black(polygon(&[(x, -4.0), (x + 1.0, -4.0), (x + 20.0, 4.0), (x + 19.0, 4.0)]))); + lattice.push(black(polygon(&[(x, 4.0), (x + 1.0, 4.0), (x + 20.0, -4.0), (x + 19.0, -4.0)]))); + } + let mut facets = Vec::new(); + for i in 0..8 { + let x = 12.5 * i as f64; + let high = if i % 2 == 0 { 6.0 } else { 3.5 }; + facets.push(black(polygon(&[(x, -high), (x + 11.0, -high / 2.0), (x + 12.5, 0.0), (x + 11.0, high / 2.0), (x, high)]))); + } + built( + "Artistic Brushes", + Document::new(100.0, 100.0), + vec![ + art("Orbit Lines", orbit, Colorization::Tints), + art("Petal Garland", group(petals), Colorization::Tints), + art("Lattice Braid", group(lattice), Colorization::Tints), + art("Facet Sweep", group(facets), Colorization::Tints), + ], + ) +} + +/// Original fine-line art for an engraving-style brush library. +fn engraving() -> BrushLibrary { + let lines = |count: usize, width: f64, spacing: f64| { + group( + (0..count) + .map(|i| { + let y = (i as f64 - (count - 1) as f64 / 2.0) * spacing; + black(shapes::rectangle(Rect::new(0.0, y - width / 2.0, 100.0, y + width / 2.0))) + }) + .collect(), + ) + }; + let taper = group( + (0..5) + .map(|i| { + let y = (i as f64 - 2.0) * 2.2; + black(polygon(&[(0.0, y - 0.35), (80.0, y - 0.35), (100.0, y), (80.0, y + 0.35), (0.0, y + 0.35)])) + }) + .collect(), + ); + let broken = group( + (0..5) + .flat_map(|row| { + (0..4).map(move |segment| { + let x = segment as f64 * 25.0 + if row % 2 == 0 { 0.0 } else { 8.0 }; + let y = (row as f64 - 2.0) * 2.2; + black(shapes::rectangle(Rect::new(x, y - 0.3, (x + 16.0).min(100.0), y + 0.3))) + }) + }) + .collect(), + ); + built( + "Engraving", + Document::new(100.0, 100.0), + vec![ + art("Fine Hatching", lines(5, 0.65, 2.2), Colorization::Tints), + art("Dense Hatching", lines(9, 0.42, 1.2), Colorization::Tints), + art("Tapered Hatching", taper, Colorization::Tints), + art("Broken Hatching", broken, Colorization::Tints), + ], + ) +} + /// An Arrows brush whose art stretches only between `start` and `end` (fractions of its length). fn arrow_art(name: &str, art: Node, start: f64, end: f64) -> Brush { Brush { @@ -550,6 +632,45 @@ fn spacer(r: Rect) -> Node { Node::path(NodeId(0), shapes::rectangle(r), Appearance::default()) } +/// Paint: original filled vector art with broad, broken, loaded, and fanned marks. Each is one +/// stroke stretched along the path, with an intentionally different edge and paint distribution. +fn paint() -> BrushLibrary { + let flat_sweep = group(vec![ + black(band(100.0, 5.0, 64, |x| 0.8 * (x / 100.0 * std::f64::consts::TAU).sin())), + black(polygon(&[(0.0, -2.5), (7.0, -3.8), (18.0, -2.5)])), + black(polygon(&[(78.0, 2.5), (94.0, 4.0), (100.0, 2.5)])), + ]); + let mut dry_drag = vec![]; + for (y, shift) in [(-5.0, 0.0), (-3.2, 4.0), (-1.3, 1.0), (0.8, 6.0), (2.8, 3.0), (4.8, 8.0)] { + dry_drag.push(black(shapes::rectangle(Rect::new(2.0 + shift, y, 35.0 + shift, y + 0.8)))); + dry_drag.push(black(shapes::rectangle(Rect::new(40.0 + shift, y, 75.0 - shift / 2.0, y + 0.8)))); + dry_drag.push(black(shapes::rectangle(Rect::new(80.0 - shift / 2.0, y, 98.0, y + 0.8)))); + } + let mut loaded_stroke = vec![black(band(100.0, 6.0, 64, |x| 1.2 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin()))]; + for (x, r) in [(12.0, 4.2), (39.0, 3.6), (64.0, 4.8), (88.0, 3.9)] { + loaded_stroke.push(black(shapes::ellipse(Rect::new(x - r, -r - 1.5, x + r, r + 1.5)))); + } + let mut fan_sweep = vec![]; + for i in -2..=2 { + let offset = i as f64; + fan_sweep.push(black(band(100.0, 1.2, 48, |x| offset * (1.4 + x * 0.045) + 0.3 * (x / 100.0 * std::f64::consts::TAU).sin()))); + } + let paint_art = |name: &str, art: Node| Brush { + name: name.into(), + kind: BrushKind::Art(ArtBrush { art, width: 150.0, colorization: Colorization::Tints, ..Default::default() }), + }; + built( + "Paint", + Document::new(100.0, 100.0), + vec![ + paint_art("Flat Sweep", flat_sweep), + paint_art("Dry Drag", group(dry_drag)), + paint_art("Loaded Stroke", group(loaded_stroke)), + paint_art("Fan Sweep", group(fan_sweep)), + ], + ) +} + /// Pattern Borders: pattern brushes of tiles drawn here; Beads has corner tiles. fn pattern_borders() -> BrushLibrary { let zigzag = black(polygon(&[(0.0, 1.4), (5.0, -2.6), (10.0, 1.4), (10.0, 2.6), (5.0, -1.4), (0.0, 2.6)])); @@ -992,10 +1113,14 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc return Some(found); } if let Some(b) = BUILTIN.iter().find(|b| b.id == key) { - return Some((builtin_info(b), builtin_library(key)?)); + return Some((builtin_info(b), builtin_library(b.id)?)); } - let id = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key))?.id; - library(s, &id) + if let Some(id) = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key)).map(|l| l.id) { + return library(s, &id); + } + // Keep the short built-in alias, but let a user or loaded library own its display name. + let b = key.eq_ignore_ascii_case("Artistic").then(|| BUILTIN.iter().find(|b| b.id == "artistic")).flatten()?; + Some((builtin_info(b), builtin_library(b.id)?)) } fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc)> { diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 6c0f651c00..fbd4512fa3 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -362,7 +362,7 @@ pub fn specs() -> Vec { "Symbol Sprayer", [], None, - "{points: [[x,y]…] (a third number is not used; one that isn't a number is an error), name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full; a `style` the document does not have is then an error. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error", + "{points: [[x,y]…] (a third value is a number or null and is not used), name?, radius?: 40, density?: 1..10 (5; a number outside 1..10 is taken as the nearer end), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one with an amount above 0, at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full; a `style` the document does not have is then an error. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error", has_doc, symbol_spray ), @@ -380,7 +380,7 @@ pub fn specs() -> Vec { "Symbolism Tool", [], None, - "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it; average leaves an instance without a size (a scale of 0) as it is. With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. An instance counts only when it changes, and no undo step is added when none does (none under the brush, average with each already at the mean, or each already at the tool's limit). A `method` that is none of the three, or a pressure that isn't a number, is an error", + "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, shift?: bool (shift, size, stain and style; false), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name (a graphic style's; left out, or naming no style in the document, the first style after the default one)} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way; style without `shift`: from none to the userDefined amount); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it; average leaves an instance without a size as it is. With `proportional` false a drag resizes along its own direction, the width by the drag's horizontal share and the height by its vertical share (a level drag the width, an upright one the height, a 45° drag both alike; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. The style goes on by the brush's strength at each sample, and a stroke's samples add up. With `alt` and without `shift`, userDefined and random style remove all of an instance's appearance items under the brush at once, whatever the brush's strength. `shift` is the tool's Shift form: shift brings the instances within `radius` of any point one place forward among their siblings (with `alt`, one place backward), once for the stroke, and does not move them; size keeps the instances where they are, `affectsDensity` included; stain and style keep each instance's amount and move its paint toward `color` or the style (stain by the tool's amount at its distance from the point, style by the brush's strength there), whatever `method` is, and leave an instance without a stain or style as it is, and `alt` has no effect. An instance counts only when it changes, and no undo step is added when none does (none under the brush, average with each already at the mean, each already at the tool's limit, or shift with nothing to move or change). A `method` that is none of the three, or a pressure that isn't a number, is an error", has_doc, symbol_adjust ), diff --git a/crates/engine/src/cmd/brushsym/symbolism.rs b/crates/engine/src/cmd/brushsym/symbolism.rs index 0199b7b13d..21fe71a644 100644 --- a/crates/engine/src/cmd/brushsym/symbolism.rs +++ b/crates/engine/src/cmd/brushsym/symbolism.rs @@ -86,8 +86,9 @@ pub(super) fn spacing(density: f64) -> f64 { } /// The document key that holds each symbol set's Symbol Set Density: `{set id: density}`, written -/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it. -const SET_DENSITY_KEY: &str = "symbolSetDensity"; +/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it, and copied to a +/// copy of a set by [`Document::reid`]. +const SET_DENSITY_KEY: &str = Document::SYMBOL_SET_DENSITY_KEY; /// The Symbol Set Density symbol set `set` was created at or last given (None when not recorded). fn set_density_of(d: &Document, set: NodeId) -> Option { @@ -261,7 +262,10 @@ pub(super) fn mean(looks: &[&Look], at: Point, with_gap: bool) -> Option { cos += l.angle.cos(); opacity += l.opacity; middle += l.center.to_vec2(); - if let Some((p, o)) = &l.fill { + // A fill at no opacity shows nothing: it is no stain or style, and its paint is not taken. + if let Some((p, o)) = &l.fill + && *o > 0.0 + { amount += o; let far = l.center.distance(at); if paint.is_none_or(|(_, nearest)| far < nearest) { diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 6f1b96b52f..14e52ffe4f 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -118,6 +118,20 @@ fn instances_of(d: &Document, name: Option<&str>) -> Vec { v } +/// The symbol instances in `nodes` and inside them, each once, in the order a walk of each node in +/// turn first reaches them. +fn instances_in<'a>(nodes: impl IntoIterator) -> Vec { + let (mut v, mut seen) = (vec![], std::collections::HashSet::new()); + for n in nodes { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::SymbolInstance { .. }) && seen.insert(c.id) { + v.push(c.id); + } + }); + } + v +} + /// The symbols an instance in `n` (its opacity masks included) places, pushed onto `out`. fn art_symbols(n: &Node, out: &mut Vec) { vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { @@ -917,11 +931,12 @@ fn samples(p: &Value, cmd: &str) -> Result> { let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing points [[x,y]…]"))?; let mut v = Vec::with_capacity(a.len()); for q in a { - let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue }; + // The pressure is checked first: a point skipped for its coordinates still has a bad one refused. let pressure = match q.get(2) { None | Some(Value::Null) => 1.0, Some(f) => f.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad(cmd, format!("a point's pressure must be a number, not {f}")))?, }; + let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue }; v.push((Point::new(x, y), pressure.clamp(0.0, 1.0))); } if v.is_empty() || v.iter().any(|(q, _)| !q.x.is_finite() || !q.y.is_finite()) { @@ -930,13 +945,15 @@ fn samples(p: &Value, cmd: &str) -> Result> { Ok(v) } -/// The fill of the graphic style `p` names with `style`, else of the document's first style after -/// the default one. +/// The fill of the graphic style `p` names with `style`, else (no name, or one the document has no +/// style for, such as the Symbol Styler's style from another document) of the document's first +/// style after the default one. fn style_paint(d: &Document, p: &Value) -> Option { - match str_param(p, "style") { - Some(n) => d.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()), - None => d.graphic_styles.get(1).or(d.graphic_styles.first()).map(|g| g.appearance.fill_paint()), - } + str_param(p, "style") + .and_then(|n| d.graphic_styles.iter().find(|g| g.name == n)) + .or(d.graphic_styles.get(1)) + .or(d.graphic_styles.first()) + .map(|g| g.appearance.fill_paint()) } /// Deterministic per-point jitter in [-1, 1]² (so previews re-applied on the snapshot agree). @@ -976,7 +993,7 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { } let style = style_paint(&st.doc, p); // Style: User Defined uses the style `style` names, so one the document does not have is an error. - if let Some(n) = str_param(p, "style").filter(|_| !modes.style && style.is_none()) { + if let Some(n) = str_param(p, "style").filter(|n| !modes.style && !st.doc.graphic_styles.iter().any(|g| g.name == *n)) { return Err(bad(C, format!("unknown graphic style `{n}`"))); } let size = natural_size(&st.doc, &name); @@ -1129,6 +1146,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { let use_pressure = switch_or(p, "usePressure", false, C)?; let proportional = switch_or(p, "proportional", true, C)?; let affects_density = switch_or(p, "affectsDensity", false, C)?; + let shift = switch_or(p, "shift", false, C)?; // The Symbol Shifter has no Method. let method = if tool == "shift" { method_param(p, C).map(|_| Method::UserDefined)? } else { method_param(p, C)? }; // Refused while an object of a dynamic instance's art is selected: the instance stays as it is. @@ -1141,20 +1159,8 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { let style_paint = style_paint(&st.doc, p); let candidates: Vec = { let d = &st.doc; - let mut v = vec![]; - if st.selection.is_empty() { - v = instances_of(d, None); - } else { - for id in &st.selection.objects { - if let Some(n) = d.node(*id) { - n.walk(&mut |c| { - if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !v.contains(&c.id) { - v.push(c.id); - } - }); - } - } - } + let mut v = + if st.selection.is_empty() { instances_of(d, None) } else { instances_in(st.selection.objects.iter().filter_map(|id| d.node(*id))) }; let editable = d.editable(); v.retain(|id| editable(*id)); v @@ -1172,12 +1178,39 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { // for the whole stroke (and for every preview of it). let first = pts.first().map_or(Point::ZERO, |(q, _)| *q); let share = |id: NodeId| if method == Method::Random { jitter(id.0 as usize, first).0 + 1.0 } else { 1.0 }; + // Shift with the Symbol Shifter: the instances under the brush come one place forward among + // their siblings (with `alt`, go one place backward), once for the whole stroke. + if tool == "shift" && shift { + let count = crate::cmd::colorcmds::edit_if_changed(s, label, |_, d| { + let under: std::collections::HashSet = candidates + .iter() + .copied() + .filter(|id| { + d.node(*id).and_then(instance_center).is_some_and(|c| { + pts.iter().any(|(q, pressure)| (if use_pressure { *pressure } else { intensity }) > 0.0 && c.distance(*q) < radius) + }) + }) + .collect(); + let moved = restack(d, &under, alt)?; + Ok((moved, moved > 0)) + })?; + return Ok(json!({ "count": count })); + } + // Shift with the Symbol Stainer or the Symbol Styler: the paint an instance's stain or style + // moves toward, and the share of the brush's strength it moves by. Shift with the Symbol Sizer + // keeps the instances where they are, Resizing Affects Density included. + let recolor = match tool.as_str() { + "stain" if shift => Some((Paint::solid(color), 0.15)), + "style" if shift => Some((style_paint.clone().unwrap_or(Paint::solid(color)), 1.0)), + _ => None, + }; + let spread = affects_density && !shift; // No undo step when no instance changes (none under the brush, or Average with each at the mean). let count = crate::cmd::colorcmds::edit_if_changed(s, label, |orig, d| { let mut touched = std::collections::BTreeSet::new(); let mut sides = Sides::new(); for (j, (q, pressure)) in pts.iter().enumerate() { - let delta = if j > 0 { *q - pts[j - 1].0 } else { Vec2::ZERO }; + let delta = j.checked_sub(1).and_then(|i| pts.get(i)).map_or(Vec2::ZERO, |(prev, _)| *q - *prev); // Use Pressure Pen: the pen's pressure at the point is the intensity there. let strength = if use_pressure { *pressure } else { intensity }; // Average: the mean of the instances under the brush, as they are at this point. @@ -1198,6 +1231,14 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { if w <= 0.0 { continue; } + // Shift with the Symbol Stainer or the Symbol Styler: the instance keeps the amount + // of its stain or style, and its paint moves toward the color or the style. An + // instance without one, or without a size, is left as it is. + if let Some((to, step)) = &recolor { + let fill = d.node(*id).and_then(|n| look(d, n, &mut sides)).and_then(|l| l.fill); + touched.extend(recolor_keeping_amount(d, *id, fill, to, step * w).then_some(*id)); + continue; + } // Average needs the instance's own values, so it leaves an instance without a size // as it is; the other methods change it as before. // The instance's own values are read for Average only. @@ -1261,8 +1302,9 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { }; n.transform(about(Affine::scale_non_uniform(kx, ky)), false); // Resizing Affects Density: instances move away from the brush's center as - // they grow and toward it as they shrink. - if affects_density { + // they grow and toward it as they shrink. Shift keeps the instances where + // they are, so the set's density stays as it was. + if spread { n.transform(Affine::translate((c - *q) * ((kx * ky).sqrt() - 1.0)), false); } } @@ -1280,9 +1322,10 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { "stain" | "style" => { let paint = if tool == "style" { style_paint.clone().unwrap_or(Paint::solid(color)) } else { Paint::solid(color) }; let (paint, o) = match &avg { - // Toward the mean amount, keeping the stain or style the instance has. + // Toward the mean amount, keeping the stain or style the instance has + // (one at no opacity is none). Some((t, look)) => { - let (own, cur) = look.fill.clone().map_or((None, 0.0), |(p, o)| (Some(p), o)); + let (own, cur) = look.fill.clone().filter(|(_, o)| *o > 0.0).map_or((None, 0.0), |(p, o)| (Some(p), o)); (own.or(t.paint.clone()).unwrap_or(paint), (cur + (t.amount - cur) * w.min(1.0)) as f32) } // Alt with the Symbol Styler removes the instance's appearance. @@ -1292,11 +1335,11 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { } None => { let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0); + // The style goes on gradually, by the brush's strength there: in + // full at the center at full intensity or pressure. let step = match (tool.as_str(), method) { - // Random: the instance's share of the style, scaled by the - // brush strength there. - ("style", Method::Random) => (share / 2.0 * w.min(1.0)) as f32, - ("style", _) => 1.0, + ("style", Method::Random) => (w * share / 2.0) as f32, + ("style", _) => w as f32, _ => (0.15 * w * share) as f32, }; (paint, if alt { cur - step } else { cur + step }) @@ -1324,9 +1367,108 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { } } } - // An instance the stroke moved away and back again is not counted. + // An instance the stroke moved away and back again, or reached but left as it was (at a + // limit already), is not counted. touched.retain(|id| d.node(*id) != orig.node(*id)); Ok((touched.len(), !touched.is_empty())) })?; Ok(json!({ "count": count })) } + +/// Move the paint of instance `id`'s stain or style (`fill`, its topmost fill with the amount) +/// toward `to` by `t`. The fill keeps its amount and everything else it has, and the instance's +/// other appearance items stay as they are. A paint with no form between it and `to` (a solid +/// color and a pattern, say) takes `to` at once, so repeated strokes below half strength still +/// reach it. An instance without a stain or style, or one whose paint does not change, is left as +/// it is. Returns whether it changed. +fn recolor_keeping_amount(d: &mut Document, id: NodeId, fill: Option<(Paint, f64)>, to: &Paint, t: f64) -> bool { + use vectorcraft_doc::blend::lerp_paint; + let Some((own, _)) = fill.filter(|(_, o)| *o > 0.0) else { return false }; + let t = t.clamp(0.0, 1.0) as f32; + let mut paint = lerp_paint(&own, to, t); + // `lerp_paint` switches such a pair halfway, so just below half it still gives `own`. + if paint == own && t > 0.0 && lerp_paint(&own, to, 0.49) == own { + paint = to.clone(); + } + if paint == own { + return false; + } + let Some(f) = d.node_mut(id).and_then(|n| n.appearance.fill_mut()) else { return false }; + f.paint = paint; + true +} + +/// Bring each of `ids` one place forward among its siblings past a sibling that is not one of them +/// (`back`: one place backward). Ones already in front of (behind) every other sibling stay, and +/// so do the clipping path of a clip group and the ruler guides above a layer's art. Returns how +/// many moved. +fn restack(d: &mut Document, ids: &std::collections::HashSet, back: bool) -> Result { + let parents: std::collections::BTreeSet> = ids.iter().map(|id| d.parent_of(*id)).collect(); + let mut moved = 0; + for par in parents { + let floor = usize::from(par.and_then(|p| d.node(p)).is_some_and(Node::clips)); + let ch = d.children_mut(par)?; + let len = Node::guide_run_start(ch); + if len <= floor + 1 { + continue; + } + let picked = |n: &Arc| ids.contains(&n.id); + if back { + for i in floor + 1..len { + if picked(&ch[i]) && !picked(&ch[i - 1]) { + ch.swap(i - 1, i); + moved += 1; + } + } + } else { + for i in (floor..len - 1).rev() { + if picked(&ch[i]) && !picked(&ch[i + 1]) { + ch.swap(i, i + 1); + moved += 1; + } + } + } + } + Ok(moved) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn instance(id: u64) -> Arc { + Arc::new(Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY })) + } + + /// The instances come out in the order a search of the list built so far gives: nested + /// groups, a group listed twice, a member listed after its group and one listed before it. + #[test] + fn instances_in_matches_searching_the_list_so_far() { + let groups: Vec = (0..40u64) + .map(|g| { + let base = g * 100; + let mut children: Vec> = (0..40).map(|i| instance(base + i)).collect(); + let inner = (40..50).map(|i| instance(base + i)).collect(); + children.insert(20, Arc::new(Node::group(NodeId(base + 90), inner))); + children.push(Arc::new(Node::group(NodeId(base + 91), vec![]))); + Node::group(NodeId(base + 99), children) + }) + .collect(); + let early = Node::new(NodeId(1_245), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY }); + let late = Node::new(NodeId(305), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY }); + let nodes: Vec<&Node> = std::iter::once(&early).chain(&groups).chain([&groups[0], &late, &groups[7]]).collect(); + let mut searched = vec![]; + for n in &nodes { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !searched.contains(&c.id) { + searched.push(c.id); + } + }); + } + let found = instances_in(nodes.iter().copied()); + assert_eq!(found, searched); + assert_eq!(found.len(), 2_000); + assert_eq!(found[0], NodeId(1_245)); + assert!(instances_in([]).is_empty()); + } +} diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 904e80df61..1e6739b6c7 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -42,7 +42,7 @@ 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}; +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}; /// Name of an Image Trace group. diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index 90c505cfb6..7c2e6d0955 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -58,9 +58,10 @@ fn view_param(cmd: &str, p: &Value) -> Result> { v.as_str().and_then(TraceView::from_id).map(Some).ok_or_else(|| bad(cmd, format!("view must be one of {}", ids()))) } -/// The `split` param (the Split view's divider, 0 to 1), if given. +/// The `split` param (the Split view's divider, 0 to 1), if given. A null divider is an error, as +/// any other value that is not such a number is; only an omitted one keeps the divider. fn split_param(cmd: &str, p: &Value) -> Result> { - let Some(v) = p.get("split").filter(|v| !v.is_null()) else { return Ok(None) }; + let Some(v) = p.get("split") else { return Ok(None) }; v.as_f64().filter(|f| (0.0..=1.0).contains(f)).map(Some).ok_or_else(|| bad(cmd, "split must be a number from 0 to 1")) } @@ -606,6 +607,30 @@ struct Prepared { library: Vec<([u8; 3], Paint)>, } +/// The object `imageTrace.make` would trace, without preparing settings or reading image bytes. +pub fn image_trace_target(s: &Session, p: &Value) -> Result { + target_image(s, "imageTrace.make", p).map(|(target, _)| target) +} + +fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box)> { + let roots = root_ids(s, p)?; + let d = &s.doc()?.doc; + roots + .iter() + .find_map(|r| { + let n = d.node(*r)?; + match &n.kind { + NodeKind::Image(i) => Some((*r, i.clone())), + _ if is_trace_group(n) => match &n.children()?.first()?.kind { + NodeKind::Image(i) => Some((*r, i.clone())), + _ => None, + }, + _ => None, + } + }) + .ok_or_else(|| bad(c, "select an image (or an Image Trace group)")) +} + /// What command `c` with params `p` traces, and how, from the session: everything but the trace. fn prepare(s: &Session, c: &str, p: &Value) -> Result { let mut params = trace_params(s, c, p)?; @@ -625,25 +650,7 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result { None if is(tr::preset(named)) || is(tr::enhanced_preset(named)) => named.to_string(), None => "Custom".to_string(), }; - let roots = root_ids(s, p)?; - // The image (inside a trace group, or selected directly). - let (target, image) = { - let d = &s.doc()?.doc; - roots - .iter() - .find_map(|r| { - let n = d.node(*r)?; - match &n.kind { - NodeKind::Image(i) => Some((*r, i.clone())), - _ if is_trace_group(n) => match &n.children()?.first()?.kind { - NodeKind::Image(i) => Some((*r, i.clone())), - _ => None, - }, - _ => None, - } - }) - .ok_or_else(|| bad(c, "select an image (or an Image Trace group)"))? - }; + let (target, image) = target_image(s, c, p)?; if by_color && s.doc()?.doc.node(target).is_some_and(vectorcraft_render::effects::has_pathfinder) { return Err(bad(c, LIVE_PATHFINDER_BY_COLOR)); } diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index c42289ccc7..7c0be8255c 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -109,6 +109,9 @@ pub struct Clipboard { /// The selected ruler guides copied with (or without) the objects (#3226), as canvas guides on /// no layer: pasting puts them on the layer new art goes to, moved as the objects are. pub guides: Vec, + /// The Symbol Set Density recorded at Copy for each copied symbol set, by its id in + /// [`Self::nodes`]: a pasted set packs from it. + pub set_densities: BTreeMap, /// The RGB and CMYK profiles the objects' colors showed through in the document they were /// copied from (its assigned profiles, else the working spaces then), by name; none for objects /// from outside an open document. Paste compares them with the destination's @@ -484,6 +487,7 @@ impl Clipboard { }) .collect(), guides: self.guides.clone(), + set_densities: self.set_densities.clone(), source_profiles: self.source_profiles.clone(), colors_converted: self.colors_converted, } diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 583341f2a4..f7b5de29dd 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1161,6 +1161,7 @@ impl Clipboard { char_styles: pick(Res::CharStyle, &src.char_styles), para_styles: pick(Res::ParaStyle, &src.para_styles), brushes, + set_densities: src.set_densities_of(&nodes), nodes, ..Default::default() } diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 0ac4f8c3b0..1b394fa95c 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -26,6 +26,8 @@ use vectorcraft_render::proof; use super::EngineError; use super::{CommandSpec, Result, Session, always, bad, cmd, color_value, has_doc, switch_or, targets, text_param}; +pub mod proof_file; + /// `Document.unknown` key under which files before format v3 kept the assigned profiles (migrated /// to `Document::color_profiles` on load). pub const PROFILES_KEY: &str = vectorcraft_doc::profiles::LEGACY_PROFILES_KEY; @@ -82,7 +84,7 @@ pub fn specs() -> Vec { "Convert Color", [], None, - "{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}", + "{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\"|\"oklch\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}; oklch values are [L (0..100 %), C, H (0..360°)] of the color's display sRGB (CSS Color 4 OKLCH: https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), with H 0 for a gray; a color outside sRGB (a Lab color, a CMYK color or an RGB color in a wider working RGB space) is clipped to sRGB first", always, convert_color ), @@ -100,10 +102,46 @@ pub fn specs() -> Vec { "Proof Setup", ["View", "Proof Setup"], None, - "{target?: \"workingCmyk\"|\"cmyk:\"|\"legacyMacRgb\"|\"srgb\"|\"monitorRgb\"|\"protanopia\"|\"deuteranopia\"|\"tritanopia\", intent?, simulatePaper?, proof?: bool (also turn Proof Colors on)} → proof state", + "{target?: \"workingCmyk\"|\"cmyk:\"|\"rgb:\"|\"legacyMacRgb\"|\"srgb\"|\"monitorRgb\"|\"protanopia\"|\"deuteranopia\"|\"tritanopia\" (cmyk: and rgb: name a CMYK or RGB profile of color.loadProfile or the built-in ones: the device to simulate), intent? (used while preserveNumbers is off), simulatePaper?: bool, preserveNumbers?: bool (Preserve CMYK or RGB Numbers: the colors' numbers in the document's space go to the device unchanged), simulateBlack?: bool (Simulate Black Ink: the device's black shows as the dark gray it prints; simulatePaper does this too; CMYK devices only, as simulatePaper), proof?: bool (also turn Proof Colors on)} → proof state", always, proof_setup ), + cmd!( + query "view.proofSetup.save", + "Save Proof Setup…", + [], + None, + "{path?: file | name?: a setup in the Proof Setups folder next to the preferences (at most 100 characters and no path characters; exactly one of the two), target?, intent?, simulatePaper?, preserveNumbers?, simulateBlack? (as view.proofSetup; default: the current proof setup's)} write a custom proof setup to a VectorCraft proof setup file (.vcproof, JSON) without changing the proof view. The target must be a device: workingCmyk, cmyk: or rgb: → {path, target, intent, simulatePaper, preserveNumbers, simulateBlack}", + always, + proof_file::save + ), + cmd!( + query "view.proofSetup.load", + "Load Proof Setup…", + [], + None, + "{path?: file | name?: a setup in the Proof Setups folder (exactly one of the two)} read a proof setup file of at most 64 KiB that view.proofSetup.save wrote, make it the proof setup and turn Proof Colors on → {path} and the proof state. A file whose device names a profile that is not loaded is refused and nothing changes", + always, + proof_file::load + ), + cmd!( + query "view.proofSetup.read", + "Read Proof Setup", + [], + None, + "{path?: file | name?: a setup in the Proof Setups folder (exactly one of the two)} the settings of a proof setup file, read as view.proofSetup.load reads it, without changing the proof view → {path, target, intent, simulatePaper, preserveNumbers, simulateBlack}", + always, + proof_file::read + ), + cmd!( + query "view.proofSetup.list", + "Saved Proof Setups", + [], + None, + "{} the proof setup files in the Proof Setups folder next to the preferences, by name, at most 100 → {folder (null without the folder), setups: [{name, path}], truncated}", + always, + proof_file::list + ), cmd!(query "view.proofColors", "Proof Colors", ["View"], None, "{on?: bool (default: toggle)} → proof state", always, |s, p| { toggle_view(s, p, "view.proofColors", |v, on| v.proof_colors = on.unwrap_or(!v.proof_colors)) }), @@ -261,7 +299,7 @@ fn load_profile(s: &mut Session, p: &Value) -> Result { use_front_profiles(s); touch_all(s); } else if proof_targets(&info.name) { - // A new file of the CMYK profile View → Proof Setup targets: redraw. + // A new file of the profile View → Proof Setup targets: redraw. touch_all(s); } else { // Documents behind the front one draw through their own profiles: those assigned it redraw. @@ -292,7 +330,7 @@ fn remove_profile(s: &mut Session, p: &Value) -> Result { if active.rgb == name || active.cmyk == name { use_front_profiles(s); } - // The CMYK profile View → Proof Setup targets: redraw. + // The profile View → Proof Setup targets: redraw. if proof_targets(&info.name) { touch_all(s); } @@ -311,9 +349,9 @@ fn touch_assigned(s: &mut Session, name: &str) { } } -/// Whether View → Proof Setup targets the CMYK profile `name`. +/// Whether View → Proof Setup targets the CMYK or RGB profile `name`. fn proof_targets(name: &str) -> bool { - matches!(proof::view().setup.target, ProofTarget::Cmyk(t) if t == name) + matches!(proof::view().setup.target, ProofTarget::Cmyk(t) | ProofTarget::Rgb(t) if t == name) } #[cfg(target_arch = "wasm32")] @@ -1003,7 +1041,7 @@ impl PasteProfile { if o.keys().any(|k| k != "rgb" && k != "cmyk") { return Err(refuse()); } - let model = |m: &str| o.get(m).map(&one).transpose(); + let model = |m: &str| o.get(m).map(one).transpose(); Ok(Some(PasteChoice { rgb: model("rgb")?, cmyk: model("cmyk")? })) } Some(v) => { @@ -1324,10 +1362,15 @@ fn convert_color(_: &mut Session, p: &Value) -> Result { let intent = intent_param(p, C)?.unwrap_or(c.settings().intent); let lab = c.lab(&col); let (model, vals) = match text_param(p, "to", C)?.unwrap_or("rgb") { - "rgb" => ("rgb", values(&c.convert(&col, Model::Rgb, intent))), - "cmyk" => ("cmyk", values(&c.convert(&col, Model::Cmyk, intent))), - "gray" | "grayscale" => ("gray", values(&c.convert(&col, Model::Gray, intent))), - "lab" => ("lab", vec![lab.l, lab.a, lab.b]), + "rgb" => ("rgb", json!(values(&c.convert(&col, Model::Rgb, intent)))), + "cmyk" => ("cmyk", json!(values(&c.convert(&col, Model::Cmyk, intent)))), + "gray" | "grayscale" => ("gray", json!(values(&c.convert(&col, Model::Gray, intent)))), + "lab" => ("lab", json!([lab.l, lab.a, lab.b])), + "oklch" => { + // RGB numbers past 0..1 ([2, 2, 2]) display clipped, as `hex` reports them. + let [l, ch, h] = vectorcraft_color::oklab::to_oklch(c.display_rgb(&col).map(|v| v.clamp(0.0, 1.0))); + ("oklch", json!([l * 100.0, ch, h])) + } other => return Err(bad(C, format!("unknown model `{other}`"))), }; let de = c.gamut_error(&col); @@ -1392,6 +1435,8 @@ fn view_json(v: &proof::ProofView) -> Value { "target": v.setup.target.id(), "intent": v.setup.intent.id(), "simulatePaper": v.setup.simulate_paper, + "preserveNumbers": v.setup.preserve_numbers, + "simulateBlack": v.setup.simulate_black, "proofColors": v.proof_colors, "overprintPreview": v.overprint, "separations": v.separations, @@ -1401,19 +1446,7 @@ fn view_json(v: &proof::ProofView) -> Value { fn proof_setup(s: &mut Session, p: &Value) -> Result { const C: &str = "view.proofSetup"; let mut v = proof::view(); - if let Some(t) = text_param(p, "target", C)? { - let t = ProofTarget::parse(t).ok_or_else(|| bad(C, format!("unknown proof target `{t}`")))?; - if let ProofTarget::Cmyk(name) = &t - && !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Cmyk) - { - return Err(bad(C, format!("unknown CMYK profile `{name}`"))); - } - v.setup.target = t; - } - if let Some(i) = intent_param(p, C)? { - v.setup.intent = i; - } - v.setup.simulate_paper = switch_or(p, "simulatePaper", v.setup.simulate_paper, C)?; + setup_params(p, &mut v.setup, C)?; if let Some(on) = on_param(p, "proof", C)? { v.proof_colors = on; } @@ -1421,6 +1454,33 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result { Ok(view_json(&v)) } +/// Take the proof setup settings `p` gives (`target`, `intent`, `simulatePaper`, `preserveNumbers` +/// and `simulateBlack`, as `view.proofSetup` reads them) into `setup`. A `cmyk:` or `rgb:` target +/// must name a CMYK or RGB profile that is loaded. +fn setup_params(p: &Value, setup: &mut cms::ProofSetup, cmd: &str) -> Result<()> { + if let Some(t) = text_param(p, "target", cmd)? { + let t = ProofTarget::parse(t).ok_or_else(|| bad(cmd, format!("unknown proof target `{t}`")))?; + if let ProofTarget::Cmyk(name) = &t + && !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Cmyk) + { + return Err(bad(cmd, format!("unknown CMYK profile `{name}`"))); + } + if let ProofTarget::Rgb(name) = &t + && !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Rgb) + { + return Err(bad(cmd, format!("unknown RGB profile `{name}`"))); + } + setup.target = t; + } + if let Some(i) = intent_param(p, cmd)? { + setup.intent = i; + } + setup.simulate_paper = switch_or(p, "simulatePaper", setup.simulate_paper, cmd)?; + setup.preserve_numbers = switch_or(p, "preserveNumbers", setup.preserve_numbers, cmd)?; + setup.simulate_black = switch_or(p, "simulateBlack", setup.simulate_black, cmd)?; + Ok(()) +} + /// Make `v` the proof view and redraw every document. When `v` equals the current view, the view /// and the revisions stay as they are; Separations Preview's visible plates are compared as a set. fn store_view(s: &mut Session, v: proof::ProofView) { diff --git a/crates/engine/src/cmd/colormgmt/proof_file.rs b/crates/engine/src/cmd/colormgmt/proof_file.rs new file mode 100644 index 0000000000..7f92bed6b4 --- /dev/null +++ b/crates/engine/src/cmd/colormgmt/proof_file.rs @@ -0,0 +1,288 @@ +//! View → Proof Setup → Customize…'s Save… and Load…: a custom proof setup (the device to simulate, +//! Preserve Numbers, the rendering intent, Simulate Paper Color and Simulate Black Ink) in a file, +//! and the setups saved in the `Proof Setups` folder next to the preferences, which View → Proof +//! Setup lists ([`Session::attach_proof_setups`]). `view.proofSetup.read` reads a file without +//! applying it, which is how Load… fills the dialog. +//! +//! The file format is VectorCraft's own: JSON with `format` [`FORMAT`], `version` 1, `target`, +//! `intent`, `simulatePaper`, `preserveNumbers` and `simulateBlack`, as `view.proofSetup` names +//! them, at most [`MAX_FILE`] bytes. + +use serde_json::{Value, json}; +use vectorcraft_color::cms::{self, Intent, ProofSetup, ProofTarget}; +use vectorcraft_render::proof; + +use super::super::{EngineError, fileio}; +use super::{Result, Session, bad, setup_params, store_view, text_param, view_json}; + +/// The extension of a proof setup file. +pub const EXT: &str = "vcproof"; +/// The `format` a proof setup file names. +pub const FORMAT: &str = "vectorcraft-proof-setup"; +/// The format version this build writes and reads. +const VERSION: u64 = 1; +/// The largest proof setup file `view.proofSetup.load` reads, bytes (VectorCraft's own limit). +pub const MAX_FILE: usize = 64 << 10; +/// The most setups `view.proofSetup.list` lists. +pub const MAX_LISTED: usize = 100; +/// The most folder entries `view.proofSetup.list` looks at, setup files or not. +const MAX_SCANNED: usize = 100_000; +/// The longest `name`, in characters. +const MAX_NAME: usize = 100; + +impl Session { + /// Keep the proof setups that `view.proofSetup.save` saves by name in the folder `dir` (`Proof + /// Setups` next to the preferences), which `view.proofSetup.list` lists. The folder is made + /// when a setup is first saved there. + pub fn attach_proof_setups(&mut self, dir: std::path::PathBuf) { + self.proof_setup_dir = Some(dir); + } + + /// The saved proof setups' folder ([`Session::attach_proof_setups`]); none on the web. + pub fn proof_setup_dir(&self) -> Option<&std::path::Path> { + self.proof_setup_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) + } + + /// How many proof setup files `view.proofSetup.save` wrote in this session; the menus list the + /// Proof Setups folder again when it changes. + pub fn proof_setup_saves(&self) -> u64 { + self.proof_setup_saves + } +} + +/// The file `p` names for `cmd`: its `path`, or the setup `name` in the Proof Setups folder. +fn file_path(s: &Session, p: &Value, cmd: &str) -> Result<(String, bool)> { + match (text_param(p, "path", cmd)?, text_param(p, "name", cmd)?) { + (Some(path), None) if path.trim().is_empty() => Err(bad(cmd, "`path` is empty")), + (Some(path), None) => Ok((path.to_string(), false)), + (None, Some(name)) => { + let name = setup_name(name, cmd)?; + let dir = s.proof_setup_dir().ok_or_else(|| bad(cmd, "saved proof setups need the preferences folder, which this run doesn't have"))?; + let path = dir.join(format!("{name}.{EXT}")); + let path = path.to_str().ok_or_else(|| bad(cmd, format!("{}: the folder's path is not valid Unicode", dir.display())))?; + Ok((path.to_string(), true)) + } + (Some(_), Some(_)) => Err(bad(cmd, "give `path` or `name`, not both")), + (None, None) => Err(bad(cmd, "missing `path` or `name`")), + } +} + +/// `name` trimmed, when it can name a file in the Proof Setups folder: not empty, at most +/// [`MAX_NAME`] characters, no path or control characters, and not starting with a dot. +fn setup_name<'a>(name: &'a str, cmd: &str) -> Result<&'a str> { + let name = name.trim(); + if name.is_empty() { + return Err(bad(cmd, "`name` is empty")); + } + if name.chars().count() > MAX_NAME { + return Err(bad(cmd, format!("`name` is longer than {MAX_NAME} characters"))); + } + if name.starts_with('.') || name.chars().any(|c| c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|')) { + return Err(bad(cmd, format!("`name` can't hold path characters: `{name}`"))); + } + Ok(name) +} + +/// `Ok` when `t` is a device a custom proof setup can simulate and its profile is loaded. +fn check_device(t: &ProofTarget) -> std::result::Result<(), String> { + let loaded = |name: &str, kind| cms::profile(name).is_some_and(|k| k.kind == kind); + match t { + ProofTarget::WorkingCmyk => Ok(()), + ProofTarget::Cmyk(name) if loaded(name, cms::ProfileKind::Cmyk) => Ok(()), + ProofTarget::Rgb(name) if loaded(name, cms::ProfileKind::Rgb) => Ok(()), + ProofTarget::Cmyk(name) => Err(format!("the device to simulate is the CMYK profile `{name}`, which is not loaded")), + ProofTarget::Rgb(name) => Err(format!("the device to simulate is the RGB profile `{name}`, which is not loaded")), + t => Err(format!("`{}` is not a device to simulate: a custom proof setup simulates workingCmyk, cmyk: or rgb:", t.id())), + } +} + +/// The settings of `setup`, as `view.proofSetup` names them. +fn setup_json(setup: &ProofSetup) -> serde_json::Map { + let v = json!({ + "target": setup.target.id(), + "intent": setup.intent.id(), + "simulatePaper": setup.simulate_paper, + "preserveNumbers": setup.preserve_numbers, + "simulateBlack": setup.simulate_black, + }); + match v { + Value::Object(m) => m, + _ => serde_json::Map::new(), + } +} + +/// The proof setup in a file's `bytes`, or why it can't be read. +pub fn parse(bytes: &[u8]) -> std::result::Result { + let v: Value = serde_json::from_slice(bytes).map_err(|e| format!("not a proof setup file: {e}"))?; + if v.get("format").and_then(Value::as_str) != Some(FORMAT) { + return Err("not a VectorCraft proof setup file".into()); + } + match v.get("version").and_then(Value::as_u64) { + Some(VERSION) => {} + Some(n) if n > VERSION => return Err(format!("the file is version {n}, made by a newer VectorCraft")), + _ => return Err("the file has no version VectorCraft reads".into()), + } + let text = |key: &str| v.get(key).and_then(Value::as_str); + let target = text("target").ok_or("the file names no device to simulate")?; + let target = ProofTarget::parse(target).ok_or_else(|| format!("unknown proof target `{target}`"))?; + let intent = text("intent").ok_or("the file names no rendering intent")?; + let intent = Intent::parse(intent).ok_or_else(|| format!("unknown intent `{intent}`"))?; + let on = |key: &str| match v.get(key) { + None | Some(Value::Null) => Ok(false), + Some(Value::Bool(b)) => Ok(*b), + Some(_) => Err(format!("`{key}` must be true or false")), + }; + Ok(ProofSetup { + target, + intent, + simulate_paper: on("simulatePaper")?, + preserve_numbers: on("preserveNumbers")?, + simulate_black: on("simulateBlack")?, + separations: None, + }) +} + +/// A proof setup file holding `setup`. +pub fn encode(setup: &ProofSetup) -> Vec { + let mut m = serde_json::Map::new(); + m.insert("format".into(), json!(FORMAT)); + m.insert("version".into(), json!(VERSION)); + m.extend(setup_json(setup)); + let mut bytes = serde_json::to_vec_pretty(&Value::Object(m)).unwrap_or_default(); + bytes.push(b'\n'); + bytes +} + +pub(super) fn save(s: &mut Session, p: &Value) -> Result { + const C: &str = "view.proofSetup.save"; + let (path, named) = file_path(s, p, C)?; + let mut setup = proof::view().setup; + setup_params(p, &mut setup, C)?; + check_device(&setup.target).map_err(|e| bad(C, e))?; + // A file `view.proofSetup.load` would refuse is not written (a device with a very long name). + let bytes = encode(&setup); + if bytes.len() > MAX_FILE { + return Err(bad(C, format!("{path}: larger than {MAX_FILE} bytes"))); + } + if named + && let Some(dir) = std::path::Path::new(&path).parent() + && !dir.is_dir() + { + crate::file_access::check_write(&path).map_err(EngineError::Other)?; + std::fs::create_dir_all(dir).map_err(|e| bad(C, format!("{}: {e}", dir.display())))?; + } + fileio::write_file(&path, &bytes)?; + s.proof_setup_saves += 1; + let mut r = setup_json(&setup); + r.insert("path".into(), json!(path)); + Ok(Value::Object(r)) +} + +/// The file `p` names for `cmd` and the usable proof setup in it. +fn read_setup(s: &Session, p: &Value, cmd: &str) -> Result<(String, ProofSetup)> { + let (path, _) = file_path(s, p, cmd)?; + // One byte past the limit shows a file over it, which is not read further. + let bytes = fileio::read_file_head(&path, MAX_FILE + 1)?; + if bytes.len() > MAX_FILE { + return Err(bad(cmd, format!("{path}: larger than {MAX_FILE} bytes"))); + } + let setup = parse(&bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?; + check_device(&setup.target).map_err(|e| bad(cmd, format!("{path}: {e}")))?; + Ok((path, setup)) +} + +pub(super) fn read(s: &mut Session, p: &Value) -> Result { + let (path, setup) = read_setup(s, p, "view.proofSetup.read")?; + let mut r = setup_json(&setup); + r.insert("path".into(), json!(path)); + Ok(Value::Object(r)) +} + +pub(super) fn load(s: &mut Session, p: &Value) -> Result { + let (path, setup) = read_setup(s, p, "view.proofSetup.load")?; + let mut v = proof::view(); + // Separations Preview's plates are not part of a proof setup file. + v.setup = ProofSetup { separations: v.setup.separations.take(), ..setup }; + v.proof_colors = true; + store_view(s, v.clone()); + let mut r = view_json(&v); + r["path"] = json!(path); + Ok(r) +} + +pub(super) fn list(s: &mut Session, _: &Value) -> Result { + let none = json!({"folder": null, "setups": [], "truncated": false}); + let Some(dir) = s.proof_setup_dir() else { return Ok(none) }; + listed(dir).map(|l| l.unwrap_or(none)) +} + +/// The web keeps no saved setups ([`Session::proof_setup_dir`]). +#[cfg(target_arch = "wasm32")] +pub fn listed(_: &std::path::Path) -> Result> { + Ok(None) +} + +/// The listing of the Proof Setups folder `dir`, as `view.proofSetup.list` gives it; `None` for a +/// request that may not read it. The app calls it on another thread, without a session. +#[cfg(not(target_arch = "wasm32"))] +pub fn listed(dir: &std::path::Path) -> Result> { + const C: &str = "view.proofSetup.list"; + let folder = dir.to_string_lossy().into_owned(); + // A request that may not read the folder learns nothing of it, nor where it is. + if crate::file_access::check_read(&folder).is_err() { + return Ok(None); + } + // The listed paths are text: a folder whose path is not valid Unicode can't be named in them. + if dir.to_str().is_none() { + return Err(bad(C, format!("{folder}: the folder's path is not valid Unicode"))); + } + let entries = match std::fs::read_dir(dir) { + Ok(entries) => entries, + // No folder yet: nothing has been saved. + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Some(json!({"folder": folder, "setups": [], "truncated": false}))), + Err(e) => return Err(bad(C, format!("{folder}: {e}"))), + }; + // The setups' names, the first MAX_LISTED by name; other entries are passed over before the + // limit applies. A link is not followed. A file is listed only when it is named + // `.vcproof` and `name` takes that name unchanged, so each listed name loads its own + // file. An entry that can't be read, or whose file name is not valid Unicode, leaves the + // listing incomplete. + let (mut names, mut truncated) = (Vec::::new(), false); + for (i, e) in entries.enumerate() { + if i == MAX_SCANNED { + truncated = true; + break; + } + let Ok(e) = e else { + truncated = true; + continue; + }; + let Ok(file) = e.file_name().into_string() else { + truncated = true; + continue; + }; + let Some(name) = file.strip_suffix(EXT).and_then(|s| s.strip_suffix('.')) else { continue }; + if setup_name(name, C).ok() != Some(name) { + continue; + } + match e.file_type() { + Ok(t) if t.is_file() => {} + Ok(_) => continue, + Err(_) => { + truncated = true; + continue; + } + } + names.push(name.to_string()); + if names.len() > 2 * MAX_LISTED { + names.sort(); + names.truncate(MAX_LISTED); + truncated = true; + } + } + names.sort(); + truncated |= names.len() > MAX_LISTED; + names.truncate(MAX_LISTED); + let setups: Vec = names.iter().map(|name| json!({"name": name, "path": dir.join(format!("{name}.{EXT}")).to_string_lossy()})).collect(); + Ok(Some(json!({"folder": folder, "setups": setups, "truncated": truncated}))) +} diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 89752c1b33..f012bcfc82 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -105,6 +105,15 @@ pub fn specs() -> Vec { has_doc, arc ), + cmd!( + "shape.threePointArc", + "Three-Point Arc", + [], + None, + "{start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: \"start\"|\"end\" (default \"start\"; only with `toward`)} → {id, cx, cy, radius, sweep}: an open circular arc from `start` to `end` in the current stroke (black when it is none) with no fill, its ends exactly at the two points (not pixel-aligned). With `through`, the arc passes through that point, an anchor of the path; with `toward`, it leaves the end `at` names heading toward that point (its tangent there). Give exactly one of `through` and `toward`; `at` with `through` is an error. `sweep` is the arc's turn in degrees, positive clockwise on the page. Two points that are the same, three on one line, or an arc reaching past the canvas are an error, and nothing is drawn", + has_doc, + three_point_arc + ), cmd!( "shape.rectangularGrid", "Rectangular Grid", @@ -680,6 +689,50 @@ fn arc(s: &mut Session, p: &Value) -> Result { insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, bbox_angle, true) } +/// An open circular arc from `start` to `end` ([`shapes::CircularArc`]): through `through`, or +/// leaving the end `at` names toward `toward`. One undo step, named as an Arc tool drag is. +fn three_point_arc(s: &mut Session, p: &Value) -> Result { + const C: &str = "shape.threePointArc"; + let point = |key: &str| finite_numbers::<2>(&p[key]).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, format!("`{key}` must be [x, y]"))); + let (start, end) = (point("start")?, point("end")?); + let from_end = match p.get("at") { + None => false, + Some(Value::String(v)) if v == "start" || v == "end" => v == "end", + Some(_) => return Err(bad(C, "`at` must be \"start\" or \"end\"")), + }; + // The arc, and the point it passes through (an anchor of the path, so the path meets it exactly). + let (arc, via) = match (p.get("through"), p.get("toward")) { + (Some(_), None) if p.get("at").is_some() => return Err(bad(C, "give `at` only with `toward`")), + (Some(_), None) => { + let through = point("through")?; + (shapes::CircularArc::through(start, end, through), Some(through)) + } + (None, Some(_)) if from_end => { + let toward = point("toward")?; + (shapes::CircularArc::arriving(start, end, end - toward), None) + } + (None, Some(_)) => { + let toward = point("toward")?; + (shapes::CircularArc::leaving(start, toward - start, end), None) + } + _ => return Err(bad(C, "give exactly one of `through` and `toward`")), + }; + let arc = arc.ok_or_else(|| bad(C, "no arc fits these points: two are the same or all three lie on one line"))?; + let path = via.map_or_else(|| arc.to_path(), |v| arc.to_path_via(v)); + let look = s.new_art_look( + vectorcraft_color::Paint::None, + if s.paint.stroke.is_none() { vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK) } else { s.paint.stroke.clone() }, + s.paint.stroke_width.max(0.1), + ); + // Not pixel-aligned: the ends stay on the given points. + let mut out = insert_look_turned(s, "Arc", path_kind(path, None), look, None, true, 0.0, false)?; + out["cx"] = json!(arc.center.x); + out["cy"] = json!(arc.center.y); + out["radius"] = json!(arc.radius); + out["sweep"] = json!(arc.sweep.to_degrees()); + Ok(out) +} + /// The grid `paths` (bottom first) as one selected group in the new-art stroke, filled with the /// current fill when `fill`; a path of several subpaths becomes a compound path of them. The group /// and its members get the bounding-box angle `bbox_angle` (a grid drawn along a Constrain Angle). diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index 955401b923..e38f8f99bb 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -14,7 +14,7 @@ pub fn specs() -> Vec { "Create Dimension", [], None, - "{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits", + "{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits", has_doc, create ), @@ -565,7 +565,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) -> LineType::Solid => None, }; if arrows { - let head = o.arrow_style.arrowhead(); + let head = o.arrowhead(); st.start_arrow = head.clone(); st.end_arrow = head; st.arrow_scale = (o.arrow_scale, o.arrow_scale); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 5e0231228b..f5ee63f167 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1568,6 +1568,8 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho for xf in placements { for (k, n) in clip.nodes.iter().enumerate() { let mut c = d.reid(n); + // A pasted symbol set packs from the density recorded for it at Copy. + d.carry_set_densities(n, &c, &clip.set_densities); imported.apply(&mut c); let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() }; if xf != Affine::IDENTITY { diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs index cbfaa434d5..17e6c3f814 100644 --- a/crates/engine/src/cmd/fileio/psdlayers.rs +++ b/crates/engine/src/cmd/fileio/psdlayers.rs @@ -24,20 +24,28 @@ //! Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color, Lighter Color) is merged with the //! layers below it in its group. A Dissolve layer's partly transparent pixels are merged as opaque //! or transparent, opaque at the share of its pixels their transparency gives, in a fixed pattern -//! that differs from layer to layer. When a merge's canvases would need more memory than allowed, -//! the layer comes in alone: in the Normal mode, or unclipped. -//! Hidden layers are left out unless `hidden` asks for them. A hidden layer that would need a merge -//! (one in a mode VectorCraft lacks, one that layers are clipped to, one clipped to another, or -//! one below a merged layer) is always left out, with the layers clipped to it. Adjustment layers, -//! fill layers that store no pixels and whose fill isn't read or whose shape is a vector mask, -//! layer effects that are switched on, knockouts and vector masks aren't applied; the warnings -//! count them and the hidden layers left out. +//! that differs from layer to layer. A layer or group in a group whose Knockout setting is 1 (read +//! as a shallow knockout) is merged with the layers below it in its group too, as the import option +//! describes: where it has pixels, they are cleared to transparency and it is drawn there at its fill +//! opacity, and its opacity fades that back toward them. In a pass-through group this is done only +//! when it and the visible layers below it are in the Normal mode. When a merge's canvases would need more +//! memory than allowed, the layer comes in alone: in the Normal mode, unclipped, or without its +//! knockout. Hidden layers are left out unless `hidden` asks for them. A hidden layer that would need +//! a merge (one in a mode VectorCraft lacks, one with a knockout in a group that changes the layers +//! below it, one that layers are clipped to, one clipped to another, or one below a merged layer) is +//! always left out, with the layers clipped to it. Adjustment layers, fill layers that store no +//! pixels and whose fill isn't read or whose shape is a vector mask, layer effects that are switched +//! on, vector masks, and the knockouts of top-level layers, of clipped layers, of layers that others +//! are clipped to and of layers in a pass-through group with a layer in another mode, and other +//! Knockout values, aren't applied; the warnings count them and the hidden layers left out. //! //! The file is untrusted: every count, length and size is checked before anything is allocated, //! groups nest at most [`MAX_DEPTH`] deep (layers deeper than a document may nest merge into the //! group around them, with a warning), each layer's pixels, like the canvases one step of a //! merge holds together, must fit the memory allowed, and all the pixels decoded and the canvases -//! the merges make must fit [`TOTAL_DECODED`] times that. +//! the merges make must fit [`TOTAL_DECODED`] times that. A merge being tried may take that much +//! past what was read before it. What the merges that aren't made, or that a hidden layer would +//! need, decoded and made is counted apart, against the same limit. use std::cell::Cell; use std::sync::Arc; @@ -66,6 +74,13 @@ const MAX_CHANNELS: usize = 56; const MIN_RECORD: usize = 34; const DAMAGED: &str = "the PSD file's layer records are damaged"; +#[cfg(test)] +thread_local! { + /// The layer lists imports on this thread have walked, and the most a test lets them walk + /// before the import stops with an error. + pub(super) static WALKS: Cell<(usize, usize)> = const { Cell::new((0, usize::MAX)) }; +} + /// The keys of the tagged blocks that make a layer an adjustment layer. const ADJUSTMENTS: [&[u8; 4]; 18] = [ b"levl", b"curv", b"brit", b"blnc", b"hue ", b"hue2", b"selc", b"mixr", b"grdm", b"phfl", b"expA", b"vibA", b"thrs", b"nvrt", b"post", b"clrL", @@ -227,7 +242,9 @@ struct Record<'a> { content: Content, effects: bool, vector_mask: bool, - knockout: bool, + /// The Knockout setting's byte (`knko`): 0 none, 1 a shallow knockout. Any other value isn't + /// applied. + knockout: u8, } /// The layer records of `info` (the layer count, the records, then their channels' data). @@ -285,7 +302,7 @@ fn record<'a>(r: &mut Reader<'a>, psb: bool) -> Result<(Record<'a>, Vec<(i16, us content: Content::Pixels, effects: false, vector_mask: false, - knockout: false, + knockout: 0, }; rec.read_extra(extra, psb)?; Ok((rec, lengths)) @@ -345,8 +362,7 @@ impl Record<'_> { b"lfx2" | b"lmfx" => effects = Some(effects == Some(true) || effects_on(data)), b"lrFX" => old_effects = true, b"vmsk" | b"vsms" => self.vector_mask = true, - // Shallow or deep knockout. - b"knko" => self.knockout = data.first().is_some_and(|&k| k != 0), + b"knko" => self.knockout = data.first().copied().unwrap_or(0), k if ADJUSTMENTS.contains(&k) => self.content = Content::Adjustment, _ => {} } @@ -612,6 +628,8 @@ struct Unit<'i> { body: Body<'i>, /// While layers are clipped to it: how its merged canvas is shaped. clip: Option, + /// Layers are clipped to it, merged into it or not. + base: bool, } impl Unit<'_> { @@ -640,13 +658,36 @@ enum Clip { enum Body<'i> { /// A layer record's pixels. Layer(usize), - /// A group's layers. - Group(&'i [Item]), + /// A group's record and its layers. + Group(usize, &'i [Item]), /// Layers merged into one image. Merged(Canvas), } +/// Where a layer list is. +#[derive(Clone, Copy, PartialEq)] +enum Level { + /// The file's top level. + Top, + /// An isolated group, or a group drawn on its own. + Group, + /// A pass-through group whose layers blend with what is below it. + Pass, +} + +/// What a knockout's merge with the layers below it gives. +enum Knocked { + /// The merged canvas. + Merged(Canvas), + /// Nothing below it draws, it draws nothing, it is at 0 fill and cuts no painted pixel below + /// it, or what is below it and the merge are both transparent: it comes in as a layer of its own. + Nothing, + /// The canvases would need more memory than allowed. + TooLarge, +} + /// A unit's body drawn alone. +#[derive(Clone)] enum Drawn { /// It draws nothing. Nothing, @@ -663,6 +704,7 @@ struct Notes { fills: usize, effects: usize, vector_masks: usize, + /// Layers whose knockout wasn't applied. knockouts: usize, /// Hidden layers left out, and layers clipped to them. hidden: usize, @@ -677,11 +719,17 @@ struct Notes { /// The counts a merge that can't be made gives back. #[derive(Clone, Copy)] struct Counts { + /// The bytes spent so far (see [`Builder::spent`]). + spent: u64, skipped: usize, + /// The knockouts counted as not applied. + unknocked: usize, merged: usize, unmerged: usize, unclipped: usize, clipped_out: usize, + /// The groups found to read no pixels. + blank: usize, } /// Adds the warning for `n` things to `out`: `one` when `n` is 1, `many` with the count in place @@ -745,8 +793,17 @@ impl Notes { out } - fn counts(&self, skipped: usize) -> Counts { - Counts { skipped, merged: self.merged.len(), unmerged: self.unmerged, unclipped: self.unclipped, clipped_out: self.clipped_out } + fn counts(&self, spent: u64, skipped: usize, unknocked: usize, blank: usize) -> Counts { + Counts { + spent, + skipped, + unknocked, + merged: self.merged.len(), + unmerged: self.unmerged, + unclipped: self.unclipped, + clipped_out: self.clipped_out, + blank, + } } } @@ -767,12 +824,47 @@ struct Builder<'a, F> { notes: Notes, /// The records [`Notes`] counted. noted: Vec, + /// Those records, in the order they were counted. + noted_log: Vec, /// The records counted as hidden layers left out. skipped: Vec, /// Those records, in the order they were counted. skip_log: Vec, + /// The records counted as knockouts not applied. + unknocked: Vec, + /// Those records, in the order they were counted. + unknock_log: Vec, + /// The records counted as layers clipped to a fill that isn't drawn. + clipped_out: Vec, + /// Those records, in the order they were counted. + clipped_out_log: Vec, + /// The records counted as clipped layers left unclipped. + unclipped: Vec, + /// Those records, in the order they were counted. + unclip_log: Vec, + /// The records that came in as layers of the document (hidden ones too, with `hidden`): not left + /// out, though a drawing for a merge that wasn't made counted them. + kept: Vec, /// Bytes of layer and mask pixels decoded, and of canvases the merges made, so far. spent: Cell, + /// Those bytes that merges not made, and merges a hidden layer would need, took: given back to + /// `spent` and counted here instead, against the same limit. + wasted: Cell, + /// `spent` when the innermost merge being tried began: until it is made or given up, it may + /// spend the whole allowance past that (see [`Self::spend`]). + trial: Cell, + /// The layers whose pixels were read so far (each time they were). + painted: Cell, + /// What each group gave when drawn alone without reading any layer's pixels (nothing, or a + /// canvas without pixels, whatever the memory left): drawing it again gives that without + /// walking its layers. + blank: Vec>, + /// The pass-through groups that laid nothing onto nothing (see [`Self::laid_nothing`]). + laid_blank: Vec, + /// The groups of both, in the order they were found. + blank_log: Vec, + /// How many times a merge was counted as not made because it needed more memory than allowed. + squeezed: usize, } impl [f32; 3]> Builder<'_, F> { @@ -786,10 +878,38 @@ impl [f32; 3]> Builder<'_, F> { } /// Count `bytes` of decoded pixels, or of a canvas a merge makes, against the whole import's - /// allowance, [`TOTAL_DECODED`] times the memory allowed for one image. + /// allowance, [`TOTAL_DECODED`] times the memory allowed for one image. While a merge is tried + /// (see [`Self::try_from_here`]), only what it spent counts against the allowance. fn spend(&self, bytes: u64) -> Result<(), String> { let total = self.spent.get().saturating_add(bytes); self.spent.set(total); + if total.saturating_sub(self.trial.get()) > self.max_alloc.saturating_mul(TOTAL_DECODED) { + return Err("the PSD file's layers take more memory to read than allowed".into()); + } + Ok(()) + } + + /// Start trying a merge that may not be made: what it spends counts against the whole + /// allowance, however much was spent before it. Gives what [`Self::tried`] takes back. + fn try_from_here(&self) -> u64 { + self.trial.replace(self.spent.get()) + } + + /// End the merge tried since [`Self::try_from_here`] gave `outer`. A merge that is `made` keeps + /// what it spent, which must then fit the allowance with what was spent before it. + fn tried(&self, outer: u64, made: bool) -> Result<(), String> { + self.trial.set(outer); + if made { self.spend(0) } else { Ok(()) } + } + + /// Move the bytes spent since `spent` was the count to [`Self::wasted`], which has an allowance + /// of its own as large: what a merge that isn't made decoded doesn't take the room for reading + /// the layers apart. + fn refund(&self, spent: u64) -> Result<(), String> { + let since = self.spent.get().saturating_sub(spent); + self.spent.set(self.spent.get().min(spent)); + let total = self.wasted.get().saturating_add(since); + self.wasted.set(total); if total > self.max_alloc.saturating_mul(TOTAL_DECODED) { return Err("the PSD file's layers take more memory to read than allowed".into()); } @@ -814,6 +934,7 @@ impl [f32; 3]> Builder<'_, F> { Paint::Cmyk(ink) => (self.cmyk)(ink), }; let px = image::Rgba([byte(rgb[0]), byte(rgb[1]), byte(rgb[2]), 255]); + self.painted.set(self.painted.get() + 1); return Ok(Some((0, 0, RgbaImage::from_pixel(h.width, h.height, px)))); } Content::Pixels | Content::Type | Content::Solid(_) | Content::Fill => rec.bounds.size(), @@ -845,6 +966,7 @@ impl [f32; 3]> Builder<'_, F> { let rgb = to_rgb(h, |c| planes.get(c).map_or(0.0, |p| at(p, linear, 0.0)), &self.cmyk); image::Rgba([byte(rgb[0]), byte(rgb[1]), byte(rgb[2]), byte(at(&alpha, false, 1.0))]) }); + self.painted.set(self.painted.get() + 1); Ok(Some((i64::from(rec.bounds.left), i64::from(rec.bounds.top), img))) } @@ -897,7 +1019,7 @@ impl [f32; 3]> Builder<'_, F> { for item in items { let (i, body) = match item { Item::Layer(i) => (*i, Body::Layer(*i)), - Item::Group(i, children) => (*i, Body::Group(children)), + Item::Group(i, children) => (*i, Body::Group(*i, children)), }; let rec = self.record(i)?; let (name, hidden, clipped, blend) = (rec.name.clone(), rec.hidden, rec.clipped, rec.blend); @@ -920,14 +1042,26 @@ impl [f32; 3]> Builder<'_, F> { Some(b) => { // Counted even when it draws nothing (an adjustment layer). self.note(i)?; - if !unclipped && self.clip(&mut out, b, &body, i, &name, blend, opacity)? { + // A clipped layer's knockout isn't applied. + if self.record(i)?.knockout != 0 { + self.unknock(i); + } + if let Some(u) = out.get_mut(b) { + u.base = true; + } + let spent = self.spent.get(); + let outer = self.try_from_here(); + let made = !unclipped && self.clip(&mut out, b, &body, i, &name, blend, opacity)?; + self.tried(outer, made)?; + if made { continue; } + self.refund(spent)?; // The merge doesn't fit: this layer and the next ones clipped to the same // base come in as layers of their own. unclipped = true; - self.notes.unclipped += 1; - out.push(Unit { name, visible: true, opacity, blend, mask_of: Some(i), record: i, body, clip: None }); + self.unclip(i); + out.push(Unit { name, visible: true, opacity, blend, mask_of: Some(i), record: i, body, clip: None, base: false }); } } continue; @@ -939,7 +1073,7 @@ impl [f32; 3]> Builder<'_, F> { continue; } self.note(i)?; - out.push(Unit { name, visible: !hidden, opacity, blend, mask_of: Some(i), record: i, body, clip: None }); + out.push(Unit { name, visible: !hidden, opacity, blend, mask_of: Some(i), record: i, body, clip: None, base: false }); base = Some(Some(out.len() - 1)); } for u in &mut out { @@ -962,7 +1096,7 @@ impl [f32; 3]> Builder<'_, F> { }; // A fill whose shape is a vector mask isn't drawn, and nothing clipped to it is either. if undrawn && u.clip.is_none() { - self.notes.clipped_out += 1; + self.clip_out(i); return Ok(true); } let layer = match self.draw_body(body, Some(i))? { @@ -1045,12 +1179,15 @@ impl [f32; 3]> Builder<'_, F> { // Once, though a merge may draw it again. match self.noted.get_mut(i) { Some(true) => return Ok(()), - Some(n) => *n = true, + Some(n) => { + *n = true; + self.noted_log.push(i); + } None => {} } - let (content, empty, effects, vector_mask, knockout) = { + let (content, empty, effects, vector_mask) = { let rec = self.record(i)?; - (rec.content, rec.stores_nothing(), rec.effects, rec.vector_mask, rec.knockout) + (rec.content, rec.stores_nothing(), rec.effects, rec.vector_mask) }; match content { Content::Type => self.notes.types += 1, @@ -1062,10 +1199,59 @@ impl [f32; 3]> Builder<'_, F> { } self.notes.effects += usize::from(effects); self.notes.vector_masks += usize::from(vector_mask); - self.notes.knockouts += usize::from(knockout); Ok(()) } + /// What [`Self::note`] has counted so far: the length of its log, and the counts. + fn noted_so_far(&self) -> (usize, [usize; 5]) { + let n = &self.notes; + (self.noted_log.len(), [n.types, n.adjustments, n.fills, n.effects, n.vector_masks]) + } + + /// Forget what [`Self::note`] counted since `so_far`, for layers that are left out. + fn unnote(&mut self, (logged, counts): (usize, [usize; 5])) { + for i in self.noted_log.split_off(logged) { + if let Some(n) = self.noted.get_mut(i) { + *n = false; + } + } + let n = &mut self.notes; + [n.types, n.adjustments, n.fills, n.effects, n.vector_masks] = counts; + } + + /// Count record `i` as a layer whose knockout isn't applied (once). + fn unknock(&mut self, i: usize) { + if let Some(s) = self.unknocked.get_mut(i) + && !*s + { + *s = true; + self.notes.knockouts += 1; + self.unknock_log.push(i); + } + } + + /// Does unit `u`, at `level` above the units `below` it, take a shallow knockout this import + /// applies? Only a layer or group in a group, neither clipped nor a base of clipped layers, does; + /// in a pass-through group, only when it and the visible units below it are in the Normal mode, so + /// that none of them blends with what is below the group. Any other knockout is counted as not + /// applied. One at 0 opacity, or with no visible unit below it, changes nothing below it: it needs + /// no merge, and a hidden one isn't left out for it. + fn knocks(&mut self, u: &Unit<'_>, below: &[Unit<'_>], level: Level) -> Result { + let rec = self.record(u.record)?; + if rec.knockout == 0 { + return Ok(false); + } + let normal = |u: &Unit<'_>| u.blend == Blend::Mode(BlendMode::Normal); + let blends_out = level == Level::Pass && !(normal(u) && below.iter().filter(|b| b.visible).all(normal)); + let applies = rec.knockout == 1 && level != Level::Top && !blends_out && !rec.clipped && !u.base && !matches!(u.body, Body::Merged(_)); + // Its fill opacity isn't checked: at 0 fill it still clears what is below it. + let changes = rec.opacity > 0.0 && below.iter().any(|b| b.visible); + if !applies { + self.unknock(u.record); + } + Ok(applies && changes) + } + /// Count record `i` as a hidden layer left out (once). fn skip(&mut self, i: usize) { if let Some(s) = self.skipped.get_mut(i) @@ -1077,21 +1263,100 @@ impl [f32; 3]> Builder<'_, F> { } } - /// `items`' units with the layers in blend modes VectorCraft lacks merged with those below. - fn merged<'i>(&mut self, items: &'i [Item], keep_hidden: bool) -> Result>, String> { + /// Count record `i` as a layer clipped to a fill that isn't drawn (once). + fn clip_out(&mut self, i: usize) { + if let Some(s) = self.clipped_out.get_mut(i) + && !*s + { + *s = true; + self.notes.clipped_out += 1; + self.clipped_out_log.push(i); + } + } + + /// Count record `i` as a clipped layer left unclipped (once). + fn unclip(&mut self, i: usize) { + self.squeezed += 1; + if let Some(s) = self.unclipped.get_mut(i) + && !*s + { + *s = true; + self.notes.unclipped += 1; + self.unclip_log.push(i); + } + } + + /// `items`' units, at `level`, with the layers in blend modes VectorCraft lacks, and in a group + /// the layers with a shallow knockout, merged with those below. + fn merged<'i>(&mut self, items: &'i [Item], keep_hidden: bool, level: Level) -> Result>, String> { + #[cfg(test)] + { + let (walked, most) = WALKS.get(); + if walked >= most { + return Err("the import walked more layer lists than the test allows".into()); + } + WALKS.set((walked + 1, most)); + } let mut out: Vec> = vec![]; for mut u in self.units(items, keep_hidden)? { + // A hidden layer in a mode VectorCraft lacks would need the merge for its mode: it is left + // out without being drawn. + if !u.visible && matches!(u.blend, Blend::Other(_)) { + self.skip(u.record); + continue; + } + if self.knocks(&u, &out, level)? { + let saved = self.saved(); + let noted = self.noted_so_far(); + let squeezed = self.squeezed; + let outer = self.try_from_here(); + let knocked = self.knock(&out, &u)?; + self.tried(outer, u.visible && matches!(knocked, Knocked::Merged(_)))?; + match knocked { + // A hidden layer that would need the merge is left out, and nothing its drawing + // counted is counted. + Knocked::Merged(_) | Knocked::TooLarge if !u.visible => { + self.restore(saved)?; + self.unnote(noted); + self.skip(u.record); + continue; + } + Knocked::Merged(canvas) => { + self.take_merge(&mut out, &u, canvas); + if let Blend::Other(other) = u.blend + && !self.notes.merged.contains(&other.label()) + { + self.notes.merged.push(other.label()); + } + continue; + } + // Nothing below it, or nothing of its own, to knock out: it comes in as a layer, + // with the hidden layers its drawing left out (see `kept`). What its drawing + // read is read again when it comes in. A hidden one may still be left out by a + // later merge: what its drawing counted is counted when it comes in instead. + Knocked::Nothing if !u.visible => { + self.restore(saved)?; + self.unnote(noted); + } + // A merge below it that its held canvas left without the memory it needed may + // be made when they come in without it: what drawing them counted is given back + // and counted again then. + Knocked::Nothing if self.squeezed != squeezed => self.restore(saved)?, + Knocked::Nothing => self.refund(saved.spent)?, + Knocked::TooLarge => { + self.restore(saved)?; + self.squeezed += 1; + self.unknock(u.record); + } + } + } let Blend::Other(other) = u.blend else { out.push(u); continue; }; - // A hidden layer that would need the merge is left out. - if !u.visible { - self.skip(u.record); - continue; - } // A merge that can't be made counts nothing its groups would have counted. - let saved = self.notes.counts(self.skip_log.len()); + let saved = self.saved(); + let outer = self.try_from_here(); let made = match out.as_mut_slice() { // Onto the previous merge alone: composited onto its canvas, in place. [prev] if prev.is_merge() => { @@ -1113,45 +1378,20 @@ impl [f32; 3]> Builder<'_, F> { } _ => match self.merge(&out, &u)? { Some(canvas) => { - let mut name = String::new(); - for (k, b) in out.iter_mut().filter(|b| b.visible).enumerate() { - if k == 0 { - name = std::mem::take(&mut b.name); - } else { - name.push_str(" + "); - name.push_str(&b.name); - } - } - if out.iter().any(|b| b.visible) { - name.push_str(" + "); - } - name.push_str(&u.name); - // Hidden layers below are left out with the rest. - for b in out.iter().filter(|b| !b.visible).map(|b| b.record).collect::>() { - self.skip(b); - } - out.clear(); - out.push(Unit { - name, - visible: true, - opacity: 1.0, - blend: Blend::Mode(BlendMode::Normal), - mask_of: None, - record: u.record, - body: Body::Merged(canvas), - clip: None, - }); + self.take_merge(&mut out, &u, canvas); true } None => false, }, }; + self.tried(outer, made)?; if made { if !self.notes.merged.contains(&other.label()) { self.notes.merged.push(other.label()); } } else { - self.restore(saved); + self.restore(saved)?; + self.squeezed += 1; self.notes.unmerged += 1; u.blend = Blend::Mode(BlendMode::Normal); out.push(u); @@ -1160,18 +1400,51 @@ impl [f32; 3]> Builder<'_, F> { Ok(out) } - /// The counts as they were before a merge that couldn't be made. - fn restore(&mut self, c: Counts) { + /// The counts as they are, for [`Self::restore`]. + fn saved(&self) -> Counts { + self.notes.counts(self.spent.get(), self.skip_log.len(), self.unknock_log.len(), self.blank_log.len()) + } + + /// The counts as they were before a merge that couldn't be made, the bytes it spent counted as + /// wasted (see [`Self::refund`]). + fn restore(&mut self, c: Counts) -> Result<(), String> { + self.refund(c.spent)?; for i in self.skip_log.split_off(c.skipped) { if let Some(s) = self.skipped.get_mut(i) { *s = false; self.notes.hidden = self.notes.hidden.saturating_sub(1); } } + for i in self.unknock_log.split_off(c.unknocked) { + if let Some(s) = self.unknocked.get_mut(i) { + *s = false; + self.notes.knockouts = self.notes.knockouts.saturating_sub(1); + } + } + // The groups found since: what their drawing counted is given back, so they are drawn again. + for g in self.blank_log.split_off(c.blank) { + if let Some(b) = self.blank.get_mut(g) { + *b = None; + } + if let Some(b) = self.laid_blank.get_mut(g) { + *b = false; + } + } + for i in self.unclip_log.split_off(c.unclipped) { + if let Some(s) = self.unclipped.get_mut(i) { + *s = false; + self.notes.unclipped = self.notes.unclipped.saturating_sub(1); + } + } + for i in self.clipped_out_log.split_off(c.clipped_out) { + if let Some(s) = self.clipped_out.get_mut(i) { + *s = false; + self.notes.clipped_out = self.notes.clipped_out.saturating_sub(1); + } + } self.notes.merged.truncate(c.merged); self.notes.unmerged = c.unmerged; - self.notes.unclipped = c.unclipped; - self.notes.clipped_out = c.clipped_out; + Ok(()) } /// The visible units `below` with `top` composited over them; `None` when the canvas would need @@ -1186,24 +1459,169 @@ impl [f32; 3]> Builder<'_, F> { Ok(Some(acc.unwrap_or_default())) } + /// `out` replaced by one layer: `canvas`, the merge of its visible units with `top`, named after + /// them, bottom first. Its hidden units are left out. + fn take_merge<'i>(&mut self, out: &mut Vec>, top: &Unit<'_>, canvas: Canvas) { + let mut name = String::new(); + for (k, b) in out.iter_mut().filter(|b| b.visible).enumerate() { + if k == 0 { + name = std::mem::take(&mut b.name); + } else { + name.push_str(" + "); + name.push_str(&b.name); + } + } + if out.iter().any(|b| b.visible) { + name.push_str(" + "); + } + name.push_str(&top.name); + // Hidden layers below are left out with the rest. + for b in out.iter().filter(|b| !b.visible).map(|b| b.record).collect::>() { + self.skip(b); + } + out.clear(); + out.push(Unit { + name, + visible: true, + opacity: 1.0, + blend: Blend::Mode(BlendMode::Normal), + mask_of: None, + record: top.record, + body: Body::Merged(canvas), + clip: None, + base: false, + }); + } + + /// The visible units `below` with `top`, a layer with a shallow knockout, knocking them out: where + /// `top` has pixels, what is below it in its group is cleared to transparency (the group's own + /// backdrop) and `top` is drawn there at its fill opacity; its opacity then fades all of that + /// back toward the units below as they were. Its layer mask shapes the cut. + fn knock(&mut self, below: &[Unit<'_>], top: &Unit<'_>) -> Result { + let (fill, opacity) = { + let rec = self.record(top.record)?; + (rec.fill, rec.opacity) + }; + let k = match self.draw_body(&top.body, top.mask_of)? { + Drawn::Nothing => return Ok(Knocked::Nothing), + Drawn::TooLarge => return Ok(Knocked::TooLarge), + Drawn::Canvas(c) if c.px.iter().all(|p| p[3] <= 0.0) => return Ok(Knocked::Nothing), + Drawn::Canvas(c) => c, + }; + // At 0 fill, beside every layer below it, it cuts nothing: no canvas for them is needed. + if fill <= 0.0 && self.beside(below, &k)? { + return Ok(Knocked::Nothing); + } + // The layer's canvas is held while the units below are drawn. + let bytes = 16 * k.px.len() as u64; + self.held = self.held.saturating_add(bytes); + let mut acc: Option = None; + let mut drawn = Ok(true); + for u in below.iter().filter(|u| u.visible) { + drawn = self.composite(&mut acc, u); + if !matches!(drawn, Ok(true)) { + break; + } + } + self.held = self.held.saturating_sub(bytes); + if !drawn? { + return Ok(Knocked::TooLarge); + } + // Nothing below draws. + let Some(below) = acc.as_ref() else { return Ok(Knocked::Nothing) }; + // At 0 fill it draws nothing of its own: where it cuts no painted pixel below, no canvas for + // the merge is needed. + if fill <= 0.0 && !cuts_paint(below, &k, top.blend, opacity, top.record) { + return Ok(Knocked::Nothing); + } + let clear = |c: &Canvas| c.px.iter().all(|p| p[3] <= 0.0); + let below_clear = clear(below); + if !knock_onto(&mut acc, &k, top.blend, fill, opacity, top.record, self.room(), &|n| self.spend(n))? { + return Ok(Knocked::TooLarge); + } + // Nothing below to cut, and nothing of its own drawn at its fill opacity. + if below_clear && acc.as_ref().is_none_or(clear) { + return Ok(Knocked::Nothing); + } + Ok(acc.map_or(Knocked::Nothing, Knocked::Merged)) + } + + /// Do the pixels `knock` paints lie outside the bounds of every visible unit `below`? Only the + /// bounds of layers and of merged canvases are known without drawing them: with a group below, + /// `false`. + fn beside(&self, below: &[Unit<'_>], knock: &Canvas) -> Result { + let width = knock.width.max(1); + let mut painted: Option<[i64; 4]> = None; + for (k, _) in knock.px.iter().enumerate().filter(|(_, p)| p[3] > 0.0) { + let (x, y) = (knock.left + (k % width) as i64, knock.top + (k / width) as i64); + painted = Some(painted.map_or([x, y, x + 1, y + 1], |[l, t, r, b]| [l.min(x), t.min(y), r.max(x + 1), b.max(y + 1)])); + } + let Some([left, top, right, bottom]) = painted else { return Ok(true) }; + for u in below.iter().filter(|u| u.visible) { + let [l, t, r, b] = match &u.body { + Body::Merged(c) => [c.left, c.top, c.left + c.width as i64, c.top + c.height as i64], + Body::Layer(i) => { + let rec = self.record(*i)?; + match rec.content { + Content::Adjustment => continue, + Content::Solid(Some(_)) if rec.color_over_canvas() => [0, 0, i64::from(self.h.width), i64::from(self.h.height)], + _ => { + let (w, h) = rec.bounds.size(); + let (l, t) = (i64::from(rec.bounds.left), i64::from(rec.bounds.top)); + [l, t, l + w as i64, t + h as i64] + } + } + } + Body::Group(..) => return Ok(false), + }; + if l < right && left < r && t < bottom && top < b { + return Ok(false); + } + } + Ok(true) + } + /// The bytes a merge step may still take: the memory allowed, less the copies of what is below /// the pass-through groups being merged. fn room(&self) -> u64 { self.max_alloc.saturating_sub(self.held) } + /// Note pass-through group `g` as laying nothing onto nothing when `acc`, nothing before, still + /// is and no layer's pixels were read since `painted`: laying its layers onto nothing again + /// gives nothing, with the same notes. + fn laid_nothing(&mut self, g: usize, acc: &Option, painted: usize) { + if acc.is_none() + && self.painted.get() == painted + && let Some(b) = self.laid_blank.get_mut(g) + && !*b + { + *b = true; + self.blank_log.push(g); + } + } + /// Unit `u` composited onto `acc`. A pass-through group lays its layers onto `acc` one by one, /// so that they blend with what is below it; at less than full opacity or with a layer mask, the /// result is then faded back toward `acc` as it was by the opacity and the mask. Anything else /// is drawn alone first. `false` when the canvas would need more memory than allowed. fn composite(&mut self, acc: &mut Option, u: &Unit<'_>) -> Result { - if let (Body::Group(items), Blend::Pass) = (&u.body, u.blend) { + if let (Body::Group(g, items), Blend::Pass) = (&u.body, u.blend) { let mask = match u.mask_of { Some(i) if self.has_mask(Some(i))? => self.mask(i, false)?, _ => None, }; + // Onto nothing, a group that laid nothing onto nothing before lays nothing again. + let (fresh, painted) = (acc.is_none(), self.painted.get()); + if fresh && self.laid_blank.get(*g) == Some(&true) { + return Ok(true); + } if u.opacity >= 1.0 && mask.is_none() { - return self.lay(acc, items); + let laid = self.lay(acc, items, Level::Pass)?; + if laid && fresh { + self.laid_nothing(*g, acc, painted); + } + return Ok(laid); } let bytes = acc.as_ref().map_or(0, |c| 16 * c.px.len() as u64); if bytes > self.room() { @@ -1212,11 +1630,14 @@ impl [f32; 3]> Builder<'_, F> { self.spend(bytes)?; let below = acc.clone(); self.held = self.held.saturating_add(bytes); - let laid = self.lay(acc, items); + let laid = self.lay(acc, items, Level::Pass); self.held = self.held.saturating_sub(bytes); if !laid? { return Ok(false); } + if fresh { + self.laid_nothing(*g, acc, painted); + } if let Some(after) = acc.as_mut() { fade(after, below.as_ref(), u.opacity, mask.as_ref()); } @@ -1230,10 +1651,10 @@ impl [f32; 3]> Builder<'_, F> { blend_onto(acc, &c, u.blend, u.opacity, u.record, self.room(), &|n| self.spend(n)) } - /// `items`' layers composited onto `acc` one by one; `false` when a canvas would need more - /// memory than allowed. - fn lay(&mut self, acc: &mut Option, items: &[Item]) -> Result { - for c in self.merged(items, false)? { + /// `items`' layers, the layers of a group at `level`, composited onto `acc` one by one; `false` + /// when a canvas would need more memory than allowed. + fn lay(&mut self, acc: &mut Option, items: &[Item], level: Level) -> Result { + for c in self.merged(items, false, level)? { if !self.composite(acc, &c)? { return Ok(false); } @@ -1271,13 +1692,29 @@ impl [f32; 3]> Builder<'_, F> { } None => return Ok(Drawn::Nothing), }, - Body::Group(items) => { - let mut acc: Option = None; - if !self.lay(&mut acc, items)? { - return Ok(Drawn::TooLarge); + Body::Group(g, items) => { + let drawn = match self.blank.get(*g).cloned().flatten() { + Some(d) => d, + None => { + let painted = self.painted.get(); + let mut acc: Option = None; + if !self.lay(&mut acc, items, Level::Group)? { + return Ok(Drawn::TooLarge); + } + let d = acc.map_or(Drawn::Nothing, Drawn::Canvas); + if self.painted.get() == painted + && let Some(b) = self.blank.get_mut(*g) + { + *b = Some(d.clone()); + self.blank_log.push(*g); + } + d + } + }; + match drawn { + Drawn::Canvas(c) => c, + other => return Ok(other), } - let Some(acc) = acc else { return Ok(Drawn::Nothing) }; - acc } }; if let Some(i) = mask_of { @@ -1306,10 +1743,10 @@ impl [f32; 3]> Builder<'_, F> { Ok(n) } - /// Layers of the document for `items`, bottom first. - fn list(&mut self, items: &[Item]) -> Result>, String> { + /// Layers of the document for `items`, the layers at `level`, bottom first. + fn list(&mut self, items: &[Item], level: Level) -> Result>, String> { let mut out = vec![]; - for u in self.merged(items, self.hidden)? { + for u in self.merged(items, self.hidden, level)? { if let Some(n) = self.node(u)? { out.push(Arc::new(n)); } @@ -1320,6 +1757,9 @@ impl [f32; 3]> Builder<'_, F> { /// The layer of the document unit `u` becomes; `None` for a layer that draws nothing (an /// adjustment layer, or one without pixels). fn node(&mut self, u: Unit<'_>) -> Result, String> { + if let Some(k) = self.kept.get_mut(u.record) { + *k = true; + } let children = match &u.body { Body::Layer(i) => match self.image(*i)? { Some((left, top, img)) => vec![Arc::new(self.image_node(&u.name, left, top, img)?)], @@ -1329,13 +1769,13 @@ impl [f32; 3]> Builder<'_, F> { Some((left, top, img)) => vec![Arc::new(self.image_node(&u.name, left, top, img)?)], None => return Ok(None), }, - Body::Group(items) => self.list(items)?, + Body::Group(_, items) => self.list(items, if u.blend == Blend::Pass { Level::Pass } else { Level::Group })?, }; let mut layer = self.layer(&u.name); layer.visible = u.visible; layer.opacity = u.opacity.clamp(0.0, 1.0); (layer.blend, layer.isolate) = match u.blend { - Blend::Mode(m) => (m, matches!(u.body, Body::Group(_))), + Blend::Mode(m) => (m, matches!(u.body, Body::Group(..))), Blend::Pass | Blend::Other(_) => (BlendMode::Normal, false), }; if let Some(c) = layer.children_mut() { @@ -1443,6 +1883,71 @@ fn blend_onto( max_alloc: u64, spend: &dyn Fn(u64) -> Result<(), String>, ) -> Result { + if !cover(acc, src, max_alloc, spend)? { + return Ok(false); + } + let Some(out) = acc.as_mut() else { return Ok(false) }; + // Only the source's rows and columns change. + let (sw, x0, y0) = (src.width.max(1), (src.left - out.left) as usize, (src.top - out.top) as usize); + for (k, s) in src.px.iter().enumerate() { + let Some(p) = out.px.get_mut((y0 + k / sw) * out.width + x0 + k % sw) else { continue }; + let a = coverage(blend, s[3] * opacity, src.left + (k % sw) as i64, src.top + (k / sw) as i64, record); + *p = over(blend, *p, [s[0], s[1], s[2], a]); + } + Ok(true) +} + +/// `knock` (of record `record`, in `blend`, with its `fill` and `opacity`), a layer with a shallow +/// knockout, knocking out `acc`, on a canvas covering both, as [`blend_onto`] makes it. Where +/// `knock` has pixels, its transparency is the share of `acc` cleared and replaced by its color at +/// `fill`; `opacity` then fades that back toward `acc` (in Dissolve, each pixel is cleared fully +/// or not at all, at the share its transparency times `opacity` gives). `false`, with `acc` as it +/// was, when the canvases would take more than `max_alloc` bytes. +#[allow(clippy::too_many_arguments)] +fn knock_onto( + acc: &mut Option, + knock: &Canvas, + blend: Blend, + fill: f32, + opacity: f32, + record: usize, + max_alloc: u64, + spend: &dyn Fn(u64) -> Result<(), String>, +) -> Result { + if !cover(acc, knock, max_alloc, spend)? { + return Ok(false); + } + let Some(out) = acc.as_mut() else { return Ok(false) }; + let (fill, opacity) = (fill.clamp(0.0, 1.0), opacity.clamp(0.0, 1.0)); + let (kw, x0, y0) = (knock.width.max(1), (knock.left - out.left) as usize, (knock.top - out.top) as usize); + for (k, s) in knock.px.iter().enumerate() { + let Some(p) = out.px.get_mut((y0 + k / kw) * out.width + x0 + k % kw) else { continue }; + let t = coverage(blend, s[3].clamp(0.0, 1.0) * opacity, knock.left + (k % kw) as i64, knock.top + (k / kw) as i64, record); + let below = p[3].clamp(0.0, 1.0); + let alpha = (1.0 - t) * below + t * fill; + if alpha <= 0.0 { + *p = [0.0; 4]; + continue; + } + let mix = |i: usize| ((1.0 - t) * below * p[i] + t * fill * s[i]) / alpha; + *p = [mix(0), mix(1), mix(2), alpha]; + } + Ok(true) +} + +/// Does `knock`, as [`knock_onto`] takes it, clear any of a pixel of `below` that has paint? +fn cuts_paint(below: &Canvas, knock: &Canvas, blend: Blend, opacity: f32, record: usize) -> bool { + let (kw, opacity) = (knock.width.max(1), opacity.clamp(0.0, 1.0)); + knock.px.iter().enumerate().any(|(k, s)| { + let (x, y) = (knock.left + (k % kw) as i64, knock.top + (k / kw) as i64); + below.get(x, y).is_some_and(|b| b[3] > 0.0) && coverage(blend, s[3].clamp(0.0, 1.0) * opacity, x, y, record) > 0.0 + }) +} + +/// `acc` grown, when it doesn't already, to a canvas covering itself and `src` (a new one counted +/// with `spend`). `false`, with `acc` as it was, when the canvases held, `acc` and `src` and a +/// larger canvas when one is needed, would take more than `max_alloc` bytes. +fn cover(acc: &mut Option, src: &Canvas, max_alloc: u64, spend: &dyn Fn(u64) -> Result<(), String>) -> Result { let (mut left, mut top, mut right, mut bottom) = (src.left, src.top, src.left + src.width as i64, src.top + src.height as i64); if let Some(a) = acc.as_ref() { left = left.min(a.left); @@ -1475,14 +1980,6 @@ fn blend_onto( } *acc = Some(out); } - let Some(out) = acc.as_mut() else { return Ok(false) }; - // Only the source's rows and columns change. - let (sw, x0, y0) = (src.width.max(1), (src.left - left) as usize, (src.top - top) as usize); - for (k, s) in src.px.iter().enumerate() { - let Some(p) = out.px.get_mut((y0 + k / sw) * width + x0 + k % sw) else { continue }; - let a = coverage(blend, s[3] * opacity, src.left + (k % sw) as i64, src.top + (k / sw) as i64, record); - *p = over(blend, *p, [s[0], s[1], s[2], a]); - } Ok(true) } @@ -1521,11 +2018,28 @@ pub(super) fn import( layers: 0, notes: Notes::default(), noted: vec![false; records.len()], + noted_log: vec![], skipped: vec![false; records.len()], skip_log: vec![], + unknocked: vec![false; records.len()], + unknock_log: vec![], + clipped_out: vec![false; records.len()], + clipped_out_log: vec![], + unclipped: vec![false; records.len()], + unclip_log: vec![], + kept: vec![false; records.len()], spent: Cell::new(0), + wasted: Cell::new(0), + trial: Cell::new(0), + painted: Cell::new(0), + blank: vec![None; records.len()], + laid_blank: vec![false; records.len()], + blank_log: vec![], + squeezed: 0, }; - let layers = b.list(&items)?; + let layers = b.list(&items, Level::Top)?; + // A drawing for a knockout or a clip leaves hidden layers out; those that came in anyway aren't. + b.notes.hidden = b.skipped.iter().zip(&b.kept).filter(|&(s, k)| *s && !*k).count(); let Builder { mut doc, notes, .. } = b; if !layers.is_empty() { doc.layers = layers; diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs index 6c227c0e17..d5dccfd662 100644 --- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs +++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs @@ -646,6 +646,453 @@ fn dissolve_layers_merge_as_opaque_or_transparent_pixels() { assert!((32..=96).contains(&red), "{red} of 256 pixels show the lower layer: {r}"); } +/// A layer with a Knockout value of `knko` and a fill opacity of `fill`. +fn knockout(l: L, knko: u8, fill: u8) -> L { + let mut l = l; + l.blocks.push((*b"knko", vec![knko, 0, 0, 0])); + l.blocks.push((*b"iOpa", vec![fill])); + l +} + +/// A green layer under a group of `group_blend` holding a red layer and `cut` above it. +fn knockout_stack(group_blend: &'static [u8; 4], cut: L) -> Vec { + vec![ + layer("Outside", [0, 0, 4, 4], [0, 255, 0, 255]), + group_end(), + layer("Lower", [0, 0, 4, 4], [255, 0, 0, 255]), + cut, + group("Group", group_blend), + ] +} + +/// The names of the document's layers, and of the layers in its second one. +fn knockout_names(s: &Session) -> (Vec, Vec) { + let d = &s.doc().unwrap().doc; + let names = |ls: &[std::sync::Arc]| ls.iter().map(|l| name(l).to_string()).collect::>(); + (names(&d.layers), d.layers.get(1).and_then(|g| g.children()).map_or(vec![], |c| names(c))) +} + +/// A layer with a shallow knockout in a group merges with the layers below it in the group: its +/// shape clears them to transparency, it draws there at its fill opacity, and its opacity fades +/// that. What is outside the group stays a layer of its own and shows through. +#[test] +fn knockout_layers_merge_with_the_layers_below_them_in_their_group() { + let cut = |fill: u8, opacity: u8| knockout(L { opacity, ..layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]) }, 1, fill); + for (fill, opacity, at_cut) in [(0, 255, [0, 0, 0, 0]), (128, 255, [0, 0, 255, 128]), (0, 128, [255, 0, 0, 127]), (255, 255, [0, 0, 255, 255])] { + for group_blend in [b"norm", b"pass"] { + let (s, r) = open(&file(4, 4, &knockout_stack(group_blend, cut(fill, opacity)), 8, false, false), json!({})); + assert_eq!(r["warnings"], json!([]), "{r}"); + let (top, inner) = knockout_names(&s); + assert_eq!((top, inner), (vec!["Outside".to_string(), "Group".into()], vec!["Lower + Cut".to_string()]), "{fill} {opacity}"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers[1].isolate, group_blend == b"norm"); + let ((x, y), px) = image_of(&s, &d.layers[1].children().unwrap()[0]); + assert_eq!(((x, y), px.dimensions()), ((0.0, 0.0), (4, 4))); + assert_eq!((px.get_pixel(1, 1).0, px.get_pixel(3, 3).0), (at_cut, [255, 0, 0, 255]), "{fill} {opacity}"); + } + } + // A layer mask shapes the cut: where it hides the layer, nothing below is cleared. + let mut masked = cut(0, 255); + masked.mask = Some(([0, 0, 1, 1], 255, 0, vec![0])); + let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", masked), 8, false, false), json!({})); + let px = image_of(&s, &s.doc().unwrap().doc.layers[1].children().unwrap()[0]).1; + assert_eq!((px.get_pixel(0, 0).0, px.get_pixel(1, 1).0), ([255, 0, 0, 255], [0, 0, 0, 0]), "{r}"); + // Without a knockout (0), the layers stay apart. + let (s, r) = + open(&file(4, 4, &knockout_stack(b"norm", knockout(layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]), 0, 0)), 8, false, false), json!({})); + assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([])), "{r}"); +} + +/// The knockouts this import doesn't apply come in as layers, counted in a warning: at the top level, +/// on a clipped layer, and with a Knockout value other than 1. Hidden ones that would need the merge +/// are left out; one that draws nothing, or nothing below it, merges nothing. +#[test] +fn knockouts_that_arent_applied_are_said() { + const UNAPPLIED: &str = "the knockout of 1 layer wasn't applied"; + let cut = |l: L, knko: u8| knockout(l, knko, 0); + let blue = || layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]); + // At the top level. + let layers = [layer("Lower", [0, 0, 4, 4], [255, 0, 0, 255]), cut(blue(), 1)]; + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({})); + assert_eq!((knockout_names(&s).0, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}"); + // Another Knockout value, and a clipped layer, in a group. + let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", cut(blue(), 2)), 8, false, false), json!({})); + assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}"); + let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", cut(L { clipped: true, ..blue() }, 1)), 8, false, false), json!({})); + assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower + Cut".to_string()], &json!([UNAPPLIED])), "{r}"); + // In a pass-through group, a layer below it, or the knockout itself, in another mode blends with + // what is outside the group: the layers stay apart, and the lower one still multiplies the green + // outside. In an isolated group they merge. + let mut multiply = knockout_stack(b"pass", cut(blue(), 1)); + multiply[2].blend = b"mul "; + let (s, r) = open(&file(4, 4, &multiply, 8, false, false), json!({})); + assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}"); + assert_eq!(s.doc().unwrap().doc.layers[1].children().unwrap()[0].blend, BlendMode::Multiply); + let (s, r) = open(&file(4, 4, &knockout_stack(b"pass", cut(L { blend: b"mul ", ..blue() }, 1)), 8, false, false), json!({})); + assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}"); + multiply[4] = group("Group", b"norm"); + let (s, r) = open(&file(4, 4, &multiply, 8, false, false), json!({})); + assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower + Cut".to_string()], &json!([])), "{r}"); + // A hidden knockout would need the merge: left out, hidden layers asked for or not. + for hidden in [false, true] { + let (s, r) = + open(&file(4, 4, &knockout_stack(b"norm", cut(L { hidden: true, ..blue() }, 1)), 8, false, false), json!({"hiddenLayers": hidden})); + assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string()], &json!([HIDDEN_1])), "{hidden}: {r}"); + } + // One that stores no pixels or only transparent ones cuts nothing, and merges nothing. + for (l, inner) in [(L { bare: true, ..blue() }, vec!["Lower"]), (layer("Cut", [0, 0, 2, 2], [0, 0, 255, 0]), vec!["Lower", "Cut"])] { + let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", cut(l, 1)), 8, false, false), json!({})); + assert_eq!((knockout_names(&s).1, &r["warnings"]), (inner.iter().map(|n| n.to_string()).collect(), &json!([])), "{r}"); + } + // Nothing below it in its group: it comes in as a layer. + let layers = [group_end(), cut(blue(), 1), group("Group", b"norm"), layer("Over", [0, 0, 1, 1], [9, 9, 9, 255])]; + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + assert_eq!(d.layers[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Cut"], "{r}"); + assert_eq!(r["warnings"], json!([]), "{r}"); +} + +/// A knockout that changes nothing below it leaves the layers apart, hidden ones included: one at 0 +/// opacity, one at 0 fill over layers that are transparent or beside their painted pixels, and one +/// whose layer mask hides all of it. At 0 fill over painted layers, and +/// at a fill over transparent ones, it still merges. A knockout at 0 fill over a transparent layer +/// stays apart without a warning when their merge would need more memory than allowed. +#[test] +fn knockouts_that_change_nothing_keep_the_layers_apart() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let layers = [ + group_end(), + layer("Lower", [0, 0, 2, 2], [255, 0, 0, 0]), + knockout(layer("Cut", [2, 2, 4, 4], [0, 0, 255, 255]), 1, 0), + group("Group", b"norm"), + ]; + // The two 2 × 2 layers drawn together fit 256 bytes, but not the 4 × 4 canvas covering both. + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 256, cms).unwrap().unwrap(); + assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Lower", "Cut"]); + assert!(warnings.is_empty(), "{warnings:?}"); + let lower = |alpha: u8| layer("Lower", [0, 0, 4, 4], [255, 0, 0, alpha]); + let hidden = L { hidden: true, ..layer("Hidden", [0, 0, 4, 4], [0, 255, 0, 255]) }; + let cut = |fill: u8, opacity: u8| knockout(L { opacity, ..layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]) }, 1, fill); + let inner = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(vec![], |c| c.iter().map(|l| name(l).to_string()).collect::>()); + for (alpha, fill, opacity, apart) in [(255, 0, 0, true), (0, 0, 255, true), (255, 0, 255, false), (0, 128, 255, false)] { + let layers = [group_end(), lower(alpha), hidden.clone(), cut(fill, opacity), group("Group", b"norm")]; + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true})); + let (names, warnings) = if apart { (vec!["Lower", "Hidden", "Cut"], json!([])) } else { (vec!["Lower + Cut"], json!([HIDDEN_1])) }; + assert_eq!((inner(&s), &r["warnings"]), (names.iter().map(|n| n.to_string()).collect(), &warnings), "{alpha} {fill} {opacity}: {r}"); + } + // A hidden knockout that needs no merge comes in with hidden layers: at 0 opacity, with nothing + // below it in its group, at 0 fill beside the painted pixels below it, and with a layer mask that + // hides all of it. + let hidden_cut = |opacity: u8| L { hidden: true, ..cut(0, opacity) }; + let beside = L { hidden: true, ..knockout(layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]), 1, 0) }; + let masked = L { hidden: true, mask: Some(([0, 0, 2, 2], 0, 0, vec![0; 4])), ..cut(255, 255) }; + for (layers, names) in [ + (vec![group_end(), lower(255), hidden_cut(0), group("Group", b"norm")], vec!["Lower", "Cut"]), + (vec![group_end(), hidden_cut(255), group("Group", b"norm")], vec!["Cut"]), + (vec![group_end(), layer("Lower", [2, 2, 4, 4], [255, 0, 0, 255]), beside, group("Group", b"norm")], vec!["Lower", "Cut"]), + (vec![group_end(), lower(255), masked.clone(), group("Group", b"norm")], vec!["Lower", "Cut"]), + ] { + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true})); + assert_eq!((inner(&s), &r["warnings"]), (names.iter().map(|n| n.to_string()).collect(), &json!([])), "{r}"); + } + // With the mask switched off it would need the merge, and is left out. + let unmasked = L { mask: Some(([0, 0, 2, 2], 0, 2, vec![0; 4])), ..masked }; + let (s, r) = open(&file(4, 4, &[group_end(), lower(255), unmasked, group("Group", b"norm")], 8, false, false), json!({"hiddenLayers": true})); + assert_eq!((inner(&s), &r["warnings"]), (vec!["Lower".to_string()], &json!([HIDDEN_1])), "{r}"); + // A hidden knockout group that would need the merge is counted once, as a hidden layer left out: + // its type layer and its own hidden layer aren't counted. + let mut words = layer("Words", [0, 0, 2, 2], [0, 0, 0, 255]); + words.blocks.push((*b"TySh", vec![0; 4])); + let layers = [ + group_end(), + lower(255), + group_end(), + words.clone(), + L { hidden: true, ..layer("Inner", [0, 0, 2, 2], [0, 0, 255, 255]) }, + L { hidden: true, ..knockout(group("Cut", b"norm"), 1, 255) }, + group("Group", b"norm"), + ]; + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true})); + assert_eq!((inner(&s), &r["warnings"]), (vec!["Lower".to_string()], &json!([HIDDEN_1])), "{r}"); + // One whose layer mask hides all of it needs no merge, but a knockout above it merges the layers + // and leaves it out: it is counted once, without its type layer. + let layers = [ + group_end(), + lower(255), + group_end(), + words, + L { hidden: true, mask: Some(([0, 0, 2, 2], 0, 0, vec![0; 4])), ..knockout(group("Masked", b"norm"), 1, 255) }, + cut(0, 255), + group("Group", b"norm"), + ]; + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true})); + assert_eq!((inner(&s), &r["warnings"]), (vec!["Lower + Cut".to_string()], &json!([HIDDEN_1])), "{r}"); +} + +/// With hidden layers asked for, the hidden layers of a group drawn for a knockout or a clip that +/// isn't made come in, and aren't counted as left out: a knockout group over a layer that stores no +/// pixels, and a clipped group whose merge needs more memory than allowed. +#[test] +fn hidden_layers_of_a_group_drawn_for_a_merge_not_made_come_in() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let children = |l: &Node| l.children().map_or(vec![], |c| c.iter().map(|l| (name(l).to_string(), l.visible)).collect::>()); + let shown_and_hidden = + || [group_end(), layer("Shown", [0, 0, 2, 2], [0, 0, 255, 255]), L { hidden: true, ..layer("Hidden", [2, 2, 4, 4], [0, 255, 0, 255]) }]; + let both = vec![("Shown".to_string(), true), ("Hidden".to_string(), false)]; + // A knockout group over a layer that stores no pixels. + let mut layers = vec![group_end(), L { bare: true, ..layer("Lower", [0, 0, 2, 2], [0; 4]) }]; + layers.extend(shown_and_hidden()); + layers.extend([knockout(group("Cut", b"norm"), 1, 255), group("Group", b"norm")]); + let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true})); + let d = &s.doc().unwrap().doc; + let cut = &d.layers[0].children().unwrap()[0]; + assert_eq!((name(cut), children(cut), &r["warnings"]), ("Cut", both.clone(), &json!([])), "{r}"); + // A clipped group whose merge with its base doesn't fit 320 bytes. + let mut layers = vec![layer("Base", [0, 0, 2, 2], [255, 0, 0, 255])]; + layers.extend(shown_and_hidden()); + layers[2].rect = [0, 0, 4, 4]; + layers.push(L { clipped: true, ..group("Clipped", b"norm") }); + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), true, 320, cms).unwrap().unwrap(); + let clipped = &doc.layers[1]; + assert_eq!((name(clipped), children(clipped)), ("Clipped", both), "{warnings:?}"); + assert_eq!(warnings, ["1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed"]); +} + +/// A knockout's merge whose canvases would need more memory than allowed leaves the layers apart, +/// with a warning. One at 0 fill beside the painted pixels below it cuts nothing, and stays apart +/// whatever the memory. +#[test] +fn a_knockout_merge_past_the_memory_allowed_leaves_the_layers_apart() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let stack = |cut: [i32; 4]| { + let layers = [ + group_end(), + layer("Lower", [0, 0, 2, 2], [255, 0, 0, 255]), + knockout(layer("Cut", cut, [0, 0, 255, 255]), 1, 0), + group("Group", b"norm"), + ]; + file(4, 4, &layers, 8, false, false) + }; + let names = |doc: &vectorcraft_doc::Document| doc.layers[0].children().unwrap().iter().map(|c| name(c).to_string()).collect::>(); + let f = stack([1, 1, 3, 3]); + // Each 2 × 2 layer fits 128 bytes (16 a pixel), but not the canvas of the layer below with the + // knockout's canvas held beside it. + let (doc, warnings) = psdlayers::import(&f, false, 128, cms).unwrap().unwrap(); + assert_eq!(names(&doc), ["Lower", "Cut"]); + assert_eq!(warnings, ["the knockout of 1 layer wasn't applied"]); + let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(names(&doc), ["Lower + Cut"]); + assert!(warnings.is_empty(), "{warnings:?}"); + for max_alloc in [128, 1 << 20] { + let (doc, warnings) = psdlayers::import(&stack([2, 2, 4, 4]), false, max_alloc, cms).unwrap().unwrap(); + assert_eq!(names(&doc), ["Lower", "Cut"], "{max_alloc}"); + assert!(warnings.is_empty(), "{max_alloc}: {warnings:?}"); + } +} + +/// A knockout that cuts nothing gives back what drawing the layers below it counted: here a +/// knockout at 0 fill beside a group, whose own knockout doesn't fit 192 bytes while the outer +/// knockout's canvas is held, but merges when the group comes in. +#[test] +fn a_knockout_that_cuts_nothing_doesnt_keep_what_drawing_below_it_counted() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let layers = [ + group_end(), + group_end(), + layer("Opaque", [0, 0, 2, 2], [255, 0, 0, 255]), + knockout(layer("Inner cut", [0, 0, 1, 2], [0, 0, 255, 255]), 1, 0), + group("Inner", b"norm"), + knockout(layer("Outer cut", [2, 2, 4, 4], [0, 0, 255, 255]), 1, 0), + group("Outer", b"norm"), + ]; + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 192, cms).unwrap().unwrap(); + let outer = doc.layers[0].children().unwrap(); + assert_eq!(outer.iter().map(|c| name(c)).collect::>(), ["Inner", "Outer cut"], "{warnings:?}"); + assert_eq!(outer[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Opaque + Inner cut"], "{warnings:?}"); + assert!(warnings.is_empty(), "{warnings:?}"); +} + +/// A knockout merge that can't be made leaves the import the whole allowance for reading the layers +/// apart: here the merge decodes 22 layers over one another before the layer beside them makes its +/// canvas too large, which used up nearly all of eight times 64 KiB. The merge has that allowance +/// also after five layers below the group were read, and a knockout at 0 fill over 22 transparent +/// layers, which cuts no paint after they are drawn, leaves the same room. +#[test] +fn a_knockout_merge_not_made_leaves_room_to_read_the_layers() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let mut layers = vec![group_end()]; + layers.extend((0..22).map(|_| layer("Lower", [0, 0, 32, 32], [255, 0, 0, 255]))); + layers.push(layer("Beside", [0, 64, 32, 96], [0, 255, 0, 255])); + layers.extend([knockout(layer("Cut", [0, 0, 32, 32], [0, 0, 255, 255]), 1, 0), group("Group", b"norm")]); + let (doc, warnings) = psdlayers::import(&file(96, 32, &layers, 8, false, false), false, 64 << 10, cms).unwrap().unwrap(); + assert_eq!(doc.layers[0].children().unwrap().len(), 24, "{warnings:?}"); + assert_eq!(warnings, ["the knockout of 1 layer wasn't applied"]); + let mut after_five = vec![layer("Outside", [0, 0, 32, 32], [0, 0, 0, 255]); 5]; + after_five.extend(layers); + let (doc, warnings) = psdlayers::import(&file(96, 32, &after_five, 8, false, false), false, 64 << 10, cms).unwrap().unwrap(); + assert_eq!((doc.layers.len(), doc.layers[5].children().unwrap().len()), (6, 24), "{warnings:?}"); + assert_eq!(warnings, ["the knockout of 1 layer wasn't applied"]); + let mut layers = vec![group_end()]; + layers.extend((0..22).map(|_| layer("Lower", [0, 0, 32, 32], [255, 0, 0, 0]))); + layers.extend([knockout(layer("Cut", [0, 0, 32, 32], [0, 0, 255, 255]), 1, 0), group("Group", b"norm")]); + let (doc, warnings) = psdlayers::import(&file(32, 32, &layers, 8, false, false), false, 64 << 10, cms).unwrap().unwrap(); + assert_eq!(doc.layers[0].children().unwrap().len(), 23, "{warnings:?}"); + assert!(warnings.is_empty(), "{warnings:?}"); +} + +/// A hidden knockout in a mode VectorCraft lacks is left out without being drawn, hidden layers +/// asked for: here its pixels are larger than the memory allowed for one image. +#[test] +fn a_hidden_knockout_in_a_mode_vectorcraft_lacks_is_left_out_unread() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let layers = [ + group_end(), + layer("Lower", [0, 0, 2, 2], [255, 0, 0, 255]), + L { hidden: true, blend: b"diss", ..knockout(layer("Cut", [0, 0, 8, 8], [0, 0, 255, 255]), 1, 255) }, + group("Group", b"norm"), + ]; + let (doc, warnings) = psdlayers::import(&file(8, 8, &layers, 8, false, false), true, 128, cms).unwrap().unwrap(); + assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Lower"]); + assert_eq!(warnings, [HIDDEN_1]); +} + +/// A Dissolve knockout at part opacity clears each pixel below it fully or not at all, at the share +/// its opacity gives, as a Dissolve layer merges. +#[test] +fn a_dissolve_knockout_at_part_opacity_clears_whole_pixels() { + let cut = knockout(L { blend: b"diss", opacity: 128, ..layer("Cut", [0, 0, 16, 16], [0, 0, 255, 255]) }, 1, 0); + let layers = [group_end(), layer("Lower", [0, 0, 16, 16], [255, 0, 0, 255]), cut, group("Group", b"norm")]; + let (s, r) = open(&file(16, 16, &layers, 8, false, false), json!({})); + let d = &s.doc().unwrap().doc; + let (_, px) = image_of(&s, &d.layers[0].children().unwrap()[0]); + assert!(px.pixels().all(|p| p.0 == [255, 0, 0, 255] || p.0[3] == 0), "{r}"); + let red = px.pixels().filter(|p| p.0 == [255, 0, 0, 255]).count(); + assert!((32..=224).contains(&red), "{red} of 256 pixels keep the lower layer: {r}"); +} + +/// The knockout of a layer that another is clipped to isn't applied, also when the clipped layer's +/// merge with it needs more memory than allowed and the two come in apart. +#[test] +fn a_clipping_base_knockout_isnt_applied_when_its_clip_doesnt_fit() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + // The 4 × 4 clipped layer and its 2 × 2 base don't fit 320 bytes together for the clip; the + // base's knockout merge with the 2 × 2 layer below would. + let layers = [ + group_end(), + layer("Lower", [0, 0, 2, 2], [255, 0, 0, 255]), + knockout(layer("Base", [0, 0, 2, 2], [0, 0, 255, 255]), 1, 0), + L { clipped: true, ..layer("Clipped", [0, 0, 4, 4], [0, 255, 0, 255]) }, + group("Group", b"norm"), + ]; + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 320, cms).unwrap().unwrap(); + assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Lower", "Base", "Clipped"], "{warnings:?}"); + assert_eq!( + warnings, + ["the knockout of 1 layer wasn't applied", "1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed"] + ); +} + +/// A knockout group that comes in as a layer counts each layer clipped in it once in the warnings, +/// though its layers are also drawn for the knockout: one clipped to a fill that isn't drawn, and +/// one that a merge past the memory allowed leaves unclipped. +#[test] +fn a_knockout_group_that_comes_in_as_a_layer_counts_its_clipped_layers_once() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let empty = L { bare: true, ..layer("Empty", [0, 0, 2, 2], [0, 0, 0, 0]) }; + // A fill whose shape is a vector mask, with a layer clipped to it: neither is drawn. + let mut soco = vec![0; 8]; + for (key, v) in [(b"Rd doub", 255.0f64), (b"Grn doub", 0.0), (b"Bl doub", 51.0)] { + soco.extend(key); + soco.extend(v.to_be_bytes()); + } + let mut outline = layer("Outline", [0, 0, 0, 0], [0; 4]); + outline.blocks.push((*b"SoCo", soco)); + outline.blocks.push((*b"vsms", vec![0; 8])); + let on_outline = L { clipped: true, ..layer("On outline", [0, 0, 2, 2], [1, 1, 1, 255]) }; + // Each 2 × 2 layer fits 128 bytes, and so do the two drawn together, but not the merge of the + // clipped one with the one below. + let base = layer("Base", [0, 0, 2, 2], [255, 0, 0, 255]); + let clipped = L { clipped: true, ..layer("Clipped", [0, 0, 2, 2], [0, 0, 255, 255]) }; + for (inner, said) in [ + (vec![outline, on_outline], "1 layer clipped to a fill layer that wasn't drawn was left out"), + (vec![base, clipped], "1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed"), + ] { + let mut layers = vec![layer("Outside", [0, 0, 4, 4], [0, 255, 0, 255]), group_end(), empty.clone(), group_end()]; + layers.extend(inner); + layers.extend([knockout(group("Cut", b"norm"), 1, 255), group("Group", b"norm")]); + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 128, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Outside", "Group"]); + assert!(warnings.iter().any(|w| w == said), "{said}: {warnings:?}"); + } +} + +/// A pass-through group that draws nothing still counts what its layers count in it, also when it +/// is drawn again inside a group that merges: a knockout above a Multiply layer isn't applied in a +/// pass-through group, though drawn alone it would be. +#[test] +fn a_pass_through_group_that_draws_nothing_still_counts_its_unapplied_knockouts() { + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let empty = |name: &'static str, blend: &'static [u8; 4]| L { bare: true, blend, ..layer(name, [0, 0, 2, 2], [0, 0, 0, 0]) }; + let layers = [ + layer("Lower", [0, 0, 4, 4], [255, 0, 0, 255]), + group_end(), + empty("Empty", b"norm"), + group_end(), + empty("Multiplied", b"mul "), + knockout(empty("Cut", b"norm"), 1, 255), + knockout(group("Through", b"pass"), 1, 255), + group("Dissolved", b"diss"), + ]; + let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 1 << 20, cms).unwrap().unwrap(); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Lower + Dissolved"], "{warnings:?}"); + assert_eq!(warnings, ["the knockout of 1 layer wasn't applied".to_string(), psdlayers::MERGED_WARNING.replace("{modes}", "Dissolve")]); +} + +/// A group that draws nothing is drawn once, however deep the groups like it nest: here each holds +/// a layer that stores no pixels and, above it, the next group, with a knockout. The import walks +/// at most as many layer lists as the file has records, with isolated groups, with groups that +/// alternate with pass-through ones, with pass-through groups inside the outermost one (whose +/// knockouts aren't applied), and with a layer in a mode VectorCraft lacks in each (a merge of +/// nothing, a canvas without pixels). +#[test] +fn groups_that_draw_nothing_are_drawn_once_however_deep_they_nest() { + const LEVELS: usize = 48; + let cms = |c: [f32; 4]| [c[0], c[1], c[2]]; + let empty = |name: &'static str, blend: &'static [u8; 4]| L { bare: true, blend, ..layer(name, [0, 0, 2, 2], [0, 0, 0, 0]) }; + // Which levels are pass-through groups. + let none: fn(usize) -> bool = |_| false; + let odd: fn(usize) -> bool = |k| k % 2 == 1; + let all: fn(usize) -> bool = |k| k > 0; + for (case, pass, dissolve, warned) in [ + ("isolated", none, false, vec![]), + ("alternating", odd, false, vec![]), + ("pass-through", all, false, vec![format!("the knockout of {} layers wasn't applied", LEVELS - 1)]), + ("dissolved", none, true, vec![psdlayers::MERGED_WARNING.replace("{modes}", "Dissolve")]), + ] { + let mut layers = vec![layer("Outside", [0, 0, 4, 4], [0, 255, 0, 255])]; + for _ in 0..=LEVELS { + layers.push(group_end()); + if dissolve { + layers.push(empty("Dissolved", b"diss")); + } + layers.push(empty("Empty", b"norm")); + } + for k in (0..=LEVELS).rev() { + let g = group("Group", if pass(k) { b"pass" } else { b"norm" }); + layers.push(if k == 0 { g } else { knockout(g, 1, 255) }); + } + psdlayers::WALKS.set((0, layers.len())); + let imported = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 1 << 20, cms); + let (walked, _) = psdlayers::WALKS.replace((0, usize::MAX)); + let (doc, warnings) = imported.unwrap().unwrap(); + assert!(walked <= layers.len(), "{case}: {walked} walks for {} records", layers.len()); + assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Outside", "Group"], "{case}"); + let mut expected = warned; + expected.push(vectorcraft_doc::depth::merged_note()); + assert_eq!(warnings, expected, "{case}"); + } +} + #[test] fn what_doesnt_come_in_is_said() { let mut text = layer("Words", [0, 0, 2, 2], [0, 0, 0, 255]); diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 746749235b..f5270c9780 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Gradient", ["Window", "Gradient"], None, - "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the paint the bucket paints with)", + "{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected, the Live Paint Bucket's gradient, or a fill edit of a Live Paint group without faces: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the paint the bucket paints with)", has_doc, edit_gradient ), @@ -117,6 +117,17 @@ impl StopOwner { } impl Session { + /// Does `paint.editGradient` without `ids` edit objects on the fill (or the stroke, `stroke`)? It does not + /// while the Live Paint Bucket is active or when nothing it can paint is selected (a Live Paint group stands + /// only for its faces in a fill edit and its edges in a stroke edit): it then edits no object and takes no + /// `aspect`. + pub fn gradient_edit_has_objects(&self, stroke: bool) -> bool { + let p = json!({ "stroke": stroke }); + !super::paint::for_bucket(self, &p) + && item_target(self, &p, "paint.editGradient") + .is_ok_and(|item| item.of_kind(self, !stroke).targets_for(self, &p, !stroke).is_ok_and(|ids| !ids.is_empty())) + } + /// The selected gradient stop (`gradient.selectStop`), while the gradient it was selected on /// is still the one behind the active proxy. Callers check it against the stop count (an undo /// can remove stops). @@ -547,6 +558,12 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result { // Objects were given or selected, even when all of them are graph design art left out below, or Live Paint group parts // of the other kind left out above: the stroke mode is then not one for new art. let selected = !ids.is_empty() || skipped; + // The default gradient for new art (and the bucket's) is fitted to each object, so it has no aspect of its own. A + // Live Paint group with no part of the edited kind gives no object either. Graph design art is left out below + // without an error, as for every other param. + if ids.is_empty() && p.get("aspect").is_some() { + return Err(bad(C, "`aspect` needs objects to place the gradient on: give ids or select objects")); + } let ids = super::appearance::drop_design_art_rows(s, ids, item, !stroke, C)?; // How the gradient lies on a stroke (the panel's Stroke buttons). let mode = match str_param(p, "strokeMode") { diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index cfb87afdb3..d2e3f7b95a 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -244,12 +244,22 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(C, "handle must be in or out")), }; let independent = switch_or(p, "independent", false, C)?; + let symmetric = switch_or(p, "symmetric", false, C)?; let link = switch_or(p, "link", false, C)?; let with = spine_points_param(p, C)?; // Any `with`, even an empty list, asks to move points, which a handle drag doesn't. if handle.is_some() && p.get("with").is_some_and(|v| !v.is_null()) { return Err(bad(C, "`with` moves points, not a handle")); } + if symmetric && independent { + return Err(bad(C, "`independent` and `symmetric` cannot both be true")); + } + if symmetric && handle.is_none() { + return Err(bad(C, "`symmetric` places a handle: give `handle`")); + } + if link && symmetric { + return Err(bad(C, "`link` and `symmetric` cannot both be true")); + } if link && independent { return Err(bad(C, "`link` and `independent` cannot both be true")); } @@ -264,6 +274,8 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result { } edit_spine(s, p, C, "Reshape Spine", |sp, anchors, keys| { let pull_out = handle.is_some_and(|out| sp.has_segment(index, !out)); + // At an open end of the spine the handle moves as it would without `symmetric`. + let symmetric = symmetric && pull_out; let a = sp.anchors.get_mut(index).ok_or_else(|| bad(C, "no such spine point"))?; if let Some(out) = handle { if link { @@ -271,6 +283,10 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result { } else { a.set_handle(out, q, independent); } + if symmetric { + let opposite = a.p - (q - a.p); + if out { a.h_in = opposite } else { a.h_out = opposite } + } return Ok(()); } let delta = q - a.p; diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index 991ebf103c..7d23f34a77 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Move Spine Point", [], None, - "{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `link` needs `handle` and cannot go with `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path", + "{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, symmetric?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `symmetric` mirrors the opposite handle about the anchor without changing its kind, except at an open end of the spine; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `symmetric` and `link` need `handle`, `symmetric` cannot go with `independent`, and `link` cannot go with `independent` or `symmetric`; all default false). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path", has_doc, spine_move_anchor ), diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 2f80e3b6c6..e5ff38efa6 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -305,7 +305,7 @@ pub fn specs() -> Vec { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index 02edf6193b..b2e69cc279 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -202,6 +202,16 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { // A polygon's Polygon Properties: its angle, radius or side length, Make Sides Equal. let (polygon_angle, polygon_radius, side) = (angle("polygonAngle")?, length("polygonRadius")?, length("sideLength")?); let equal = p.get("makeSidesEqual").and_then(Value::as_bool) == Some(true); + // A rectangle's Rectangle Angle and an ellipse's Ellipse Angle, as `polygonAngle` turns a polygon. + let (rectangle_angle, ellipse_angle) = (angle("rectangleAngle")?, angle("ellipseAngle")?); + // Whether a shape at `now` already stands at `a`: a turn the rounding of an earlier one left + // (89.999999999°, or 359.9999999999° against 0°) counts as no change. + let at_angle = |now: Option, a: f64| { + now.is_some_and(|n| { + let d = (n - a).rem_euclid(360.0); + d.min(360.0 - d) < 1e-9 + }) + }; // A line's Line Properties: its length (its first end stays) and its angle (about its midpoint). // A line's length can reach across the whole canvas, past `MAX_COORD`: its ends are checked below. let line_length = number("lineLength", |x| x > 0.0, "a length in points above 0")?; @@ -249,12 +259,15 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { Some(l @ LiveShape::Polygon { sides: now, .. }) if !(sides.is_none_or(|n| n.clamp(3, 1000) == u64::from(*now)) && (!equal || l.polygon_sides_equal()) - && polygon_angle.is_none_or(|a| l.polygon_angle() == Some(a)) + && polygon_angle.is_none_or(|a| at_angle(l.polygon_angle(), a)) && side.and_then(|len| l.polygon_radius_for_side(len)).or(polygon_radius).is_none_or(|r| l.polygon_radius() == Some(r))) => { return false; } - Some(LiveShape::Ellipse { pie, .. }) if pie_of(*pie) != *pie => return false, + Some(l @ LiveShape::Ellipse { pie, .. }) if pie_of(*pie) != *pie || ellipse_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => { + return false; + } + Some(l @ LiveShape::Rectangle { .. }) if rectangle_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => return false, _ => {} } if relative_radii.is_some_and(|on| live.as_deref().map(|l| l.radii_relative()) != Some(on)) { @@ -298,9 +311,18 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } *path = l.to_path(); } - if let Some(l @ LiveShape::Ellipse { .. }) = live.as_deref_mut() - && (pie_start.is_some() || pie_end.is_some() || invert) + if let Some(a) = rectangle_angle + && let Some(l @ LiveShape::Rectangle { .. }) = live.as_deref_mut() { + l.set_shape_angle(a); + *path = l.to_path(); + } + if let Some(l @ LiveShape::Ellipse { .. }) = live.as_deref_mut() + && (pie_start.is_some() || pie_end.is_some() || invert || ellipse_angle.is_some()) + { + if let Some(a) = ellipse_angle { + l.set_shape_angle(a); + } if let LiveShape::Ellipse { pie, .. } = l { *pie = pie_of(*pie); } @@ -339,6 +361,11 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { for id in &ids { super::pixelgrid::resnap(d, *id); } + // A shape named in `ids` and not selected is not checked after the edit: one that a turn or + // a new radius would take past the coordinate limit is an error here, and nothing changes. + if !crate::sanity::objects_in_range(d, &ids) { + return Err(bad("object.setLiveShape", format!("coordinate out of range (limit ±{MAX_COORD} pt)"))); + } Ok(()) })?; ok() diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 6d01cabd2a..d32594d92d 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -50,7 +50,7 @@ pub fn specs() -> Vec { "Move Direction Handle", [], None, - "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); link and independent cannot both be true; both default false; with link false, at moves the anchor and both handles before placing the chosen handle", + "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle", has_doc, set_handle ), @@ -461,6 +461,13 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { return link_handle(s, p, id, si, ai, out, pos); } let independent = switch_or(p, "independent", false, "path.setHandle")?; + let symmetric = switch_or(p, "symmetric", false, "path.setHandle")?; + if symmetric && independent { + return Err(bad("path.setHandle", "`independent` and `symmetric` cannot both be true")); + } + // The other handle is mirrored only where a segment leaves the anchor on its side: at an open + // end the handle moves as it would without `symmetric`. + let symmetric = symmetric && has_segment(s, id, si, ai, !out)?; let at = match p.get("at").filter(|v| !v.is_null()) { None => None, Some(v) => Some(finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad("path.setHandle", "`at` must be [x, y]"))?), @@ -472,6 +479,7 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { && at.is_none_or(|to| to == a.p) && (if out { a.h_out } else { a.h_in }) == pos && !(independent && a.kind != AnchorKind::Corner) + && (!symmetric || (if out { a.h_in } else { a.h_out }) == a.p - (pos - a.p)) { return ok(); } @@ -504,6 +512,10 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { } else { a.set_handle(out, pos, independent); } + if symmetric { + let opposite = a.p - (pos - a.p); + if out { a.h_in = opposite } else { a.h_out = opposite } + } Ok(()) })?; ok() @@ -519,6 +531,9 @@ fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out if switch_or(p, "independent", false, C)? { return Err(bad(C, "`link` and `independent` cannot both be true")); } + if switch_or(p, "symmetric", false, C)? { + return Err(bad(C, "`link` and `symmetric` cannot both be true")); + } if !(pos.x.abs() < 1e9 && pos.y.abs() < 1e9) { return Err(bad(C, "x and y must be finite")); } @@ -655,6 +670,16 @@ fn anchor_of(s: &Session, id: NodeId, si: usize, ai: usize) -> Result Result { + if s.script_running() { + return Err(EngineError::Busy); + } + let d = &s.doc()?.doc; + Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).is_some_and(|sp| sp.has_segment(ai, out))) +} + fn set_anchors(s: &mut Session, p: &Value) -> Result { let id = object_param(p, "id", "path.setAnchors")?.ok_or_else(|| bad("path.setAnchors", "missing id"))?; let subs = p.get("subpaths").and_then(Value::as_array).ok_or_else(|| bad("path.setAnchors", "missing subpaths"))?; diff --git a/crates/engine/src/cmd/patterncmds.rs b/crates/engine/src/cmd/patterncmds.rs index 57f9094e48..e4b6d810a6 100644 --- a/crates/engine/src/cmd/patterncmds.rs +++ b/crates/engine/src/cmd/patterncmds.rs @@ -9,12 +9,13 @@ //! **Repeat** objects are live nodes (`NodeKind::Repeat`) holding the source art and the //! arrangement; `vectorcraft_doc::pattern` evaluates the instances. +use std::collections::HashSet; use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::Paint; use vectorcraft_doc::pattern::{self, Overlap, PATTERN_EDIT_LAYER, PatternDef, PatternEdit, RepeatKind, RepeatSpec, TileType, pattern_paint}; -use vectorcraft_doc::swatches::PaintFn; +use vectorcraft_doc::swatches::{PaintFn, graph_paints, node_paints, override_paints, walk_with_masks}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection}; use vectorcraft_geom::{Point, Rect}; @@ -37,6 +38,15 @@ pub fn specs() -> Vec { can_make_pattern, pattern_make ), + cmd!( + "object.pattern.replaceArt", + "Replace Pattern Art", + [], + None, + "{name, ids?} make copies of the selected art the tile art of pattern `name`, as Alt-dragging (Option-dragging on macOS) art onto its swatch in the Swatches panel does; the pattern keeps its name, swatch, tile and options (with Size Tile to Art on, the tile fits the new art), every fill and stroke painted with it draws the new tile, and the art stays on the canvas, selected; one undo step, none when the art matches the tile art already; refused while a pattern is edited, with nothing selected, and for art painted with the pattern itself → {name}", + can_replace_pattern_art, + pattern_replace_art + ), cmd!( "object.pattern.edit", "Edit Pattern", @@ -198,6 +208,12 @@ fn has_selection_or_ids(s: &Session) -> std::result::Result<(), String> { has_doc(s) } +/// Replace Pattern Art: a document, and no pattern is being edited. +fn can_replace_pattern_art(s: &Session) -> std::result::Result<(), String> { + has_doc(s)?; + if editing(s).is_some() { Err("finish editing the pattern first".into()) } else { Ok(()) } +} + /// The repeats of the selection: selected ones, and those around a selected object. None while /// an object of a dynamic symbol instance's art is selected. fn selected_repeats(s: &Session) -> Vec { @@ -412,6 +428,103 @@ pub(crate) fn finish_edit(d: &mut Document, sel: &mut Selection) -> Result Result { + const C: &str = "object.pattern.replaceArt"; + let name = text_param(p, "name", C)?.ok_or_else(|| bad(C, "missing name"))?.to_string(); + let roots = roots(s, p, C)?; + let d = &s.doc()?.doc; + let old = d.pattern(&name).map(|def| def.art.clone()).ok_or_else(|| bad(C, format!("no pattern `{name}`")))?; + if roots.is_empty() { + return Err(bad(C, "select the art for the pattern tile")); + } + let src: Vec> = roots.iter().filter_map(|id| d.node(*id).cloned()).map(Arc::new).collect(); + if paints_pattern(d, &src, &name) { + return Err(bad(C, format!("art painted with `{name}` can't be its tile"))); + } + // Copies made from the same next id are equal when the art matches the tile art. + let fresh = |art: &[Arc]| copies(&mut Document::clone(d), art); + if fresh(&old) == fresh(&src) { + return Ok(json!({ "name": name })); + } + s.edit("Replace Pattern Art", |d, _| { + let art: Vec> = copies(d, &src).into_iter().map(Arc::new).collect(); + if let Some(def) = d.pattern_mut(&name) { + def.art = art; + if def.size_tile_to_art { + def.fit_tile_to_art(); + } + } + Ok(()) + })?; + Ok(json!({ "name": name })) +} + +/// What a piece of art uses by name, for [`paints_pattern`]. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +enum Uses<'a> { + Symbol(&'a str), + Pattern(&'a str), + GraphDesign(&'a str), + Brush(&'a str), +} + +/// Does `art` paint pattern `name`, itself or through the symbols (of its instances and of the +/// inline graphics in its type), patterns, graph designs and brushes it uses? A graph's stored +/// series and label paints count, since its marks and labels take them each time it is drawn again. +fn paints_pattern(d: &Document, art: &[Arc], name: &str) -> bool { + let brushes = vectorcraft_brush::library(d); + // What was already looked into, and the art left to look at. + let mut seen: HashSet = HashSet::new(); + let mut left: Vec<&Node> = art.iter().map(|a| &**a).collect(); + while let Some(n) = left.pop() { + let mut used = vec![]; + walk_with_masks(n, &mut |c| { + match &c.kind { + NodeKind::SymbolInstance { symbol, .. } => used.push(Uses::Symbol(symbol.as_str())), + // The symbol of every inline graphic in type counts, overset or not. + NodeKind::Text(t) => used.extend(t.runs.iter().filter_map(|r| r.inline.as_ref()).map(|a| Uses::Symbol(a.symbol.as_str()))), + _ => {} + } + for it in &c.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(sk) = it + && let Some(b) = &sk.brush + { + used.push(Uses::Brush(b.as_str())); + } + } + for p in node_paints(c).chain(override_paints(c)).chain(graph_paints(c)) { + if let Paint::Pattern { pattern, .. } = p { + used.push(Uses::Pattern(pattern.as_str())); + } + } + if let Some(g) = c.extras().graph.as_deref() { + used.extend(g.series_markers.iter().flatten().map(|m| Uses::GraphDesign(m.as_str()))); + used.extend(g.series_columns.iter().flatten().map(|c| Uses::GraphDesign(c.design.as_str()))); + } + }); + for u in used { + if u == Uses::Pattern(name) { + return true; + } + if !seen.insert(u) { + continue; + } + match u { + Uses::Symbol(symbol) => left.extend(d.symbols.iter().find(|x| x.name == symbol).map(|x| &*x.art)), + Uses::Pattern(pattern) => left.extend(d.pattern(pattern).into_iter().flat_map(|x| x.art.iter().map(|a| &**a))), + Uses::GraphDesign(design) => left.extend(d.graph_designs.iter().find(|x| x.name == design).map(|x| &*x.art)), + Uses::Brush(brush) => left.extend(brushes.iter().filter(|x| x.name == brush).flat_map(|x| x.art())), + } + } + } + false +} + /// Leave pattern editing mode, discarding the changes (`object.pattern.cancel`). An existing /// pattern gets its definition back, its name included when Pattern Options renamed it while it was /// edited and no other pattern, swatch or color group has taken that name since. A new pattern is diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index e09e362550..fa41a609c8 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -363,6 +363,7 @@ pub(super) const ALLOWED: &[&str] = &[ "object.pattern.done", "object.pattern.edit", "object.pattern.make", + "object.pattern.replaceArt", "object.puppetWarp", "object.puppetWarp.pins", "object.rasterize", @@ -571,6 +572,7 @@ pub(super) const ALLOWED: &[&str] = &[ "shape.rectangularGrid", "shape.spiral", "shape.star", + "shape.threePointArc", "shapeBuilder.merge", "shapeBuilder.regions", "shaper.expand", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index f66322498e..49b6680bde 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -752,6 +752,13 @@ impl Session { t.set_option("cornerRadius", &r); } } + // A press of the tool that is dropped keeps the new radius, also when the tool lent a + // selection tool for the press. + if self.press_taken_by("roundedRectangle") + && let Some((_, saved)) = self.press_options.as_mut() + { + saved.insert("cornerRadius".into(), r); + } } if fonts_folder_changed { let folder = self.prefs.fonts_folder.trim(); diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index cc5c7f4dce..cf46d853d8 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; setting hidden, createAlias and execute return false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; setting hidden, createAlias and execute return false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 01c8f913d1..f1e47b889a 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", has_doc, stroke_set ), diff --git a/crates/engine/src/cmd/swatch.rs b/crates/engine/src/cmd/swatch.rs index 76003551cd..511352b9a5 100644 --- a/crates/engine/src/cmd/swatch.rs +++ b/crates/engine/src/cmd/swatch.rs @@ -6,7 +6,7 @@ use serde_json::{Value, json}; use vectorcraft_color::{Color, Gradient, GradientKind, GradientMethod, GradientStop, Paint, Swatch, SwatchGroup, tint_percent}; use vectorcraft_doc::pattern::pattern_paint; use vectorcraft_doc::swatches::{LinkFn, PaintFn, color_name, map_node_paints, map_node_solid_paints, node_colors}; -use vectorcraft_doc::{Document, NodeId}; +use vectorcraft_doc::{Document, NodeId, Selection}; use super::paint::paint_from; use super::{ @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Add Used Colors", ["Window", "Swatches"], None, - "{selection?: false (only the selected art's colours; default: all the art's), global?: false (the new swatches are global and the matching unlinked colours in that art link to them)} add a swatch for each colour used (fills, strokes, text, gradient stops, mesh points) that no solid swatch has yet, as one undo step → {added: [names], linked}", + "{selection?: false (only the selected art's colours; default: all the art's), global?: false (the new swatches are global and the matching unlinked colours in that art link to them)} add a swatch for each colour used (fills, strokes, text, gradient stops, mesh points) that no solid swatch has yet, as one undo step (none when there is no new color; the Swatches panel menu's Add Selected Colors sends selection and global; with Global Edit on, the other members keep their colors) → {added: [names], linked}", has_doc, swatch_add_used ), @@ -1037,20 +1037,41 @@ fn swatch_sort(s: &mut Session, _: &Value) -> Result { ok() } +/// The colors of the art `ids` that no swatch links them to and no solid swatch has, each once, in +/// paint order: the swatches Add Used Colors makes. +fn new_used_colors(d: &Document, ids: &[NodeId]) -> Vec { + let (mut linked_to, mut colors) = (vec![], vec![]); + artwork_colors(d, ids, false, &mut linked_to, &mut colors); + // Colors a solid swatch already has are skipped. + let have: HashSet = d.swatches_iter().filter_map(|w| w.paint.color()).filter_map(|c| color_key(&c)).collect(); + colors.retain(|c| color_key(c).is_none_or(|k| !have.contains(&k))); + colors +} + fn swatch_add_used(s: &mut Session, p: &Value) -> Result { const C: &str = "swatch.addUsedColors"; let global = switch_or(p, "global", false, C)?; let only_selection = switch_or(p, "selection", false, C)?; - let (added, linked) = s.edit("Add Used Colors", |d, sel| { + let used_ids = |d: &Document, sel: &Selection| -> Result> { let ids: Vec = if only_selection { sel.objects.clone() } else { d.layers.iter().map(|l| l.id).collect() }; if only_selection && ids.is_empty() { return Err(bad(C, "select artwork to add its colours")); } - let (mut linked_to, mut colors) = (vec![], vec![]); - artwork_colors(d, &ids, false, &mut linked_to, &mut colors); - // Colours a solid swatch already has are skipped. - let have: HashSet = d.swatches_iter().filter_map(|w| w.paint.color()).filter_map(|c| color_key(&c)).collect(); - colors.retain(|c| color_key(c).is_none_or(|k| !have.contains(&k))); + Ok(ids) + }; + // Typing in progress is its own undo step and is in the document the colors are read from. + super::variablecmds::settle_typing(s)?; + // With no new color there is nothing to add or link, so no edit and no undo step. + let st = s.doc()?; + if new_used_colors(&st.doc, &used_ids(&st.doc, &st.selection)?).is_empty() { + return Ok(json!({"added": [], "linked": 0})); + } + // Linking a paint to its new swatch keeps its color, so Global Edit gives the link to no other + // member: a member whose color differs keeps it. + let global_edit = s.doc_mut()?.global_edit.take(); + let edited = s.edit("Add Used Colors", |d, sel| { + let ids = used_ids(&*d, &*sel)?; + let colors = new_used_colors(d, &ids); let mut free = d.free_swatch_names(); let mut links = vec![]; for c in colors { @@ -1060,7 +1081,9 @@ fn swatch_add_used(s: &mut Session, p: &Value) -> Result { } let linked = if global { link_colors(d, &ids, &links) } else { 0 }; Ok((links.into_iter().map(|(_, n)| n).collect::>(), linked)) - })?; + }); + s.doc_mut()?.global_edit = global_edit; + let (added, linked) = edited?; Ok(json!({"added": added, "linked": linked})) } diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index f50a2c7364..185baf734f 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Move Type Path Handle", [], None, - "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change", + "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner; symmetric: mirror the other handle about the anchor without changing its kind, except at an open end of the path; independent and symmetric cannot both be true; both default false); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change", has_doc, set_path_handle ), @@ -1449,6 +1449,10 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result { let out = super::object::choice(p, C, "which", &["in", "out"])? != Some("in"); let pos = vectorcraft_geom::Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?); let independent = switch_or(p, "independent", false, C)?; + let symmetric = switch_or(p, "symmetric", false, C)?; + if symmetric && independent { + return Err(bad(C, "`independent` and `symmetric` cannot both be true")); + } let node = s.doc()?.doc.node(id); let on_path = matches!(node.map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. })); if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) { @@ -1461,7 +1465,7 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result { let within = |t: &TextObject| { t.type_path().and_then(|p| p.bounds()).is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= crate::MAX_COORD)) }; - if !(t.set_path_handle((si, ai), out, pos, independent) && within(t)) { + if !(t.set_path_handle_with_symmetry((si, ai), out, pos, independent, symmetric) && within(t)) { t.kind = before; return Err(bad(C, "no such path anchor, or the path would reach past the canvas")); } diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 82e090a3ef..69194eba00 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -105,6 +105,7 @@ const WAIT_FOR_TOOL_EDIT: &[&str] = &[ "symbol.selectInstances", "view.guides.lock", "view.proofSetup", + "view.proofSetup.load", "view.proofColors", "view.overprintPreview", "view.separationsPreview", diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8cc6b4084e..f35a64c5ee 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -189,6 +189,11 @@ pub struct Session { /// The folder of the New Document profiles `file.new` starts documents from; `None`: none, /// every document starts with the defaults ([`Session::attach_new_doc_profiles`]). new_doc_profile_dir: Option, + /// The folder of the proof setups `view.proofSetup.save` saves by name and View → Proof Setup + /// lists; `None`: no folder ([`Session::attach_proof_setups`]). + proof_setup_dir: Option, + /// How many proof setup files `view.proofSetup.save` wrote ([`Session::proof_setup_saves`]). + proof_setup_saves: u64, /// The folder of each script's data folder (`Folder.userData`), beside which the grants file /// keeps the file access people allowed scripts; `None`: no folder /// ([`Session::attach_script_data`]). @@ -324,6 +329,9 @@ pub struct Session { /// The id and persistent options of the tool when the press under way began, which a dropped /// press puts back ([`Session::drop_tool_press`]). pub(crate) press_options: Option<(String, serde_json::Map)>, + /// An option of the active tool was set during the press under way, which stored all of its + /// options, so a dropped press stores the options it puts back. + pub(crate) press_options_stored: bool, /// The engine saves the selection and active layer before a Type press and restores them if it drops. pub(crate) press_type_selection: Option<(Selection, Option)>, /// The freeform gradient point selected once the tool took the press under way, which a diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d811da6e2e..0e702c0076 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -168,6 +168,8 @@ pub fn refused_to_scripts(id: &str) -> bool { "color.removeProfile", "file.print", "view.proofSetup", + "view.proofSetup.save", + "view.proofSetup.load", "view.proofColors", "view.overprintPreview", "view.separationsPreview", diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 6ad8ed586e..cb85e3e47c 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -99,6 +99,8 @@ impl Session { scripts_dir: None, metadata_templates_dir: None, new_doc_profile_dir: None, + proof_setup_dir: None, + proof_setup_saves: 0, script_data_dir: None, plugin_output: None, plugin_install_approval: None, @@ -135,6 +137,7 @@ impl Session { plane_widget_press: false, pointer_held: false, press_options: None, + press_options_stored: false, press_type_selection: None, press_point: None, ruler_guide: None, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 815a33eeae..b74d501308 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -202,12 +202,14 @@ mod symbol_nine_slice; mod symbolbounds; mod symboledit; mod symbolism_options; +mod symbolism_shift; mod symbollib; mod tangent_line; mod targeting; mod textcombos; mod textedit; pub(super) mod textimport; +mod three_point_arc; mod tileedge; mod tints; mod toolsettings; diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index 1010f6f3d3..0b8cc2eb7d 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -112,6 +112,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { "calligraphic-nibs", "pressure-sensitive", "bristle-brushes", + "paint", "pattern-borders", "scatter-shapes", "stipple", @@ -119,8 +120,10 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { "energy-beams", "dry-media", "tech-circuit", + "engraving", "arrows", - "image-brush" + "image-brush", + "artistic" ] ); assert!(libs.iter().all(|l| l["category"] == "builtIn")); @@ -169,6 +172,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { ("calligraphic-nibs", "calligraphic"), ("pressure-sensitive", "art"), ("bristle-brushes", "bristle"), + ("paint", "art"), ("pattern-borders", "pattern"), ("scatter-shapes", "scatter"), ("stipple", "scatter"), @@ -177,6 +181,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { ("dry-media", "art"), ("arrows", "art"), ("image-brush", "scatter"), + ("artistic", "art"), ] { let (_, lib) = cmd::brushlib::library(&s, id).unwrap(); assert!(lib.len() >= 4, "{id}"); @@ -207,6 +212,46 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err()); } +#[test] +fn artistic_library_strokes_are_editable_and_reopen_from_a_saved_library() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "artistic").unwrap(); + let (_, alias) = cmd::brushlib::library(&s, "Artistic").unwrap(); + assert_eq!(alias.brushes, lib.brushes); + assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], "artistic"); + let names = ["Orbit Lines", "Petal Garland", "Lattice Braid", "Facet Sweep"]; + assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names); + let line = run(&mut s, "shape.line", json!({"x1": 10, "y1": 50, "x2": 190, "y2": 50}))["id"].as_u64().unwrap(); + let red = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)), 1.0); + for b in &lib.brushes { + let BrushKind::Art(a) = &b.kind else { panic!("{} is not an art brush", b.name) }; + assert!(art_paths(&a.art).len() >= 2, "{} has no editable vector art", b.name); + for path in [line_to(180.0), line_to(1.0)] { + assert!(!vectorcraft_brush::stroke_pieces(&lib.doc, b, &path, &black_stroke()).is_empty(), "{} draws nothing", b.name); + } + // The art is black, so with Tints every path takes the stroke color itself. + let mut fills = vec![]; + for piece in vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &red) { + piece.walk(&mut |n| { + if n.path_data().is_some() { + fills.push(n.appearance.fill_paint().color().map(|c| c.to_rgb())); + } + }); + } + let is_red = |c: &Option<[f32; 3]>| c.is_some_and(|[r, g, b]| (r - 1.0).abs() < 1e-5 && g.abs() < 1e-5 && b.abs() < 1e-5); + assert!(!fills.is_empty() && fills.iter().all(is_red), "{} does not take the stroke color: {fills:?}", b.name); + let before = undo_len(&s); + let added = run(&mut s, "brush.addFromLibrary", json!({"library": "artistic", "name": b.name, "apply": true, "ids": [line]})); + assert_eq!(strs(&added["added"]), [b.name.as_str()]); + assert_eq!(added["applied"], json!([line])); + assert_eq!(undo_len(&s), before + 1); + } + 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); +} + #[test] fn image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved() { let mut s = session(); @@ -244,6 +289,26 @@ fn image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved() { assert_eq!(reopened.images, lib.doc.images); } +#[test] +fn a_loaded_library_named_artistic_keeps_its_name_ahead_of_the_builtin_alias() { + let mut file = vectorcraft_doc::Document::new(100.0, 100.0); + vectorcraft_brush::store(&mut file, &[vectorcraft_brush::defaults()[0].clone()]); + let b64 = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&file)); + let mut s = session(); + let loaded = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Artistic.vectorcraft"})); + assert_eq!(loaded["name"], "Artistic"); + let id = loaded["library"].as_str().unwrap(); + assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], id); + assert_eq!(run(&mut s, "brush.library", json!({"library": "ARTISTIC"}))["id"], id); + assert_eq!(run(&mut s, "brush.library", json!({"library": "artistic"}))["id"], "artistic", "exact built-in id still works"); + // A name a built-in library has selects the built-in, as for every built-in; the loaded one keeps its id. + let full = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Artistic Brushes.vectorcraft"})); + assert_eq!(full["name"], "Artistic Brushes"); + let full_id = full["library"].as_str().unwrap(); + assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic Brushes"}))["id"], "artistic"); + assert_eq!(run(&mut s, "brush.library", json!({"library": full_id}))["id"], full_id); +} + /// Every path of brush art `n`: (anchors, opacity). fn art_paths(n: &vectorcraft_doc::Node) -> Vec<(usize, f32)> { let mut out = vec![]; @@ -272,6 +337,30 @@ fn black_stroke() -> vectorcraft_doc::StrokeLayer { vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0) } +#[test] +fn engraving_library_draws_fine_parallel_strokes_and_survives_save() { + let mut s = session(); + let listed = run(&mut s, "brush.libraries", json!({})); + let entry = listed["libraries"].as_array().unwrap().iter().find(|l| l["id"] == "engraving").unwrap(); + assert_eq!((entry["name"].as_str(), entry["category"].as_str(), entry["count"].as_u64()), (Some("Engraving"), Some("builtIn"), Some(4))); + let (_, lib) = cmd::brushlib::library(&s, "Engraving").unwrap(); + for b in &lib.brushes { + for length in [2.0, 200.0] { + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(length), &black_stroke()); + let pts = anchors(&pieces.iter().collect::>()); + assert!(!pts.is_empty() && pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{} at {length} pt", b.name); + } + } + let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 20, "x2": 210, "y2": 20}))["id"].as_u64().unwrap(); + let added = run(&mut s, "brush.addFromLibrary", json!({"library": "engraving", "name": "Fine Hatching", "apply": true, "ids": [path]})); + assert_eq!(strs(&added["added"]), ["Fine Hatching"]); + assert_eq!(added["applied"], json!([path])); + let saved = run(&mut s, "brush.saveLibrary", json!({"names": ["Fine Hatching"]})); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(vectorcraft_brush::find(&reopened, "Fine Hatching").unwrap(), lib.brushes[0]); +} + #[test] fn stipple_library_draws_dot_textures_and_survives_save() { let mut s = session(); @@ -519,6 +608,37 @@ fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_librar assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); } +#[test] +fn paint_brushes_draw_distinct_marks_and_survive_a_saved_library() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "Paint").unwrap(); + let names = ["Flat Sweep", "Dry Drag", "Loaded Stroke", "Fan Sweep"]; + 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, 150.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": "paint", "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); +} + /// Ink and Wash: a tapered ink art brush, a brush pen whose size follows the pen pressure and two /// translucent washes, with names of their own and a few paths of art each. #[test] diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 9d1447adb8..ce3e1e6a77 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3331,6 +3331,68 @@ fn live_paint_bucket_paint_and_stroke_commands_leave_the_selection_unpainted() { assert!(failed.is_empty(), "{failed:#?}"); } +/// `paint.editGradient` with an `aspect` and no object to edit (the Live Paint Bucket's gradient, +/// nothing selected, or a fill edit of a Live Paint group without faces) is an error that leaves the default gradient as it was, since a gradient +/// fitted to each object has no aspect of its own. Named objects still take the aspect. +#[test] +fn edit_gradient_aspect_without_objects_is_an_error() { + let aspect = |n: &Node| match n.appearance.fill_paint() { + Paint::Gradient(g) => g.geom.map(|x| x.aspect), + _ => None, + }; + let mut s = session(); + let g = live(&mut s); + let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0); + s.execute("select.set", &json!({"ids": [g.0, rect.0]})).unwrap(); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + s.execute("gradient.presets.apply", &json!({"name": "vignette"})).unwrap(); + let (group, art, fill) = (node(&s, g), node(&s, rect), s.paint.fill.clone()); + let steps = s.doc().unwrap().history.undo.len(); + assert!(!s.gradient_edit_has_objects(false), "the bucket edits its own gradient"); + for params in [json!({"stroke": false, "aspect": 50}), json!({"stroke": false, "aspect": 50, "reverse": true})] { + assert!(s.execute("paint.editGradient", ¶ms).is_err(), "{params}"); + assert_eq!(s.paint.fill, fill, "{params}: the bucket's gradient stays"); + } + assert_eq!((node(&s, g), node(&s, rect)), (group, art), "the selection keeps its paint"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step"); + // Named objects take it. + s.execute("paint.editGradient", &json!({"stroke": false, "kind": "radial", "aspect": 50, "ids": [rect.0]})).unwrap(); + assert_eq!(aspect(&node(&s, rect)), Some(0.5)); + // Without the bucket and with nothing selected, the default gradient has no aspect either. + s.select_tool("selection", ViewInfo::default()).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + let fill = s.paint.fill.clone(); + assert!(!s.gradient_edit_has_objects(false)); + assert!(s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 50})).is_err()); + assert_eq!(s.paint.fill, fill, "the default gradient stays"); + // An empty group has nothing to paint. + let empty = s + .edit("Group", |d, _| { + let id = d.alloc_id(); + d.insert(d.default_layer(), 0, Node::group(id, vec![]))?; + Ok(id) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [empty.0]})).unwrap(); + assert!(!s.gradient_edit_has_objects(false), "an empty group"); + assert!(s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 50})).is_err()); + // A fill edit of a Live Paint group with edges and no faces edits no object; a stroke edit edits its edges. + let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 100, "y2": 0})).unwrap()["id"].as_u64().unwrap()); + let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [edges_only.0]})).unwrap(); + let (fill, group, steps) = (s.paint.fill.clone(), node(&s, edges_only), s.doc().unwrap().history.undo.len()); + assert!(!s.gradient_edit_has_objects(false), "a Live Paint group without faces"); + assert!(s.gradient_edit_has_objects(true), "its edges take a stroke edit"); + assert!(s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 50})).is_err()); + assert_eq!((&s.paint.fill, node(&s, edges_only)), (&fill, group), "the default and the group stay"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step"); + // A selected object takes it. + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + assert!(s.gradient_edit_has_objects(false) && s.gradient_edit_has_objects(true)); + s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 25})).unwrap(); + assert_eq!(aspect(&node(&s, rect)), Some(0.25)); +} + /// With the Live Paint Bucket active, objects named with `ids` still take a stroke, and a brush /// still goes to the selection. #[test] @@ -9429,9 +9491,12 @@ fn image_trace_split_view_keeps_and_validates_its_divider() { assert_eq!((back.node(g).unwrap().trace_view(), back.node(g).unwrap().trace_split()), (vectorcraft_doc::TraceView::Split, 0.25)); // Bad dividers are refused and change nothing. let steps = s.doc().unwrap().history.undo.len(); - for bad in [json!(-0.1), json!(1.01), json!("0.5"), json!(true), json!([0.5])] { + for bad in [json!(-0.1), json!(1.01), json!("0.5"), json!(true), json!([0.5]), json!(null)] { assert!(s.execute("imageTrace.setView", &json!({"view": "split", "split": bad})).is_err(), "{bad}"); } + // A null divider with another view is refused too, and the view stays. + assert!(s.execute("imageTrace.setView", &json!({"view": "outlines", "split": null})).is_err()); + assert_eq!(node(&s, g).trace_view(), vectorcraft_doc::TraceView::Split); assert_eq!((s.doc().unwrap().history.undo.len(), node(&s, g).trace_split()), (steps, 0.25)); for edge in [0.0, 1.0] { s.execute("imageTrace.setView", &json!({"view": "split", "split": edge})).unwrap(); diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 660b24d6f6..3e64f1557d 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -318,6 +318,45 @@ fn convert_query_and_intents() { assert!(s.execute("color.convert", &json!({"color": "#808080", "intent": "vivid"})).is_err()); } +/// `to: "oklch"` answers the OKLCH of the color's display sRGB, which converts back to the color; +/// a CMYK color's display color, not its naive separation, sets them. +#[test] +fn convert_to_oklch_answers_lightness_chroma_and_hue() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = session(); + let r = s.execute("color.convert", &json!({"color": "#ff0000", "to": "oklch"})).unwrap(); + assert_eq!(r["model"], "oklch"); + let v: Vec = r["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + assert!((v[0] - 62.80).abs() < 0.005 && (v[1] - 0.2577).abs() < 5e-5 && (v[2] - 29.23).abs() < 0.005, "{r}"); + let (rgb, lowered) = vectorcraft_color::oklab::from_oklch(v[0] / 100.0, v[1], v[2]); + assert!(!lowered); + assert_eq!(Color::rgb(rgb[0], rgb[1], rgb[2]).to_hex(), "#ff0000"); + assert_eq!(r["hex"], "#ff0000"); + let gray = s.execute("color.convert", &json!({"color": "#808080", "to": "oklch"})).unwrap(); + assert_eq!(gray["values"][2], 0.0, "{gray}"); + let ink = json!({"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0}); + let cyan = s.execute("color.convert", &json!({"color": ink, "to": "oklch"})).unwrap(); + let shown = vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&Color::cmyk(1.0, 0.0, 0.0, 0.0))); + let naive = vectorcraft_color::oklab::to_oklch([0.0, 1.0, 1.0]); + let c: Vec = cyan["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + let got = [c[0] / 100.0, c[1], c[2]]; + assert!((0..3).all(|i| (got[i] - shown[i]).abs() < 1e-9) && shown[1] > 0.05, "{cyan} {shown:?}"); + assert!((got[0] - naive[0]).abs() > 0.02, "{cyan} {naive:?}"); + // A Lab color outside sRGB answers the OKLCH of its color clipped to sRGB. + let vivid = s.execute("color.convert", &json!({"color": {"l": 50.0, "a": 100.0, "b": 0.0}, "to": "oklch"})).unwrap(); + let w: Vec = vivid["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + let shown = cms::active().display_rgb(&Color::lab(50.0, 100.0, 0.0)).map(|v| v.clamp(0.0, 1.0)); + let clipped = vectorcraft_color::oklab::to_oklch(shown); + assert!((w[0] / 100.0 - clipped[0]).abs() < 1e-9 && (w[1] - clipped[1]).abs() < 1e-9, "{vivid} {clipped:?}"); + assert!((w[2] - clipped[2]).abs() < 1e-9 && (0.0..360.0).contains(&w[2]), "{vivid} {clipped:?}"); + assert!(vectorcraft_color::oklab::in_srgb(vectorcraft_color::oklab::oklch_to_srgb(w[0] / 100.0, w[1], w[2])), "{vivid}"); + // RGB numbers past 0..1 answer the OKLCH of the clipped color `hex` reports: white. + let past = s.execute("color.convert", &json!({"color": [2.0, 2.0, 2.0], "to": "oklch"})).unwrap(); + assert_eq!(past["hex"], "#ffffff"); + let l = past["values"][0].as_f64().unwrap(); + assert!((l - 100.0).abs() < 0.01 && past["values"][1].as_f64().unwrap() < 1e-3, "{past}"); +} + #[test] fn assign_profile_is_stored_and_undoable() { let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); @@ -682,6 +721,273 @@ fn proof_setup_simulates_tritanopia() { s.execute("view.proofSetup", &json!({"target": "workingCmyk", "proof": false})).unwrap(); } +/// View › Proof Setup › Customize's settings: an RGB profile as the device, Preserve Numbers and +/// Simulate Black Ink, kept in the proof view, read back and drawn; bad values are refused and +/// leave the view as it was. +#[test] +fn proof_setup_takes_the_custom_proof_settings() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let mut s = session(); + rect(&mut s, 0.0, 0.0, 100.0, 100.0, json!("#000000")); + let r = s.execute("view.proofSetup", &json!({})).unwrap(); + assert_eq!((r["preserveNumbers"].as_bool(), r["simulateBlack"].as_bool()), (Some(false), Some(false))); + let device = format!("cmyk:{}", cms::GENERIC_CMYK); + let r = s.execute("view.proofSetup", &json!({"target": device, "simulateBlack": true, "proof": true})).unwrap(); + assert_eq!((r["target"].as_str(), r["simulateBlack"].as_bool(), r["proofColors"].as_bool()), (Some(device.as_str()), Some(true), Some(true))); + let setup = vectorcraft_render::proof::active_proof().unwrap(); + assert!(setup.simulate_black && !setup.preserve_numbers); + let doc = s.doc().unwrap().doc.clone(); + let gray = render(&doc, RenderOptions { proof: Some(setup.clone()), ..Default::default() }).pixel(50, 50); + let black = render(&doc, RenderOptions { proof: Some(ProofSetup { simulate_black: false, ..setup }), ..Default::default() }).pixel(50, 50); + assert!(gray[0] > black[0] + 10, "the press black shows as a gray: {gray:?} vs {black:?}"); + let rgb = format!("rgb:{}", cms::DISPLAY_P3); + let r = s.execute("view.proofSetup", &json!({"target": rgb, "preserveNumbers": true})).unwrap(); + assert_eq!((r["target"].as_str(), r["preserveNumbers"].as_bool()), (Some(rgb.as_str()), Some(true))); + assert_eq!(vectorcraft_render::proof::view().setup.target, ProofTarget::Rgb(cms::DISPLAY_P3.into())); + // Unchanged settings leave the revision alone. + let rev = s.doc().unwrap().revision; + s.execute("view.proofSetup", &json!({"target": rgb, "preserveNumbers": true, "simulateBlack": true})).unwrap(); + assert_eq!(s.doc().unwrap().revision, rev); + let view = vectorcraft_render::proof::view(); + refused(&mut s, "view.proofSetup", json!({"target": "rgb:Nope"}), "unknown RGB profile `Nope`"); + refused(&mut s, "view.proofSetup", json!({"target": format!("rgb:{}", cms::GENERIC_CMYK)}), "unknown RGB profile"); + refused(&mut s, "view.proofSetup", json!({"target": "rgb:"}), "unknown RGB profile"); + refused(&mut s, "view.proofSetup", json!({"target": "workingCmyk", "preserveNumbers": "yes"}), "`preserveNumbers` must be true or false"); + refused(&mut s, "view.proofSetup", json!({"simulateBlack": 1}), "`simulateBlack` must be true or false"); + assert_eq!(vectorcraft_render::proof::view(), view, "the proof view is unchanged"); + assert_eq!(s.doc().unwrap().revision, rev, "nothing redraws"); +} + +/// A custom proof setup saved to a file loads back as the same setup with Proof Colors on; saving +/// leaves the proof view as it is, and `view.proofSetup.read` only reads the file. +#[test] +fn a_saved_proof_setup_loads_back() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-file"); + let path = dir.join("press.vcproof").to_string_lossy().to_string(); + let mut s = session(); + let device = format!("cmyk:{}", cms::GENERIC_CMYK); + let r = s + .execute( + "view.proofSetup.save", + &json!({"path": path, "target": device, "intent": "perceptual", "preserveNumbers": true, "simulateBlack": true}), + ) + .unwrap(); + assert_eq!((r["path"].as_str(), r["target"].as_str(), r["intent"].as_str()), (Some(path.as_str()), Some(device.as_str()), Some("perceptual"))); + assert_eq!(vectorcraft_render::proof::view(), Default::default(), "saving leaves the proof view alone"); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("\"format\": \"vectorcraft-proof-setup\"") && text.contains("\"version\": 1"), "{text}"); + let r = s.execute("view.proofSetup.read", &json!({"path": path})).unwrap(); + assert_eq!((r["target"].as_str(), r["preserveNumbers"].as_bool(), r["simulateBlack"].as_bool()), (Some(device.as_str()), Some(true), Some(true))); + assert_eq!(vectorcraft_render::proof::view(), Default::default(), "reading changes nothing"); + assert!(!crate::waits_for_tool_edit("view.proofSetup.read"), "reading does not finish a tool's edit"); + let rev = s.doc().unwrap().revision; + let r = s.execute("view.proofSetup.load", &json!({"path": path})).unwrap(); + assert_eq!((r["proofColors"].as_bool(), r["path"].as_str()), (Some(true), Some(path.as_str()))); + let v = vectorcraft_render::proof::view(); + assert!(v.proof_colors); + let want = ProofSetup { + target: ProofTarget::Cmyk(cms::GENERIC_CMYK.into()), + intent: Intent::Perceptual, + simulate_paper: false, + preserve_numbers: true, + simulate_black: true, + ..Default::default() + }; + assert_eq!(v.setup, want); + assert!(s.doc().unwrap().revision > rev, "the canvas redraws"); + // Saved from the current setup, the file holds that setup: the round trip keeps every field. + let again = dir.join("again.vcproof").to_string_lossy().to_string(); + s.execute("view.proofSetup.save", &json!({"path": again, "simulatePaper": true})).unwrap(); + s.execute("view.proofSetup", &json!({"target": "workingCmyk"})).unwrap(); + s.execute("view.proofSetup.load", &json!({"path": again})).unwrap(); + assert_eq!(vectorcraft_render::proof::view().setup, ProofSetup { simulate_paper: true, ..want }); +} + +/// Saving refuses a target that is not a device, bad params, a bad name and a file larger than +/// loading reads; loading refuses a file +/// that is too large, not a proof setup, newer, or whose device is a profile that is not loaded, +/// and the proof view stays as it was. +#[test] +fn proof_setup_files_refuse_what_they_cannot_use() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-refused"); + let file = |n: &str| dir.join(n).to_string_lossy().to_string(); + let mut s = session(); + let path = file("a.vcproof"); + refused(&mut s, "view.proofSetup.save", json!({"path": path, "target": "protanopia"}), "`protanopia` is not a device to simulate"); + refused(&mut s, "view.proofSetup.save", json!({"path": path, "target": "rgb:Nope"}), "unknown RGB profile `Nope`"); + refused(&mut s, "view.proofSetup.save", json!({"path": path, "simulateBlack": "yes"}), "`simulateBlack` must be true or false"); + refused(&mut s, "view.proofSetup.save", json!({}), "missing `path` or `name`"); + refused(&mut s, "view.proofSetup.save", json!({"path": path, "name": "x"}), "not both"); + refused(&mut s, "view.proofSetup.save", json!({"path": " "}), "`path` is empty"); + refused(&mut s, "view.proofSetup.save", json!({"name": "x"}), "need the preferences folder"); + assert!(!std::path::Path::new(&path).exists(), "nothing is written"); + s.attach_proof_setups(dir.join("Proof Setups")); + for bad_name in ["", " ", "../up", "a/b", "a\\b", ".hidden", "c:d"] { + refused(&mut s, "view.proofSetup.save", json!({"name": bad_name}), "`name`"); + } + refused(&mut s, "view.proofSetup.save", json!({"name": "x".repeat(101)}), "longer than 100 characters"); + // A device whose name makes the file larger than load reads is refused, and nothing is written. + let long = "Long Profile Name ".repeat(4000); + cms::register_icc(&cms::icc_bytes(cms::DISPLAY_P3).unwrap(), Some(long.clone())).unwrap(); + let refusal = s.execute("view.proofSetup.save", &json!({"path": path, "target": format!("rgb:{long}")})); + cms::unregister_icc(&long); + assert!(refusal.unwrap_err().to_string().contains("larger than 65536 bytes"), "a setup load can't read is refused"); + assert!(!std::path::Path::new(&path).exists(), "nothing is written"); + let before = vectorcraft_render::proof::view(); + let write = |n: &str, text: &str| { + let p = file(n); + std::fs::write(&p, text).unwrap(); + p + }; + let ok = r#"{"format": "vectorcraft-proof-setup", "version": 1, "target": "workingCmyk", "intent": "relative"}"#; + let cases = [ + (write("big.vcproof", &format!("{ok}{}", " ".repeat(64 << 10))), "larger than 65536 bytes"), + (write("junk.vcproof", "not json"), "not a proof setup file"), + (write("other.vcproof", r#"{"format": "other", "version": 1}"#), "not a VectorCraft proof setup file"), + (write("newer.vcproof", &ok.replace("\"version\": 1", "\"version\": 2")), "made by a newer VectorCraft"), + (write("missing.vcproof", &ok.replace("workingCmyk", "cmyk:Not Loaded")), "the CMYK profile `Not Loaded`, which is not loaded"), + (write("blind.vcproof", &ok.replace("workingCmyk", "deuteranopia")), "not a device to simulate"), + (write("intent.vcproof", &ok.replace("relative", "vivid")), "unknown intent `vivid`"), + (write("flag.vcproof", &ok.replace("}", r#", "simulatePaper": 1}"#)), "`simulatePaper` must be true or false"), + ]; + for (p, msg) in cases { + for cmd in ["view.proofSetup.load", "view.proofSetup.read"] { + refused(&mut s, cmd, json!({"path": p}), msg); + } + } + refused(&mut s, "view.proofSetup.load", json!({"path": file("gone.vcproof")}), "gone.vcproof"); + assert_eq!(vectorcraft_render::proof::view(), before, "the proof view is unchanged"); + // A file of the limit's size is read. + let padded = format!("{ok}{}", " ".repeat((64 << 10) - ok.len())); + s.execute("view.proofSetup.load", &json!({"path": write("limit.vcproof", &padded)})).unwrap(); +} + +/// Setups saved by name go in the Proof Setups folder, made on the first save, and are listed by +/// name; other files there are left out, and a run without the folder lists none. +#[test] +fn proof_setups_saved_by_name_are_listed() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let mut s = session(); + assert_eq!(s.execute("view.proofSetup.list", &json!({})).unwrap(), json!({"folder": null, "setups": [], "truncated": false})); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-list"); + let folder = dir.join("Proof Setups"); + s.attach_proof_setups(folder.clone()); + let r = s.execute("view.proofSetup.list", &json!({})).unwrap(); + assert_eq!(r["setups"], json!([]), "no folder yet: none saved"); + let r = s.execute("view.proofSetup.save", &json!({"name": " Coated Press ", "target": format!("rgb:{}", cms::DISPLAY_P3)})).unwrap(); + let saved = folder.join("Coated Press.vcproof"); + assert_eq!(r["path"].as_str(), Some(saved.to_string_lossy().as_ref())); + s.execute("view.proofSetup.save", &json!({"name": "Bright"})).unwrap(); + std::fs::write(folder.join("notes.txt"), "x").unwrap(); + std::fs::create_dir(folder.join("Sub.vcproof")).unwrap(); + let r = s.execute("view.proofSetup.list", &json!({})).unwrap(); + let names: Vec<&str> = r["setups"].as_array().unwrap().iter().filter_map(|e| e["name"].as_str()).collect(); + assert_eq!(names, ["Bright", "Coated Press"]); + assert_eq!(r["truncated"], false); + s.execute("view.proofSetup.load", &json!({"name": "Coated Press"})).unwrap(); + assert_eq!(vectorcraft_render::proof::view().setup.target, ProofTarget::Rgb(cms::DISPLAY_P3.into())); + for i in 0..101 { + std::fs::write(folder.join(format!("z{i:03}.vcproof")), "x").unwrap(); + } + let r = s.execute("view.proofSetup.list", &json!({})).unwrap(); + assert_eq!((r["setups"].as_array().unwrap().len(), r["truncated"].as_bool()), (100, Some(true))); + assert_eq!((r["setups"][0]["name"].as_str(), r["setups"][99]["name"].as_str()), (Some("Bright"), Some("z097")), "the first 100 by name"); +} + +/// Other files in the Proof Setups folder, however many, do not keep its setups from the listing. +#[test] +fn proof_setups_are_listed_among_many_other_files() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let mut s = session(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-list-crowded"); + let folder = dir.join("Proof Setups"); + std::fs::create_dir_all(&folder).unwrap(); + for i in 0..5000 { + std::fs::write(folder.join(format!("a{i:04}.txt")), "").unwrap(); + } + s.attach_proof_setups(folder.clone()); + s.execute("view.proofSetup.save", &json!({"name": "Press"})).unwrap(); + let r = s.execute("view.proofSetup.list", &json!({})).unwrap(); + assert_eq!((r["setups"].as_array().unwrap().len(), r["truncated"].as_bool()), (1, Some(false))); + assert_eq!(r["setups"][0]["name"], "Press"); +} + +/// The listing names only files that `name` loads (`.vcproof`, a name `save` can give), in +/// the order of those names, and the limit keeps the first by name; a folder that can't be read is +/// an error, not an empty listing. +#[test] +fn proof_setups_are_listed_by_names_that_load_them() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let mut s = session(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-list-names"); + let folder = dir.join("Proof Setups"); + std::fs::create_dir_all(&folder).unwrap(); + s.attach_proof_setups(folder.clone()); + let ok = r#"{"format": "vectorcraft-proof-setup", "version": 1, "target": "workingCmyk", "intent": "relative"}"#; + for file in ["Press.vcproof", "Press Matte.vcproof", "Loud.VCPROOF", " Lead.vcproof"] { + std::fs::write(folder.join(file), ok).unwrap(); + } + let names = |r: &Value| r["setups"].as_array().unwrap().iter().filter_map(|e| e["name"].as_str().map(str::to_string)).collect::>(); + let r = s.execute("view.proofSetup.list", &json!({})).unwrap(); + assert_eq!((names(&r), r["truncated"].as_bool()), (vec!["Press".to_string(), "Press Matte".to_string()], Some(false))); + for name in names(&r) { + s.execute("view.proofSetup.read", &json!({ "name": name })).unwrap(); + } + // `Press` and `Press Matte` compete for the last place: the first by name keeps it. + for i in 0..99 { + std::fs::write(folder.join(format!("A{i:02}.vcproof")), "x").unwrap(); + } + let r = s.execute("view.proofSetup.list", &json!({})).unwrap(); + let listed = names(&r); + assert_eq!((listed.len(), listed.last().map(String::as_str), r["truncated"].as_bool()), (100, Some("Press"), Some(true))); + // A folder that is not one can't be listed. + let file = dir.join("not a folder"); + std::fs::write(&file, "x").unwrap(); + s.attach_proof_setups(file); + refused(&mut s, "view.proofSetup.list", json!({}), "not a folder"); +} + +/// A file name that is not valid Unicode is left out of the listing, which then says it is +/// incomplete: a path made from a lossy copy of the name would name another file. +#[test] +fn proof_setup_names_that_are_not_unicode_are_left_out() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let mut s = session(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-list-bytes"); + let folder = dir.join("Proof Setups"); + std::fs::create_dir_all(&folder).unwrap(); + #[cfg(unix)] + let odd = { + use std::os::unix::ffi::OsStringExt; + std::ffi::OsString::from_vec(b"Odd\xff.vcproof".to_vec()) + }; + #[cfg(windows)] + let odd = { + use std::os::windows::ffi::OsStringExt; + std::ffi::OsString::from_wide(&"Odd?.vcproof".encode_utf16().map(|u| if u == u16::from(b'?') { 0xD800 } else { u }).collect::>()) + }; + // A file system that refuses such a name has nothing to leave out. + if std::fs::write(folder.join(odd), "x").is_err() { + return; + } + std::fs::write(folder.join("Press.vcproof"), "x").unwrap(); + s.attach_proof_setups(folder); + let r = s.execute("view.proofSetup.list", &json!({})).unwrap(); + assert_eq!( + (r["setups"].as_array().map(Vec::len), r["setups"][0]["name"].as_str(), r["truncated"].as_bool()), + (Some(1), Some("Press"), Some(true)) + ); +} + /// Whether the content has a DeviceCMYK fill/stroke operator (`c m y k k` / `K`). fn has_cmyk_op(pdf: &str) -> bool { let toks: Vec<&str> = pdf.split_ascii_whitespace().collect(); diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index e372467603..1ea6e5091f 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -585,6 +585,106 @@ fn a_polygon_takes_its_angle_radius_side_length_and_equal_sides() { } } +/// Rectangle Angle and Ellipse Angle: `rectangleAngle` and `ellipseAngle` turn each selected live +/// rectangle or ellipse about its own center, keeping its size, corners and pie, as one undo step. +/// The angle it already has records no step, each key leaves the other kind as it is, and a value +/// that is not a number is an error. +#[test] +fn a_rectangle_and_an_ellipse_take_their_angle() { + let (mut s, rect) = session(); + run(&mut s, json!({"radius": 8})); + let ellipse = NodeId(s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 120, "height": 80})).unwrap()["id"].as_u64().unwrap()); + run(&mut s, json!({"pieStart": 30, "pieEnd": 120})); + let live = |s: &Session, id: NodeId| { + let n = s.doc().unwrap().doc.node(id).unwrap(); + (n.live_shape().unwrap().clone(), n.geometric_bounds().unwrap()) + }; + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let close = |a: f64, b: f64| (a - b).abs() < 1e-6; + let angle = |s: &Session, id: NodeId| live(s, id).0.shape_angle().unwrap(); + // The ellipse's center: the middle of its untransformed box, wherever its pie leaves the path. + let ellipse_center = |s: &Session| match live(s, ellipse).0 { + LiveShape::Ellipse { w, h, xf, .. } => xf * vectorcraft_geom::Point::new(w / 2.0, h / 2.0), + l => panic!("{l:?}"), + }; + let center = ellipse_center(&s); + + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + let n = steps(&s); + run(&mut s, json!({"rectangleAngle": 90})); + let (l, b) = live(&s, rect); + assert!(close(angle(&s, rect), 90.0), "{l:?}"); + // 100 × 60 at (10, 10) turned about (60, 40): 60 wide, 100 tall, same center. + assert!(close(b.width(), 60.0) && close(b.height(), 100.0) && close(b.center().x, 60.0) && close(b.center().y, 40.0), "{b:?}"); + let LiveShape::Rectangle { w, h, radii, .. } = &l else { panic!("{l:?}") }; + assert!(close(*w, 100.0) && close(*h, 60.0) && *radii == [8.0; 4], "{w} {h} {radii:?}"); + assert_eq!(steps(&s), n + 1, "one undo step"); + for same in [json!({"rectangleAngle": 90}), json!({"rectangleAngle": 450}), json!({"rectangleAngle": -270}), json!({"ellipseAngle": 10})] { + run(&mut s, same.clone()); + assert_eq!(steps(&s), n + 1, "{same} records no undo step"); + } + // A turn the field gives back rounded is the angle the shape has: typing it again records no step. + run(&mut s, json!({"rectangleAngle": 33.3})); + let now = angle(&s, rect); + run(&mut s, json!({"rectangleAngle": now})); + run(&mut s, json!({"rectangleAngle": 33.3})); + assert_eq!(steps(&s), n + 2); + for bad in [json!({"rectangleAngle": "left"}), json!({"ellipseAngle": "up"}), json!({"rectangleAngle": true})] { + assert!(s.execute("object.setLiveShape", &bad).is_err(), "{bad}"); + assert_eq!(steps(&s), n + 2, "{bad} changes nothing"); + } + + // The ellipse turns about its center and keeps its pie. + s.execute("select.set", &json!({"ids": [ellipse.0]})).unwrap(); + run(&mut s, json!({"ellipseAngle": 90})); + let (l, b) = live(&s, ellipse); + assert!(close(angle(&s, ellipse), 90.0), "{l:?}"); + let LiveShape::Ellipse { pie, .. } = &l else { panic!("{l:?}") }; + assert_eq!(*pie, (30.0, 120.0)); + let now = ellipse_center(&s); + assert!(close(now.x, center.x) && close(now.y, center.y), "{center:?} → {now:?}"); + assert!(b.width() < b.height(), "120 × 80 turned a quarter turn: {b:?}"); + + // Both selected: each key turns its own kind only, each about its own center. + s.execute("select.set", &json!({"ids": [rect.0, ellipse.0]})).unwrap(); + run(&mut s, json!({"rectangleAngle": 45})); + assert!(close(angle(&s, rect), 45.0) && close(angle(&s, ellipse), 90.0)); + let b = live(&s, rect).1; + assert!(close(b.center().x, 60.0) && close(b.center().y, 40.0), "{b:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(close(angle(&s, rect), 33.3)); + + // A reflected rectangle takes the angle too, about its center. + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap(); + let before = live(&s, rect).1.center(); + run(&mut s, json!({"rectangleAngle": 20})); + let after = live(&s, rect).1.center(); + assert!(close(angle(&s, rect), 20.0) && close(before.x, after.x) && close(before.y, after.y), "{before:?} → {after:?}"); +} + +/// A shape named in `ids` that a turn would take past the coordinate limit (±4,000,000 pt) is an +/// error that changes nothing, whether or not it is selected. +#[test] +fn a_turn_past_the_coordinate_limit_is_an_error() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let mut add = |cmd: &str, p: Value| s.execute(cmd, &p).unwrap()["id"].as_u64().unwrap(); + // Each reaches within 10 pt of the limit and past it when turned. + let rect = add("shape.rectangle", json!({"x": 3_999_890, "y": 100, "width": 100, "height": 100})); + let ellipse = add("shape.ellipse", json!({"x": 3_999_950, "y": 100, "width": 40, "height": 100})); + let polygon = add("shape.polygon", json!({"cx": 3_999_955, "cy": 200, "radius": 50, "sides": 6})); + for (id, key, angle) in [(rect, "rectangleAngle", 45), (ellipse, "ellipseAngle", 90), (polygon, "polygonAngle", 90)] { + for selected in [false, true] { + s.execute("select.set", &json!({"ids": if selected { vec![id] } else { vec![] }})).unwrap(); + let (doc, steps) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let e = s.execute("object.setLiveShape", &json!({"ids": [id], key: angle})).unwrap_err(); + assert!(e.to_string().contains("out of range"), "{key}, selected {selected}: {e}"); + assert!(*s.doc().unwrap().doc == *doc && s.doc().unwrap().history.undo.len() == steps, "{key}, selected {selected}: changed"); + } + } +} + /// A live line's Line Properties: Line Length keeps its first end in place, Line Angle (degrees /// counterclockwise, any finite value brought into 0 to 360) turns it about its midpoint, the /// length applies before the angle, every selected line takes them in one undo step, and a value diff --git a/crates/engine/src/tests/pattern.rs b/crates/engine/src/tests/pattern.rs index fafcc80ac6..01f8e76fbc 100644 --- a/crates/engine/src/tests/pattern.rs +++ b/crates/engine/src/tests/pattern.rs @@ -212,6 +212,153 @@ fn cancel_new_pattern_removes_it() { assert_eq!(doc(&s).layers.len(), 1); } +/// A 30×40 blue rectangle at (100, 100) with no stroke, selected. +fn blue_rect(s: &mut Session) -> NodeId { + let b = rect(s, 100.0, 100.0, 30.0, 40.0); + s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#0000ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [b.0], "none": true})).unwrap(); + sel(s, &[b]); + b +} + +/// Replace Pattern Art gives the pattern copies of the selected art as its tile art in one undo +/// step: the pattern keeps its name, swatch, place, tile and options, art painted with it keeps the +/// paint, and the selected art stays on the canvas, selected. Undo and Redo swap the two tiles. +#[test] +fn replace_art_gives_a_pattern_new_tile_art() { + let mut s = session(); + let red = make_dots(&mut s); + let filled = rect(&mut s, 200.0, 200.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"ids": [filled.0], "swatch": "Dots"})).unwrap(); + s.execute("pattern.options", &json!({"name": "Dots", "tileType": "hexByRow"})).unwrap(); + let blue = blue_rect(&mut s); + let old = doc(&s).pattern("Dots").unwrap().clone(); + let place = |s: &Session| doc(s).swatches_iter().position(|w| w.name == "Dots"); + let (at, swatches, steps) = (place(&s), doc(&s).swatches_iter().count(), s.doc().unwrap().history.undo.len()); + let v = s.execute("object.pattern.replaceArt", &json!({"name": "Dots"})).unwrap(); + assert_eq!(v["name"], "Dots"); + let d = doc(&s); + let def = d.pattern("Dots").unwrap(); + assert_eq!(def.art.len(), 1); + assert_eq!(def.art[0].kind, node(&s, blue).kind, "the tile art is the blue rectangle"); + assert_eq!(def.art[0].appearance, node(&s, blue).appearance); + assert_ne!(def.art[0].id, blue, "a copy with an id of its own"); + assert_eq!((def.tile, def.tile_type, &def.name), (old.tile, old.tile_type, &old.name), "the tile and options stay"); + assert_eq!((d.patterns.len(), place(&s), d.swatches_iter().count()), (1, at, swatches), "no new pattern or swatch"); + assert!(is_pattern(&node(&s, filled).appearance.fill_paint(), "Dots"), "the filled art keeps the pattern"); + assert!(d.node(blue).is_some() && d.node(red).is_some(), "the art stays"); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), vec![blue], "the art stays selected"); + let st = s.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.history.undo.last().map(|e| e.label.as_str())), (steps + 1, Some("Replace Pattern Art"))); + let new = def.art.clone(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(doc(&s).pattern("Dots").unwrap(), &old, "Undo gives the old tile art back"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(doc(&s).pattern("Dots").unwrap().art, new, "Redo gives the new tile art"); +} + +/// With Size Tile to Art on, the tile fits the new art (and its spacing); `ids` names the art. +#[test] +fn replace_art_fits_the_tile_when_size_tile_to_art_is_on() { + let mut s = session(); + make_dots(&mut s); + s.execute("pattern.options", &json!({"name": "Dots", "sizeTileToArt": true, "hSpacing": 4, "vSpacing": 6})).unwrap(); + let blue = blue_rect(&mut s); + s.execute("select.set", &json!({"ids": []})).unwrap(); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [blue.0]})).unwrap(); + assert_eq!(doc(&s).pattern("Dots").unwrap().tile, Rect::new(98.0, 97.0, 132.0, 143.0)); +} + +/// Art that matches the tile art already, its own ids aside, records no undo step. +#[test] +fn replace_art_that_matches_the_tile_art_records_nothing() { + let mut s = session(); + make_dots(&mut s); + blue_rect(&mut s); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots"})).unwrap(); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + s.execute("object.pattern.replaceArt", &json!({"name": "Dots"})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + assert_eq!(doc(&s), &before); +} + +/// Replace Pattern Art is refused, changing nothing, for a missing name or pattern, with no art, +/// while a pattern is edited, and for art painted with the pattern itself, directly, through +/// another pattern, through a symbol, through the paints a graph stores, through a graph design a +/// graph draws its columns with, through the art of a brush on a stroke and through the symbol of an +/// inline graphic in type. +#[test] +fn replace_art_is_refused_without_changing_anything() { + let mut s = session(); + make_dots(&mut s); + // "Holds dots": a pattern whose tile is painted with Dots. + let other = rect(&mut s, 100.0, 100.0, 10.0, 10.0); + s.execute("paint.setFill", &json!({"ids": [other.0], "swatch": "Dots"})).unwrap(); + sel(&mut s, &[other]); + s.execute("object.pattern.make", &json!({"name": "Holds dots", "edit": false})).unwrap(); + let via = rect(&mut s, 150.0, 150.0, 10.0, 10.0); + s.execute("paint.setFill", &json!({"ids": [via.0], "swatch": "Holds dots"})).unwrap(); + let stroked = rect(&mut s, 200.0, 200.0, 10.0, 10.0); + s.execute("paint.setStroke", &json!({"ids": [stroked.0], "swatch": "Dots"})).unwrap(); + sel(&mut s, &[stroked]); + let instance = id_of(&s.execute("symbol.new", &json!({"name": "Dotted"})).unwrap()); + let graph = graph_painted_with(&mut s, "Dots"); + // A graph whose stored columns name design "Dotted columns", drawn with Dots, before it is drawn + // again. + let design = rect(&mut s, 300.0, 300.0, 10.0, 10.0); + s.execute("paint.setFill", &json!({"ids": [design.0], "swatch": "Dots"})).unwrap(); + s.execute("graph.design", &json!({"new": "Dotted columns", "ids": [design.0]})).unwrap(); + let v = s.execute("graph.create", &json!({"type": "column", "x": 300, "y": 200, "width": 60, "height": 40, "csv": ",2024\nQ1,3"})); + let designed = id_of(&v.unwrap()); + let mut extras = doc_mut(&mut s).node_mut(designed).unwrap().extras_mut(); + extras.graph.as_mut().unwrap().series_columns = + vec![Some(vectorcraft_doc::ColumnDesign { design: "Dotted columns".into(), ..Default::default() })]; + drop(extras); + // A path stroked with an art brush whose art is filled with Dots. + let brush_art = rect(&mut s, 300.0, 350.0, 20.0, 5.0); + s.execute("paint.setFill", &json!({"ids": [brush_art.0], "swatch": "Dots"})).unwrap(); + s.execute("brush.new", &json!({"type": "art", "name": "Dotted brush", "ids": [brush_art.0]})).unwrap(); + let brushed = rect(&mut s, 300.0, 380.0, 40.0, 10.0); + s.execute("paint.setFill", &json!({"ids": [brushed.0], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [brushed.0], "color": "#000000"})).unwrap(); + s.execute("brush.apply", &json!({"name": "Dotted brush", "ids": [brushed.0]})).unwrap(); + // Type that shows symbol "Dotted" as an inline graphic. + let typed = id_of(&s.execute("text.create", &json!({"x": 20, "y": 420, "text": "Hi"})).unwrap()); + s.execute("text.insertInline", &json!({"id": typed.0, "at": 0, "symbol": "Dotted"})).unwrap(); + let plain = blue_rect(&mut s); + let unchanged = |s: &Session, before: &vectorcraft_doc::Document, steps: usize, case: &str| { + assert_eq!(doc(s), before, "{case}: the document stays"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{case}: no undo step"); + }; + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + for (case, p, why) in [ + ("no name", json!({}), "missing name".to_string()), + ("no pattern", json!({"name": "Stripes"}), "no pattern `Stripes`".into()), + ("no art", json!({"name": "Dots", "ids": [9999]}), "select the art for the pattern tile".into()), + ("painted with it", json!({"name": "Dots", "ids": [other.0]}), "art painted with `Dots` can't be its tile".into()), + ("through a pattern", json!({"name": "Dots", "ids": [via.0]}), "art painted with `Dots` can't be its tile".into()), + ("through a symbol", json!({"name": "Dots", "ids": [instance.0]}), "art painted with `Dots` can't be its tile".into()), + ("through a graph's paints", json!({"name": "Dots", "ids": [graph.0]}), "art painted with `Dots` can't be its tile".into()), + ("through a graph design", json!({"name": "Dots", "ids": [designed.0]}), "art painted with `Dots` can't be its tile".into()), + ("through a brush", json!({"name": "Dots", "ids": [brushed.0]}), "art painted with `Dots` can't be its tile".into()), + ("through an inline graphic", json!({"name": "Dots", "ids": [typed.0]}), "art painted with `Dots` can't be its tile".into()), + ] { + let err = s.execute("object.pattern.replaceArt", &p).unwrap_err(); + assert!(err.to_string().contains(&why), "{case}: {err}"); + unchanged(&s, &before, steps, case); + } + s.execute("select.set", &json!({"ids": []})).unwrap(); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + let err = s.execute("object.pattern.replaceArt", &json!({"name": "Dots"})).unwrap_err(); + assert!(err.to_string().contains("select the art for the pattern tile"), "nothing selected: {err}"); + unchanged(&s, &before, steps, "nothing selected"); + s.execute("object.pattern.edit", &json!({"name": "Holds dots"})).unwrap(); + let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len()); + let err = s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [plain.0]})).unwrap_err(); + assert!(matches!(&err, EngineError::Disabled(_, w) if w == "finish editing the pattern first"), "while editing: {err}"); + unchanged(&s, &before, steps, "while editing"); +} + fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document { Arc::make_mut(&mut s.doc_mut().unwrap().doc) } diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index 10c2edcc17..b2664a9682 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -836,6 +836,21 @@ fn a_null_in_group_colors_removes_that_swatch_and_the_ones_after_it_keep_their_p assert_eq!(link(&s, green), ("#00ff00".into(), Some(names[2].clone())), "art linked to a swatch that stays keeps its link"); } +/// "keep" in `groupColors` leaves the group's swatch at its place as it is, without Global Adjust, +/// and past the group's swatches it adds none. +#[test] +fn keep_in_group_colors_leaves_that_swatch_as_it_is() { + let mut s = session(); + run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#2878f0", "#ff0000"]})); + let p = json!({"map": [], "group": "Brand", "groupColors": ["keep", "#00ff00", "keep"], "globalAdjust": {"brightness": -50}}); + run(&mut s, "recolor.apply", p); + let g = &s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches; + let g: Vec = g.iter().map(|w| w.paint.color().unwrap().to_hex()).collect(); + assert_eq!(g.len(), 2, "{g:?}"); + assert_eq!(g[0], "#2878f0", "the kept swatch takes no Global Adjust"); + assert_ne!(g[1], "#00ff00", "the other new color takes it"); +} + /// A gradient or pattern swatch of the group keeps its place and its paint when `recolor.apply` /// rewrites the group: the group's colors, from the rows or from `groupColors`, go to its color /// swatches in order. diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 7c8c167527..7653dc083d 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -12,12 +12,14 @@ use crate::*; const DENIED: &str = "Script file access denied"; -/// A fresh folder for test `name`, with a `main` folder inside it for the script. +/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real +/// path: kept grants hold real paths, and a path named through a link (macOS's `/var` is +/// `/private/var`) is refused by its names alone. fn folder(name: &str) -> PathBuf { let base = std::env::temp_dir().join(format!("vc-script-io-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&base); std::fs::create_dir_all(base.join("main")).unwrap(); - base + std::fs::canonicalize(&base).unwrap() } fn write(path: &Path, bytes: &[u8]) { diff --git a/crates/engine/src/tests/swatchcmds.rs b/crates/engine/src/tests/swatchcmds.rs index 1b87639ef9..ff02889253 100644 --- a/crates/engine/src/tests/swatchcmds.rs +++ b/crates/engine/src/tests/swatchcmds.rs @@ -125,6 +125,69 @@ fn add_used_colors_skips_colours_that_have_swatches() { assert!(doc(&s).swatch("R=171 G=205 B=239").unwrap().global); } +/// A run that finds no new color, over all the art or the selection, records no undo step. +#[test] +fn add_used_colors_with_no_new_color_records_no_undo_step() { + let mut s = session(); + let a = rect_filled(&mut s, json!({"color": "#123456"})); + run(&mut s, "swatch.addUsedColors", json!({})); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let before = doc(&s).clone(); + let undo = undo_len(&s); + for p in [json!({}), json!({"selection": true, "global": true})] { + assert_eq!(run(&mut s, "swatch.addUsedColors", p), json!({"added": [], "linked": 0})); + assert_eq!(undo_len(&s), undo); + assert_eq!(*doc(&s), before); + } + // An empty selection is still an error, with nothing changed. + run(&mut s, "select.set", json!({"ids": []})); + let undo = undo_len(&s); + assert!(s.execute("swatch.addUsedColors", &json!({"selection": true})).is_err()); + assert_eq!(undo_len(&s), undo); +} + +/// A run that finds no new color, while the Type tool is typing, still ends the typing session: the +/// typing is its own undo step. +#[test] +fn add_used_colors_with_no_new_color_ends_the_typing() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut s = session(); + let v = ViewInfo::default(); + let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 10, "text": "Hello"}))["id"].as_u64().unwrap()); + run(&mut s, "swatch.addUsedColors", json!({})); + s.select_tool("type", v).unwrap(); + let b = doc(&s).bounds_of(&[t], false).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, b.x1 - 1.0, b.center().y), v).unwrap(); + } + s.tool_text("!", v).unwrap(); + assert!(crate::cmd::typing_in_progress(&s)); + let steps = undo_len(&s); + assert_eq!(run(&mut s, "swatch.addUsedColors", json!({})), json!({"added": [], "linked": 0})); + assert!(!crate::cmd::typing_in_progress(&s)); + let labels: Vec = s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect(); + assert_eq!((labels.len(), labels.last().map(String::as_str)), (steps + 1, Some("Typing"))); +} + +/// Add Selected Colors while Global Edit is on links only the selected art: a member of the same +/// shape with another color keeps its color and stays unlinked, and Global Edit stays on. +#[test] +fn add_selected_colors_in_global_edit_keeps_the_other_members_colors() { + let mut s = session(); + let a = rect_filled(&mut s, json!({"color": "#123456"})); + let b = rect_filled(&mut s, json!({"color": "#654321"})); + run(&mut s, "select.set", json!({"ids": [a.0]})); + let r = run(&mut s, "select.globalEdit", json!({})); + assert_eq!((r["active"].clone(), r["ids"].clone()), (json!(true), json!([a.0, b.0])), "the other rectangle is a member"); + let other = fill(&s, b); + let undo = undo_len(&s); + run(&mut s, "swatch.addUsedColors", json!({"selection": true, "global": true})); + assert!(matches!(fill(&s, a), Paint::Solid { swatch: Some(_), .. }), "{:?}", fill(&s, a)); + assert_eq!(fill(&s, b), other, "the unselected member keeps its color"); + assert_eq!(undo_len(&s), undo + 1); + assert!(s.doc().unwrap().global_edit.is_some(), "Global Edit stays on"); +} + /// Give `id` the fill `p` exactly as written (a command would round or convert some colors). fn set_fill(s: &mut Session, id: NodeId, p: Paint) { std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().appearance.set_fill(p); diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index fdcd554991..8036bf04c3 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -160,6 +160,37 @@ fn save_and_load_round_trip_keeps_cmyk_spot_and_groups() { assert!(s.execute("swatch.library.save", &json!({"user": true})).is_err(), "no user folder in a headless session"); } +/// A library color group that holds a gradient comes into the document whole, the gradient at its +/// place in the group, as a `.ai` library's pattern swatch comes in its color group. +#[test] +fn add_brings_a_library_color_group_holding_a_gradient_whole() { + let mut s = session(); + run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#123456", "#abcdef"]})); + let r = run(&mut s, "swatch.library.save", json!({"names": ["Brand", "Sunset"], "name": "Mixed"})); + // Move the Sunset gradient into the library's Brand group, as a hand-edited file can. + let mut lib: Value = serde_json::from_str(r["data"].as_str().unwrap()).unwrap(); + let swatches = lib["swatches"].as_array_mut().unwrap(); + let at = swatches.iter().position(|w| w["name"] == "Sunset").unwrap(); + let sunset = swatches.remove(at); + lib["groups"][0]["swatches"].as_array_mut().unwrap().insert(1, sunset); + let r = run(&mut s, "swatch.library.load", json!({"data": lib.to_string(), "name": "mixed.vcswatches"})); + let id = r["library"].as_str().unwrap().to_string(); + let (_, loaded) = cmd::swatchlib::library(&s, &id).unwrap(); + assert!(matches!(loaded.groups[0].swatches[1].paint, Paint::Gradient(_)), "the reader keeps the gradient in the group"); + run(&mut s, "swatch.delete", json!({"names": ["Brand", "Sunset"]})); + for p in [json!({"library": id}), json!({"library": id, "names": ["Brand"]})] { + let undo = undo_len(&s); + let r = run(&mut s, "swatch.library.add", p.clone()); + assert!(r["added"].as_array().unwrap().iter().any(|n| n == "Sunset"), "{p}: {r}"); + let brand = doc(&s).swatch_groups.iter().find(|g| g.name == "Brand").map(|g| g.swatches.clone()).unwrap_or_default(); + let kinds: Vec<(&str, bool)> = brand.iter().map(|w| (w.name.as_str(), matches!(w.paint, Paint::Gradient(_)))).collect(); + assert_eq!(kinds.len(), 3, "{p}: {kinds:?}"); + assert_eq!(kinds[1], ("Sunset", true), "{p}: the gradient keeps its place in the group"); + assert_eq!(undo_len(&s), undo + 1, "{p}: one undo step"); + run(&mut s, "edit.undo", json!({})); + } +} + /// The swatch library commands, and the graphic style library save and load that share their file /// handling, refuse a parameter of the wrong form, such as `user: "true"` or `names: "Grays"`, with /// an error that names it; the document keeps its swatches and no undo step is recorded. A null diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs index b8cb29f213..4a75c170c7 100644 --- a/crates/engine/src/tests/symbolism_options.rs +++ b/crates/engine/src/tests/symbolism_options.rs @@ -180,6 +180,48 @@ fn average_at_the_mean_adds_no_undo_step() { assert!(state(&s) == before); } +/// An instance the brush reaches but leaves as it is (the Symbol Screener with Alt on an opaque +/// instance, or without Alt on one at the lowest opacity it gives) is not counted, and a stroke +/// that changes no instance adds no undo step. +#[test] +fn an_instance_left_as_it_is_is_not_counted() { + let mut s = session(); + let (opaque, faint) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 300.0, 150.0)); + s.execute("transparency.set", &json!({"ids": [faint.0], "opacity": 5})).unwrap(); + let before = state(&s); + let r = adjust(&mut s, json!({"tool": "screen", "points": [[100, 150]], "radius": 30, "intensity": 10, "alt": true})); + assert_eq!(r["count"], 0, "Alt on an opaque instance"); + let r = adjust(&mut s, json!({"tool": "screen", "points": [[300, 150]], "radius": 30, "intensity": 10})); + assert_eq!(r["count"], 0, "an instance at 5%"); + assert!(state(&s) == before, "a stroke that changes nothing changed the document or its history"); + // A stroke over both counts only the instance it changes. + let r = adjust(&mut s, json!({"tool": "screen", "points": [[200, 150]], "radius": 150, "intensity": 10})); + assert_eq!(r["count"], 1); + assert!(node(&s, opaque).opacity < 1.0 && node(&s, faint).opacity == 0.05); +} + +/// Average gives an opacity below 5% when that is the mean: the Symbol Sprayer's new instance and +/// the Symbol Screener's instances take the mean of the instances under the brush. +#[test] +fn average_keeps_a_mean_opacity_below_five_percent() { + let mut s = session(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let first = members(&s, set)[0]; + s.execute("transparency.set", &json!({"ids": [first.0], "opacity": 2})).unwrap(); + s.select(|_, sel| sel.set([set])).unwrap(); + s.execute("symbol.spray", &json!({"name": "Dot", "points": [[215, 150]], "radius": 30})).unwrap(); + let sprayed = *members(&s, set).last().unwrap(); + assert!((node(&s, sprayed).opacity - 0.02).abs() < 1e-6, "{}", node(&s, sprayed).opacity); + // Two instances at 0% and 4%: Average brings both toward 2%, and neither goes past it. + let mut s = session(); + let (a, b) = (dot(&mut s, 200.0, 150.0), dot(&mut s, 220.0, 150.0)); + s.execute("transparency.set", &json!({"ids": [a.0], "opacity": 0})).unwrap(); + s.execute("transparency.set", &json!({"ids": [b.0], "opacity": 4})).unwrap(); + adjust(&mut s, json!({"tool": "screen", "points": [[210, 150]], "radius": 40, "intensity": 10, "method": "average"})); + let (pa, pb) = (node(&s, a).opacity, node(&s, b).opacity); + assert!(pa > 0.0 && pa <= 0.02 + 1e-6 && (0.02 - 1e-6..0.04).contains(&pb), "{pa} {pb}"); +} + /// Average evens out the Symbol Stainer's amount and the Symbol Scruncher's spacing. #[test] fn average_evens_out_the_stain_and_the_spacing() { @@ -279,6 +321,38 @@ fn an_unknown_method_is_refused() { assert_eq!(center(&s, a), Point::new(200.0, 150.0)); } +/// `tool.setOption` refuses a Symbolism Tools Options value of the wrong kind or name, and the +/// tool's options stay as they were. +#[test] +fn tool_set_option_refuses_bad_symbolism_options() { + let mut s = session(); + let before = s.tool_options_of("symbolSizer"); + for (key, bad, want) in [ + ("method", json!("smooth"), "`method` must be one of userDefined, average, random"), + ("sprayStain", json!("random"), "`sprayStain` must be one of average, userDefined"), + ("usePressure", json!("yes"), "`usePressure` must be true or false"), + ("diameter", json!("big"), "`diameter` must be a number from 2 to 2000"), + ("style", json!(3), "`style` must be a string or null"), + ("diameter", json!(1), "`diameter` must be a number from 2 to 2000"), + ] { + let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": {key: bad}})); + assert_eq!(r, Err(want.to_string()), "{key}"); + assert_eq!(s.tool_options_of("symbolSizer"), before, "{key}"); + } + let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": {"method": "random", "sprayStain": "userDefined"}})).unwrap(); + assert_eq!((r["method"].as_str(), r["sprayStain"].as_str()), (Some("random"), Some("userDefined"))); + // Every option the options dialog sends is taken, together. + let all = json!({ + "diameter": 100.0, "intensity": 6.0, "density": 4.0, "usePressure": true, "method": "average", "showBrush": false, + "sprayScrunch": "userDefined", "spraySize": "userDefined", "spraySpin": "userDefined", "sprayScreen": "userDefined", + "sprayStain": "average", "sprayStyle": "userDefined", "proportional": false, "affectsDensity": true, + }); + let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": all})).unwrap(); + for (key, v) in all.as_object().unwrap() { + assert_eq!(&r[key], v, "{key}"); + } +} + /// With `usePressure` each point's pen pressure is the intensity there; without it the pressure is /// not used. A pressure that isn't a number is an error. #[test] @@ -316,6 +390,13 @@ fn pen_pressure_is_the_intensity_with_use_pressure() { json!({"tool": tool, "points": [[200, 150, "hard"]], "usePressure": true}), "a point's pressure must be a number, not \"hard\"", ); + // Also on a point without coordinates, beside one that has them. + refused( + &mut s, + "symbol.adjust", + json!({"tool": tool, "points": [[200, 150], [null, 0, "bad"]], "usePressure": true}), + "a point's pressure must be a number, not \"bad\"", + ); } for key in ["usePressure", "proportional", "affectsDensity"] { let mut p = json!({"tool": "size", "points": [[200, 150]]}); @@ -644,6 +725,45 @@ fn set_density_starts_from_the_density_a_set_was_sprayed_at() { assert!((center(&s, a).x - (150.0 - 50.0 * 0.25 / 0.65)).abs() < 1e-9, "{:?}", center(&s, a)); } +/// A set duplicated packs from the density recorded for its source, and a pasted set from the +/// density its source had at Copy: after Cut, after the source is given another density, and in +/// another document. +#[test] +fn a_copied_set_packs_from_the_density_of_its_source() { + for copy in ["duplicate", "paste", "cut", "changed after copy", "other document"] { + let mut s = session(); + let row: Vec = (0..4).map(|i| json!([60.0 + 60.0 * f64::from(i), 150.0])).collect(); + let set = + NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4, "density": 2})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| sel.set([set])).unwrap(); + let first = match copy { + "duplicate" => "edit.duplicate", + "cut" => "edit.cut", + _ => "edit.copy", + }; + s.execute(first, &json!({})).unwrap(); + if copy == "changed after copy" { + s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap(); + } + if copy == "other document" { + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + } + if copy != "duplicate" { + s.execute("edit.paste", &json!({})).unwrap(); + } + let copied = s.doc().unwrap().selection.objects.clone(); + assert!(copied.len() == 1 && (copy == "other document" || copied[0] != set), "{copy}: {copied:?}"); + let ids = members(&s, copied[0]); + let xs = |s: &Session| ids.iter().map(|id| center(s, *id).x).collect::>(); + let was = xs(&s); + let middle = was.iter().sum::() / 4.0; + s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [copied[0].0]})).unwrap(); + for (before, after) in was.iter().zip(xs(&s)) { + assert!((after - (middle + (before - middle) * 0.25 / 0.95)).abs() < 1e-9, "{copy}: {before} -> {after}"); + } + } +} + /// A set of one instance takes the new density without moving, as one undo step, so a later change /// packs it from that density; setting the density it already has adds no undo step. #[test] @@ -719,6 +839,102 @@ fn set_density_refuses_bad_densities_and_objects_without_a_set() { assert!(state(&s) == before); } +/// The Symbol Styler applies the style gradually, by the brush's strength at the instance: the pen +/// pressure with Use Pressure Pen, else the intensity, less toward the brush's edge. Random gives +/// each instance a share of that amount. +#[test] +fn the_styler_applies_the_style_by_the_brushs_strength() { + let styled = |extra: Value, x: f64| { + let mut s = session(); + let a = dot(&mut s, 100.0, 150.0); + let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + let mut p = json!({"tool": "style", "points": [[x, 150]], "radius": 10, "style": "Blue"}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + adjust(&mut s, p); + node(&s, a).appearance.fill().map_or(0.0, |f| f.opacity) + }; + let near = |a: f32, b: f32| (a - b).abs() < 1e-6; + assert!(near(styled(json!({"intensity": 10}), 100.0), 1.0), "full strength at the center"); + assert!(near(styled(json!({"intensity": 5}), 100.0), 0.5)); + assert!(near(styled(json!({"intensity": 10}), 105.0), 0.5), "half way to the edge"); + assert!(near(styled(json!({"usePressure": true, "points": [[100, 150, 0.25]]}), 100.0), 0.25)); + assert!(near(styled(json!({"usePressure": true, "points": [[100, 150, 1.0]]}), 100.0), 1.0)); + assert_eq!(styled(json!({"usePressure": true, "points": [[100, 150, 0.0]]}), 100.0), 0.0, "no pressure, no style"); + // Random: instances the same distance from the point take different amounts, each from none to + // the User Defined amount there (0.25: pressure 0.5, half way to the brush's edge). + let mut s = session(); + let ring: Vec = (0..6) + .map(|i| { + let a = f64::from(i) * std::f64::consts::TAU / 6.0; + dot(&mut s, 100.0 + 5.0 * a.cos(), 150.0 + 5.0 * a.sin()) + }) + .collect(); + let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + adjust(&mut s, json!({"tool": "style", "points": [[100, 150, 0.5]], "radius": 10, "usePressure": true, "method": "random", "style": "Blue"})); + let amounts: Vec = ring.iter().map(|a| node(&s, *a).appearance.fill().map_or(0.0, |f| f.opacity)).collect(); + assert!(amounts.iter().all(|a| *a <= 0.25 + 1e-6), "{amounts:?}"); + assert!(amounts.iter().any(|a| *a > 0.0), "{amounts:?}"); + assert!(amounts.iter().any(|a| (a - amounts[0]).abs() > 1e-6), "{amounts:?}"); +} + +/// A sprayed instance's Average stain is the stain of the nearest instance whose stain shows: one +/// at no opacity is passed over and counts as no stain in the mean amount. +#[test] +fn average_spray_passes_over_a_stain_at_no_opacity() { + use vectorcraft_color::{Color, Paint}; + let mut s = session(); + let set = + NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150], [130, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let ids = members(&s, set); + assert_eq!(ids.len(), 2); + s.edit("Stains", |d, _| { + for (id, color, amount) in [(ids[0], Color::rgb(1.0, 0.0, 0.0), 0.0), (ids[1], Color::rgb(0.0, 0.0, 1.0), 1.0)] { + let n = d.node_mut(id).unwrap(); + n.appearance.items.retain(|i| !matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))); + let mut f = vectorcraft_doc::FillLayer::new(Paint::solid(color)); + f.opacity = amount; + n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f)); + } + Ok(()) + }) + .unwrap(); + s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150]], "radius": 40})).unwrap(); + let new: Vec = members(&s, set).into_iter().filter(|id| !ids.contains(id)).collect(); + assert_eq!(new.len(), 1); + let f = node(&s, new[0]).appearance.fill().cloned().unwrap(); + assert_eq!(f.paint, Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + assert!((f.opacity - 0.5).abs() < 1e-6, "{}", f.opacity); +} + +/// The Symbol Shifter moves an instance whose transform flattens it (it has no size), as it moves +/// any other, and counts it. +#[test] +fn the_shifter_moves_an_instance_without_a_size() { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + s.edit("Flatten", |d, _| { + if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(a).map(|n| &mut n.kind) { + *xf = Affine::new([0.0, 0.0, 0.0, 0.0, 200.0, 150.0]); + } + Ok(()) + }) + .unwrap(); + let r = adjust(&mut s, json!({"tool": "shift", "points": [[200, 150], [210, 150]], "radius": 40, "intensity": 10})); + assert_eq!(r["count"], 1); + assert!(center(&s, a).x > 200.0, "{:?}", center(&s, a)); + // Average has no mean of such instances to move toward: it leaves them as they are. + let (before, x) = (state(&s), center(&s, a).x); + let r = adjust(&mut s, json!({"tool": "screen", "method": "average", "points": [[x, 150]], "radius": 40, "intensity": 10})); + assert_eq!(r["count"], 0); + assert!(state(&s) == before); +} + /// An instance with no size is shifted and screened as before; only Average, which needs its size, /// leaves it as it is. #[test] @@ -759,6 +975,29 @@ fn an_instance_without_a_size_is_changed_by_every_method_but_average() { assert!(state(&s) == before); } +/// Average Stainer: an instance whose stain is at no opacity has no stain of its own, so it takes +/// the stain the mean picks, not its hidden paint. +#[test] +fn average_stain_replaces_a_stain_at_no_opacity() { + use vectorcraft_color::{Color, Paint}; + let mut s = session(); + let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 120.0, 150.0)); + s.edit("Stains", |d, _| { + for (id, color, amount) in [(a, Color::rgb(1.0, 0.0, 0.0), 0.0), (b, Color::rgb(0.0, 0.0, 1.0), 1.0)] { + let n = d.node_mut(id).unwrap(); + let mut f = vectorcraft_doc::FillLayer::new(Paint::solid(color)); + f.opacity = amount; + n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f)); + } + Ok(()) + }) + .unwrap(); + adjust(&mut s, json!({"tool": "stain", "method": "average", "points": [[100, 150]], "radius": 40, "intensity": 10})); + let f = node(&s, a).appearance.fill().cloned().unwrap(); + assert_eq!(f.paint, Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + assert!(f.opacity > 0.0, "{}", f.opacity); +} + /// A stroke that leaves every instance under the brush as it is (each already at full stain, or /// at the least opacity) counts none and adds no undo step. #[test] diff --git a/crates/engine/src/tests/symbolism_shift.rs b/crates/engine/src/tests/symbolism_shift.rs new file mode 100644 index 0000000000..ca08dc2069 --- /dev/null +++ b/crates/engine/src/tests/symbolism_shift.rs @@ -0,0 +1,272 @@ +//! The symbolism tools' Shift forms in `symbol.adjust {shift}`: the Symbol Shifter's stacking +//! order, the Symbol Sizer keeping the set's density, and the Symbol Stainer and Symbol Styler +//! keeping their amount while the color or style changes. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeKind}; +use vectorcraft_geom::Point; + +use crate::*; + +/// A document with the 20 pt square symbol "Dot" and nothing selected. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + s.execute("symbol.new", &json!({"name": "Dot"})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + s +} + +/// An instance of Dot centered on (`x`, `y`), not selected. +fn dot(s: &mut Session, x: f64, y: f64) -> NodeId { + let id = NodeId(s.execute("symbol.place", &json!({"name": "Dot", "x": x, "y": y})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| sel.clear()).unwrap(); + id +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +fn center(s: &Session, id: NodeId) -> Point { + match node(s, id).kind { + NodeKind::SymbolInstance { xf, .. } => xf * Point::ZERO, + other => panic!("not an instance: {other:?}"), + } +} + +fn width(s: &Session, id: NodeId) -> f64 { + node(s, id).geometric_bounds().unwrap().width() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn state(s: &Session) -> (Document, usize) { + ((*s.doc().unwrap().doc).clone(), undo_len(s)) +} + +fn adjust(s: &mut Session, p: Value) -> Value { + s.execute("symbol.adjust", &p).unwrap() +} + +/// The children of symbol set `set`, in stacking order (the first is at the back). +fn members(s: &Session, set: NodeId) -> Vec { + node(s, set).children().unwrap().iter().map(|c| c.id).collect() +} + +/// The instance's fill: its color as RGB and its amount. +fn fill(s: &Session, id: NodeId) -> Option<([f32; 3], f32)> { + node(s, id).appearance.fill().map(|f| (f.paint.color().map_or([0.0; 3], |c| c.to_rgb()), f.opacity)) +} + +/// A symbol set of four instances in a row at x = 40, 120, 200 and 280, selected. +fn row(s: &mut Session) -> (NodeId, Vec) { + let pts: Vec = (0..4).map(|i| json!([40.0 + 80.0 * f64::from(i), 150.0])).collect(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": pts, "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let ids = members(s, set); + assert_eq!(ids.len(), 4); + (set, ids) +} + +/// Shift-click with the Symbol Shifter brings the instances under the brush one place forward in +/// the set, and Alt+Shift-click sends them one place backward, without moving them on the canvas. +#[test] +fn shift_click_with_the_shifter_changes_the_stacking_order() { + let mut s = session(); + let (set, ids) = row(&mut s); + let centers: Vec = ids.iter().map(|id| center(&s, *id)).collect(); + let click = |s: &mut Session, x: f64, alt: bool| { + adjust(s, json!({"tool": "shift", "points": [[x, 150]], "radius": 10, "intensity": 10, "shift": true, "alt": alt}))["count"].clone() + }; + let steps = undo_len(&s); + assert_eq!(click(&mut s, 120.0, false), 1); + assert_eq!(members(&s, set), [ids[0], ids[2], ids[1], ids[3]]); + assert_eq!(undo_len(&s), steps + 1, "one undo step"); + assert_eq!(ids.iter().map(|id| center(&s, *id)).collect::>(), centers, "nothing moves on the canvas"); + assert_eq!(click(&mut s, 120.0, false), 1); + assert_eq!(members(&s, set), [ids[0], ids[2], ids[3], ids[1]]); + // Already in front of the others: nothing changes and no undo step is added. + let before = state(&s); + assert_eq!(click(&mut s, 120.0, false), 0); + assert!(state(&s) == before); + // Alt sends it back one place at a time; at the back it stays. + assert_eq!(click(&mut s, 120.0, true), 1); + assert_eq!(members(&s, set), [ids[0], ids[2], ids[1], ids[3]]); + click(&mut s, 120.0, true); + click(&mut s, 120.0, true); + assert_eq!(members(&s, set), [ids[1], ids[0], ids[2], ids[3]]); + assert_eq!(click(&mut s, 120.0, true), 0); + // Two instances under the brush move together past the next one. + s.execute("edit.undo", &json!({})).unwrap(); + let both = adjust(&mut s, json!({"tool": "shift", "points": [[40, 150], [120, 150]], "radius": 10, "intensity": 10, "shift": true})); + assert_eq!(both["count"], 2); + assert_eq!(members(&s, set), [ids[2], ids[0], ids[1], ids[3]]); + // Without Shift a drag moves the instances, as before. + adjust(&mut s, json!({"tool": "shift", "points": [[280, 150], [290, 150]], "radius": 30, "intensity": 10})); + assert!(center(&s, ids[3]).x > centers[3].x); +} + +/// Shift with the Symbol Sizer resizes the instances and keeps their centers where they are, even +/// with Resizing Affects Density. +#[test] +fn shift_with_the_sizer_keeps_the_density() { + let at = |affects: bool, shift: bool| { + let mut s = session(); + let a = dot(&mut s, 220.0, 150.0); + adjust( + &mut s, + json!({"tool": "size", "points": [[200, 150], [200, 150]], "radius": 60, "intensity": 10, "affectsDensity": affects, "shift": shift}), + ); + (center(&s, a), width(&s, a)) + }; + let (moved, _) = at(true, false); + assert!(moved.x > 220.5, "{moved:?}"); + let (kept, grown) = at(true, true); + assert!((kept.x - 220.0).abs() < 1e-9 && (kept.y - 150.0).abs() < 1e-9 && grown > 20.5, "{kept:?} {grown}"); + // It resizes as the Sizer does with Resizing Affects Density off. + assert_eq!(at(false, false), (kept, grown)); + assert_eq!(at(false, true), (kept, grown)); +} + +/// Shift with the Symbol Stainer keeps the stain's amount and moves its color toward the fill +/// color; an instance without a stain is left as it is. +#[test] +fn shift_with_the_stainer_keeps_the_amount_and_changes_the_color() { + let mut s = session(); + let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 300.0, 150.0)); + adjust(&mut s, json!({"tool": "stain", "points": [[100, 150], [100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"})); + let (red, amount) = fill(&s, a).unwrap(); + assert!(amount > 0.2 && red[0] > 0.99 && red[2] < 0.01, "{red:?} {amount}"); + // A second fill below the stain, which Shift leaves as it is. + s.edit("Add fill", |d, _| { + let n = d.node_mut(a).unwrap(); + let lower = n.appearance.fill().unwrap().clone(); + n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer { opacity: 0.5, ..lower })); + Ok(()) + }) + .unwrap(); + let lower = node(&s, a).appearance.items[0].clone(); + let stain = |s: &mut Session, x: f64| { + adjust(s, json!({"tool": "stain", "points": [[x, 150], [x, 150]], "radius": 5, "intensity": 10, "color": "#0000ff", "shift": true})) + }; + assert_eq!(stain(&mut s, 100.0)["count"], 1); + let (color, kept) = fill(&s, a).unwrap(); + assert_eq!(kept, amount, "the amount stays"); + assert!(color[0] < red[0] && color[2] > 0.01, "toward blue: {color:?}"); + assert_eq!((node(&s, a).appearance.items.len(), &node(&s, a).appearance.items[0]), (2, &lower), "the other fill stays"); + // More strokes go on toward blue, with the amount still the same. + for _ in 0..30 { + stain(&mut s, 100.0); + } + let (bluer, kept) = fill(&s, a).unwrap(); + assert_eq!(kept, amount); + assert!(bluer[2] > 0.9 && bluer[0] < 0.1, "{bluer:?}"); + // Alt has no effect with Shift. + let green = json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#00ff00", "shift": true}); + adjust(&mut s, green.clone()); + let plain = fill(&s, a); + s.execute("edit.undo", &json!({})).unwrap(); + let mut with_alt = green; + with_alt["alt"] = json!(true); + adjust(&mut s, with_alt); + assert_eq!(fill(&s, a), plain); + // No stain on b: nothing changes and no undo step is added. + let before = state(&s); + assert_eq!(stain(&mut s, 300.0)["count"], 0); + assert!(state(&s) == before && fill(&s, b).is_none()); +} + +/// Shift with the Symbol Styler keeps the amount of the instance's stain or style and moves its +/// fill toward the selected style's fill. +#[test] +fn shift_with_the_styler_keeps_the_amount_and_changes_the_style() { + let mut s = session(); + let a = dot(&mut s, 100.0, 150.0); + let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + // A red stain at part strength. + adjust(&mut s, json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"})); + let (red, amount) = fill(&s, a).unwrap(); + assert!(red[0] > 0.99 && amount > 0.0 && amount < 0.5, "{red:?} {amount}"); + // Half the brush's strength at a point 2.5 pt from the instance: half way to blue. + adjust(&mut s, json!({"tool": "style", "points": [[102.5, 150]], "radius": 5, "intensity": 10, "style": "Blue", "shift": true})); + let (mixed, kept) = fill(&s, a).unwrap(); + assert_eq!(kept, amount); + assert!(mixed[0] < 0.99 && mixed[2] > 0.01, "{mixed:?}"); + // At the brush's center with full intensity it takes the style's fill. + adjust(&mut s, json!({"tool": "style", "points": [[100, 150]], "radius": 5, "intensity": 10, "style": "Blue", "shift": true})); + let (blue, kept) = fill(&s, a).unwrap(); + assert_eq!(kept, amount); + assert!(blue[2] > 0.99 && blue[0] < 0.01, "{blue:?}"); +} + +/// A stain or style with no form between it and the new paint (a pattern and a solid color) takes +/// the new paint at once, at any strength, and keeps its amount. +#[test] +fn shift_changes_a_paint_that_has_no_form_in_between() { + use vectorcraft_color::Paint; + let mut s = session(); + let a = dot(&mut s, 100.0, 150.0); + s.edit("Pattern fill", |d, _| { + let mut f = vectorcraft_doc::FillLayer::new(Paint::Pattern { pattern: "Tile".into(), xf: Default::default() }); + f.opacity = 0.4; + d.node_mut(a).unwrap().appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f)); + Ok(()) + }) + .unwrap(); + // Low intensity, near the brush's edge: far below half strength. + let r = adjust(&mut s, json!({"tool": "stain", "points": [[104, 150]], "radius": 5, "intensity": 1, "color": "#ff0000", "shift": true})); + assert_eq!(r["count"], 1); + let f = node(&s, a).appearance.fill().cloned().unwrap(); + assert_eq!(f.opacity, 0.4, "the amount stays"); + assert!(f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.99), "{:?}", f.paint); +} + +/// A style name the document has no style for (the Styler's style from another document, or one +/// since renamed or deleted) moves the fill toward the document's first style after the default +/// one, as no name does, and the stain's amount stays. +#[test] +fn the_styler_takes_the_first_style_for_a_name_the_document_lacks() { + use vectorcraft_color::{Color, Paint}; + let styled = |style: Option<&str>| { + let mut s = session(); + let a = dot(&mut s, 100.0, 150.0); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + adjust(&mut s, json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"})); + let mut p = json!({"tool": "style", "points": [[100, 150]], "radius": 5, "intensity": 10, "shift": true}); + if let Some(n) = style { + p["style"] = json!(n); + } + let stained = node(&s, a).appearance.fill().map(|f| f.opacity); + adjust(&mut s, p); + let f = node(&s, a).appearance.fill().cloned().unwrap(); + assert_eq!(Some(f.opacity), stained, "the amount stays"); + let first = s.doc().unwrap().doc.graphic_styles[1].appearance.fill_paint(); + (f.paint, first) + }; + let (missing, first) = styled(Some("No Such Style")); + let (none, _) = styled(None); + assert_eq!(missing, none); + // The paint is the first style's, not the active fill color. + assert_eq!(none, first); + assert_ne!(none, Paint::solid(Color::rgb(0.0, 1.0, 0.0))); +} + +/// A `shift` that is not true, false or null is refused and changes nothing. +#[test] +fn a_bad_shift_is_refused() { + let mut s = session(); + dot(&mut s, 100.0, 150.0); + for tool in ["shift", "size", "stain", "style"] { + let before = state(&s); + let r = s.execute("symbol.adjust", &json!({"tool": tool, "points": [[100, 150]], "shift": "yes"})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "`shift` must be true or false"), "{tool}: {r:?}"); + assert!(state(&s) == before); + } +} diff --git a/crates/engine/src/tests/three_point_arc.rs b/crates/engine/src/tests/three_point_arc.rs new file mode 100644 index 0000000000..ebd755dda7 --- /dev/null +++ b/crates/engine/src/tests/three_point_arc.rs @@ -0,0 +1,220 @@ +//! `shape.threePointArc`: an open circular arc between two ends, through a third point or +//! leaving an end toward it, and the Three-Point Arc tool's clicks that run it. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_geom::Point; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + +use crate::*; + +const C: &str = "shape.threePointArc"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).unwrap().clone() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn object_count(s: &Session) -> usize { + let mut n = 0; + s.doc().unwrap().doc.walk(|_| n += 1); + n +} + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +/// The largest distance of `points` from the path of `id`. +fn farthest_from_path(s: &Session, id: NodeId, points: &[Point]) -> f64 { + let n = node(s, id); + let path = n.path_data().unwrap(); + points.iter().map(|p| path.nearest(*p).unwrap().4).fold(0.0, f64::max) +} + +/// The arc from (0, 0) to (80, 0) through (40, -40) is the upper half of the circle about +/// (40, 0) with radius 40: an open path from one end to the other, through the third point, with +/// no fill and a stroke, selected, and one undo step. +#[test] +fn the_arc_through_a_third_point_is_an_open_path_and_one_undo_step() { + let mut s = session(); + let undo = undo_len(&s); + let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "through": [40, -40]})).unwrap(); + assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(0.0), Some(40.0)), "{out}"); + // From (0, 0) over the top to (80, 0): clockwise on the page. + assert!((out["sweep"].as_f64().unwrap() - 180.0).abs() < 1e-9, "{out}"); + let id = id_of(&out); + let n = node(&s, id); + let NodeKind::Path { path, live: None, .. } = &n.kind else { panic!("not a plain path: {:?}", n.kind) }; + let sp = &path.subpaths[0]; + assert!(!sp.closed && path.subpaths.len() == 1); + assert_eq!((sp.anchors.first().map(|a| a.p), sp.anchors.last().map(|a| a.p)), (Some(Point::ORIGIN), Some(Point::new(80.0, 0.0)))); + assert!(farthest_from_path(&s, id, &[Point::new(40.0, -40.0)]) < 1e-9); + assert!(n.appearance.fill_paint().is_none(), "no fill"); + assert!(!n.appearance.stroke_paint().is_none(), "a stroke"); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + assert_eq!(undo_len(&s), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).is_none()); + // A third point between the quarter turns is an anchor too, so the path meets it exactly. + let via = Point::new(1000.0 * 20f64.to_radians().cos(), 1000.0 * 20f64.to_radians().sin()); + let out = s.execute(C, &json!({"start": [1000, 0], "end": [0, 1000], "through": [via.x, via.y]})).unwrap(); + let id = id_of(&out); + assert!(node(&s, id).path_data().unwrap().subpaths[0].anchors.iter().any(|a| a.p == via)); + assert!(farthest_from_path(&s, id, &[via]) < 1e-9); +} + +/// With `toward`, the arc leaves `start` heading at the point (its first handle points there), +/// or with `at: "end"` arrives at `end` along the line from the point to `end` (run backward, the +/// arc leaves `end` heading at the point). +#[test] +fn the_arc_toward_a_point_has_that_tangent_at_its_end() { + let mut s = session(); + let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "toward": [30, -30]})).unwrap(); + let n = node(&s, id_of(&out)); + let first = n.path_data().unwrap().subpaths[0].anchors[0]; + let d = (first.h_out - first.p).normalize(); + assert!((d.dot(vectorcraft_geom::Vec2::new(1.0, -1.0).normalize()) - 1.0).abs() < 1e-12, "{d:?}"); + // A quarter turn's tangent: the center is at (40, 40) and the radius √3200. + assert!((out["radius"].as_f64().unwrap() - 3200f64.sqrt()).abs() < 1e-9, "{out}"); + let out = s.execute(C, &json!({"start": [0, 0], "end": [80, 0], "toward": [50, -30], "at": "end"})).unwrap(); + let n = node(&s, id_of(&out)); + let last = *n.path_data().unwrap().subpaths[0].anchors.last().unwrap(); + let d = (last.p - last.h_in).normalize(); + assert!((d.dot(vectorcraft_geom::Vec2::new(1.0, 1.0).normalize()) - 1.0).abs() < 1e-12, "{d:?}"); + // The direction from the start and from the end mirror each other. + assert!((out["cx"].as_f64().unwrap() - 40.0).abs() < 1e-9 && (out["cy"].as_f64().unwrap() - 40.0).abs() < 1e-9, "{out}"); +} + +/// Points that are the same, a third point on the line through the ends, and an arc reaching past +/// the canvas are refused with a message; nothing is drawn and no undo step is added. +#[test] +fn points_with_no_arc_are_refused() { + let mut s = session(); + let (undo, count) = (undo_len(&s), object_count(&s)); + for p in [ + json!({"start": [0, 0], "end": [0, 0], "through": [10, 10]}), + json!({"start": [0, 0], "end": [80, 0], "through": [40, 0]}), + json!({"start": [0, 0], "end": [80, 0], "through": [120, 0]}), + json!({"start": [0, 0], "end": [80, 0], "through": [80, 0]}), + json!({"start": [0, 0], "end": [80, 0], "toward": [0, 0]}), + json!({"start": [0, 0], "end": [80, 0], "toward": [-50, 0]}), + json!({"start": [0, 0], "end": [80, 0], "toward": [40, 0], "at": "end"}), + json!({"start": [0, 0], "end": [0, 0], "toward": [10, 10]}), + ] { + let e = s.execute(C, &p).unwrap_err().to_string(); + assert!(e.contains("no arc fits these points"), "{p}: {e}"); + } + // Nearly in line beyond the end: the circle's center is about 1.2·10⁷ pt down the page, and the + // arc goes round the far side of it. + let far = json!({"start": [0, 0], "end": [80, 0], "through": [200, 0.001]}); + let e = s.execute(C, &far).unwrap_err().to_string(); + assert!(e.contains("result would exceed the canvas"), "{e}"); + assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); +} + +/// Missing or malformed points, both or neither of `through` and `toward`, an `at` that is not +/// "start" or "end", and an `at` with `through` are errors; nothing is drawn. +#[test] +fn malformed_params_are_refused() { + let mut s = session(); + let count = object_count(&s); + for (p, want) in [ + (json!({"end": [80, 0], "through": [40, 40]}), "`start` must be [x, y]"), + (json!({"start": [0, 0], "end": [80], "through": [40, 40]}), "`end` must be [x, y]"), + (json!({"start": [0, 0], "end": [80, 0], "through": [40, "a"]}), "`through` must be [x, y]"), + (json!({"start": [0, 0], "end": [80, 0], "through": null}), "`through` must be [x, y]"), + (json!({"start": [0, 0], "end": [80, 0], "toward": [10, 0, 0]}), "`toward` must be [x, y]"), + (json!({"start": [0, 0], "end": [80, 0]}), "give exactly one of `through` and `toward`"), + (json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "toward": [0, 40]}), "give exactly one of `through` and `toward`"), + (json!({"start": [0, 0], "end": [80, 0], "toward": [0, 40], "at": "middle"}), "`at` must be \"start\" or \"end\""), + (json!({"start": [0, 0], "end": [80, 0], "toward": [0, 40], "at": null}), "`at` must be \"start\" or \"end\""), + (json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "at": "end"}), "give `at` only with `toward`"), + (json!({"start": [0, 0], "end": [80, 0], "through": [40, 40], "at": "start"}), "give `at` only with `toward`"), + ] { + let e = s.execute(C, &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } + assert_eq!(object_count(&s), count); +} + +/// With Align New Objects to Pixel Grid on, the ends stay on the given points. +#[test] +fn the_arc_is_not_moved_onto_the_pixel_grid() { + let mut s = session(); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + let id = id_of(&s.execute(C, &json!({"start": [0.3, 0.2], "end": [80.6, 0.1], "through": [40.4, -39.7]})).unwrap()); + let n = node(&s, id); + let sp = &n.path_data().unwrap().subpaths[0]; + assert_eq!(sp.anchors.first().map(|a| a.p), Some(Point::new(0.3, 0.2))); + assert_eq!(sp.anchors.last().map(|a| a.p), Some(Point::new(80.6, 0.1))); + assert!(!n.extras().pixel_aligned); +} + +fn view() -> ViewInfo { + ViewInfo { smart_guides: false, ..ViewInfo::default() } +} + +fn click(s: &mut Session, x: f64, y: f64) { + for k in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(k, x, y).with_mods(Mods::default()), view()).unwrap(); + } +} + +/// With the Three-Point Arc tool, three clicks draw the arc in one undo step; `]` before the third +/// click makes the third point give the direction instead. Escape drops the ends. +#[test] +fn three_clicks_with_the_tool_draw_the_arc() { + let mut s = session(); + s.select_tool("threePointArc", view()).unwrap(); + let (undo, count) = (undo_len(&s), object_count(&s)); + click(&mut s, 100.0, 200.0); + click(&mut s, 180.0, 200.0); + assert_eq!((undo_len(&s), object_count(&s)), (undo, count), "two ends draw nothing yet"); + click(&mut s, 140.0, 160.0); + assert_eq!(undo_len(&s), undo + 1); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + assert!(farthest_from_path(&s, id, &[Point::new(100.0, 200.0), Point::new(140.0, 160.0), Point::new(180.0, 200.0)]) < 1e-9); + // Escape after the ends: the next clicks start afresh. + click(&mut s, 0.0, 0.0); + click(&mut s, 10.0, 300.0); + s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap(); + click(&mut s, 100.0, 300.0); + click(&mut s, 180.0, 300.0); + s.tool_key(ToolKey::BracketRight, Mods::default(), view()).unwrap(); + let undo = undo_len(&s); + // Straight up from the first end: the upper half circle about (140, 300). + click(&mut s, 100.0, 250.0); + assert_eq!(undo_len(&s), undo + 1); + let id = *s.doc().unwrap().selection.objects.first().unwrap(); + assert!(farthest_from_path(&s, id, &[Point::new(140.0, 260.0)]) < 1e-9); +} + +/// `tool.setOption` (the Tool Options dialog's Save) sets the tool's `direction` option, and +/// refuses a value that is not true or false, or an option the tool doesn't have. +#[test] +fn set_option_sets_the_direction_and_refuses_bad_values() { + let mut s = session(); + for on in [true, false] { + let set = s.set_tool_option_cmd(&json!({"tool": "threePointArc", "values": {"direction": on}})).unwrap(); + assert_eq!(set["direction"], json!(on)); + assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(on)); + } + let cases = [ + (json!({"tool": "threePointArc", "key": "direction", "value": "yes"}), "tool `threePointArc`: `direction` must be true or false"), + (json!({"tool": "threePointArc", "key": "bogus", "value": true}), "tool `threePointArc`: unknown option `bogus`"), + ]; + for (p, want) in cases { + assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}"); + } + assert_eq!(s.tool_options_of("threePointArc")["direction"], json!(false)); +} diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index fbde9edca7..69d382f2dc 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -138,6 +138,86 @@ fn a_dropped_press_does_not_keep_what_its_drag_changed() { assert_eq!(s.prefs.tool_settings["polygon"]["sides"], json!(7), "and stores its sides"); } +/// An option set with `tool.setOption` while a press is held survives the dropped press, in the +/// tool and in the stored options, while what the drag itself changed is put back in both. +#[test] +fn an_option_set_during_a_dropped_press_is_kept() { + let mut s = session(); + select(&mut s, "rectangularGrid"); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap(); + s.tool_key(ToolKey::Up, Mods::default(), v).unwrap(); + s.tool_key(ToolKey::Right, Mods::default(), v).unwrap(); + assert_eq!((s.tool_options()["rows"].clone(), s.tool_options()["columns"].clone()), (json!(6), json!(6))); + s.set_tool_option_cmd(&json!({"key": "columns", "value": 9})).unwrap(); + s.drop_tool_press(v).unwrap(); + let o = s.tool_options(); + assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(9)), "the drag's rows go back; the set columns stay"); + let saved = &s.prefs.tool_settings["rectangularGrid"]; + assert_eq!((saved["rows"].clone(), saved["columns"].clone()), (json!(5), json!(9)), "the drag's rows are not stored; the set columns are"); + select(&mut s, "selection"); + select(&mut s, "rectangularGrid"); + let o = s.tool_options(); + assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(9)), "a tool switch keeps the set columns"); + // The same through the desktop app's setter. + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap(); + s.tool_key(ToolKey::Up, Mods::default(), v).unwrap(); + s.set_tool_option("columns", &json!(3)); + s.drop_tool_press(v).unwrap(); + let o = s.tool_options(); + assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(3))); + let saved = &s.prefs.tool_settings["rectangularGrid"]; + assert_eq!((saved["rows"].clone(), saved["columns"].clone()), (json!(5), json!(3))); +} + +/// A Corner Radius preference set while a Rounded Rectangle press is held survives the dropped +/// press, in the tool and in the preference. +#[test] +fn a_corner_radius_set_during_a_dropped_press_is_kept() { + let mut s = session(); + select(&mut s, "roundedRectangle"); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap(); + let mut p = s.prefs.clone(); + p.corner_radius = 30.0; + s.apply_prefs(p); + s.drop_tool_press(v).unwrap(); + assert_eq!(s.tool_options()["cornerRadius"].as_f64(), Some(30.0), "the tool keeps the new radius"); + assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it"); +} + +/// An option set with `tool.setOption` on a tool that lent a selection tool for a Cmd-drag +/// survives the dropped press, in the tool and in the stored options. So does a Corner Radius +/// preference set while the Rounded Rectangle lends one. +#[test] +fn an_option_set_on_a_lending_tool_during_a_dropped_press_is_kept() { + let mut s = session(); + select(&mut s, "rectangularGrid"); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + let cmd = Mods { cmd: true, ..Default::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("rectangularGrid"), "the press lent a selection tool"); + s.set_tool_option_cmd(&json!({"tool": "rectangularGrid", "key": "columns", "value": 9})).unwrap(); + s.drop_tool_press(v).unwrap(); + assert_eq!(s.tool_id(), "rectangularGrid", "the lending tool is back"); + assert_eq!(s.tool_options()["columns"], json!(9), "the tool keeps the set columns"); + assert_eq!(s.prefs.tool_settings["rectangularGrid"]["columns"], json!(9), "and stores them"); + select(&mut s, "roundedRectangle"); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("roundedRectangle"), "the press lent a selection tool"); + let mut p = s.prefs.clone(); + p.corner_radius = 30.0; + s.apply_prefs(p); + s.drop_tool_press(v).unwrap(); + assert_eq!(s.tool_options()["cornerRadius"].as_f64(), Some(30.0), "the tool keeps the new radius"); + assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it"); +} + /// A dropped Pen press drops only the anchor it was placing: the path being drawn goes on with /// the next click. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 5f36c5a98e..9923a3a7a2 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -298,6 +298,10 @@ impl Session { let points = self.tool.options().get("meshPoints").cloned().unwrap_or_else(|| Value::Array(vec![])); lent.set_option("meshPoints", &points); } + // The Cmd/Ctrl held for the loan is not the Cmd/Ctrl that mirrors a dragged handle (#7842). + if id == "directSelection" { + lent.set_option("lentByCmd", &Value::Bool(true)); + } self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone())); self.lender = Some(std::mem::replace(&mut self.tool, lent)); Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled)) @@ -611,13 +615,18 @@ impl Session { /// Escape, as during a drag, for most tools), and a release returns the tool to rest. Of what /// the tool asks for along the way, only a cancel and a notify run, so a marquee selects /// nothing and a click opens no size dialog. The tool gets back the persistent options it had - /// when the press began, and none of the press's changes to them are stored. A dropped Type - /// press restores the prior selection. The freeform gradient point selected once the tool - /// took the press is selected again. A press held while the tool computes an edit on another - /// thread has not reached the tool: it is removed from the held input with the pointer events - /// and tool keys held after it, and the tool is left as it is. A perspective plane key held - /// after it stays held, since the plane it picks outlasts a dropped press. Pointer events held - /// after the last held release belong to the press the tool has, and are removed with it. + /// when the press began, and none of the press's changes to them are stored. An option set + /// during the press with [`Self::set_tool_option`] or [`Self::set_tool_options`], or a General › + /// Corner Radius change during a Rounded Rectangle press, keeps its new value, also when the + /// tool lent a selection tool for the press (a Cmd-drag). Setting an option stores all of the + /// tool's options, the press's changes included, so the dropped press then stores the options + /// it puts back. A dropped Type press restores the prior selection. The freeform gradient + /// point selected once the tool took the press is selected again. A press held while the tool + /// computes an edit on another thread has not reached the tool: it is removed from the held + /// input with the pointer events and tool keys held after it, and the tool is left as it is. + /// A perspective plane key held after it stays held, since the plane it picks outlasts a + /// dropped press. Pointer events held after the last held release belong to the press the tool + /// has, and are removed with it. pub fn drop_tool_press(&mut self, view: ViewInfo) -> Result<()> { let (from, held) = self.held_press(); let keep: Vec = (self.held_input.iter().enumerate()) @@ -635,6 +644,7 @@ impl Session { // Nothing to roll back without a document; the tool still drops the press and gets the release. let _ = self.cancel_interaction(); let before = self.press_options.take(); + let stored = std::mem::take(&mut self.press_options_stored); let type_selection = self.press_type_selection.take(); let point = self.press_point.take(); let mut acts = self.with_tool_cx(view, |t, cx| t.drop_press(cx)); @@ -669,6 +679,11 @@ impl Session { self.tool.set_option(k, v); } } + // An option set during the press stored every option the tool had then, the press's + // changes included: those stored values are put back too. + if stored { + self.keep_tool_settings(); + } } r.map(drop) } @@ -706,6 +721,7 @@ impl Session { match ev.kind { PointerKind::Down => { self.press_options = Some((self.tool.id().to_string(), Self::persistent_options(self.tool.as_ref()))); + self.press_options_stored = false; self.press_type_selection = if matches!(self.tool.id(), "type" | "areaType" | "typeOnPath" | "verticalType" | "verticalAreaType" | "verticalTypeOnPath") { self.active().map(|st| (st.selection.clone(), st.active_layer)) @@ -715,6 +731,7 @@ impl Session { } PointerKind::Up => { self.press_options = None; + self.press_options_stored = false; self.press_type_selection = None; } _ => {} @@ -1309,9 +1326,12 @@ impl Session { if key == "queue" && self.tool.id() == "place" { self.note_place_queue_roots(); } + let before_press = self.options_before_press_set(); + let sets_pressed = self.press_taken_by(self.tool.id()); self.tool.set_option(key, v); self.tool_set_since_reset = true; self.keep_tool_settings(); + self.keep_press_set(before_press, |k| sets_pressed && k == key, sets_pressed); } /// Keep the automation roots in force now as those the place cursor's queue, being loaded, @@ -1356,6 +1376,8 @@ impl Session { self.note_place_queue_roots(); } let active = id.is_none_or(|id| id == self.tool.id()); + let before_press = self.options_before_press_set(); + let sets_pressed = self.press_taken_by(id.unwrap_or(self.tool.id())); // The tool that lent a selection tool for a Cmd-drag is the tool chosen, and active again // when the drag ends. let lender = id.is_some_and(|id| self.lender.as_deref().is_some_and(|l| l.id() == id)); @@ -1393,9 +1415,46 @@ impl Session { let set = other.id(); Self::restore_stores(&self.prefs, self.tool.as_mut(), |store| settings::stores(set).any(|(s, _)| s == store)); } + self.keep_press_set(before_press, |k| sets_pressed && values.contains_key(k), sets_pressed); out } + /// The tool that took the press under way: the active tool, or the tool that lent a selection + /// tool for it (a Cmd-drag), which the dropped press gives its options back to. + fn pressed_tool(&self) -> Option<&dyn Tool> { + let (pressed, _) = self.press_options.as_ref()?; + std::iter::once(&self.tool).chain(self.lender.as_ref()).map(|t| t.as_ref()).find(|t| t.id() == pressed) + } + + /// Tool `id` took the press under way ([`Self::pressed_tool`]). + pub(crate) fn press_taken_by(&self, id: &str) -> bool { + self.pressed_tool().is_some_and(|t| t.id() == id) + } + + /// The persistent options of the tool that took the press under way ([`Self::pressed_tool`]) + /// before an option is set: a dropped press puts back the options it began with, except those + /// the set changes ([`Self::keep_press_set`]). + fn options_before_press_set(&self) -> Option> { + self.pressed_tool().map(Self::persistent_options) + } + + /// After an option is set during a held press, the press's saved options take the options of + /// the tool that took the press that the set changed from `before` or named (`named`), so a + /// dropped press keeps them. `stored`: the set stored that tool's options, the press's changes + /// included, so a dropped press stores the options it puts back. + fn keep_press_set(&mut self, before: Option>, named: impl Fn(&str) -> bool, stored: bool) { + let Some(before) = before else { return }; + let Some(now) = self.pressed_tool().map(Self::persistent_options) else { return }; + self.press_options_stored |= stored; + if let Some((_, saved)) = self.press_options.as_mut() { + for (k, v) in now { + if before.get(&k) != Some(&v) || named(&k) { + saved.insert(k, v); + } + } + } + } + /// `tool.setOption {tool?, key?, value?, values?}` (a command of the desktop app and of the /// headless host): set one option (`key`, `value`) or several (`values`) of `tool` (default: /// the tool active when the call arrives, named before the edit in progress is finished) → its diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index 7c0aef252e..c07d741265 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -6,7 +6,7 @@ use std::sync::{Mutex, MutexGuard}; use serde_json::json; -use vectorcraft_color::cms; +use vectorcraft_color::{Color, cms}; use vectorcraft_engine::Session; use vectorcraft_engine::cmd::colormgmt::{PROFILES_KEY, ProfileChoice, ProfileIssue, doc_profiles}; use vectorcraft_engine::store::MAX_PRESET_FILE; @@ -20,6 +20,22 @@ fn settings() -> MutexGuard<'static, ()> { SETTINGS.lock().unwrap_or_else(|e| e.into_inner()) } +/// The working Color Settings as a test found them, put back when it ends (a failing one too) +/// before the next test takes its turn. +struct Restored(cms::ColorSettings, #[allow(dead_code)] MutexGuard<'static, ()>); + +impl Drop for Restored { + fn drop(&mut self) { + let _ = cms::set_active(&self.0); + } +} + +/// [`settings`], with the working Color Settings put back afterwards. +fn restored_settings() -> Restored { + let g = settings(); + Restored(cms::working_settings(), g) +} + #[test] fn color_settings_lists_profiles_and_validates() { let _g = settings(); @@ -923,6 +939,114 @@ fn saved_color_settings_that_cannot_be_used_leave_the_defaults() { } } +/// View › Proof Setup › Customize's Preserve CMYK Numbers proofs each color from its own inks: +/// with Device CMYK as the working space, C50 M50 Y50 and K50 show as the same gray, and on +/// VectorCraft Generic CMYK they print, and so proof, as different grays; a pattern's tile art +/// proofs the same way. Without it the proof starts from the drawn pixels, which are the same. +#[test] +fn preserve_cmyk_numbers_proofs_each_color_from_its_inks() { + let _g = restored_settings(); + let mut s = session(); + s.execute("edit.colorSettings", &json!({"cmyk": cms::DEVICE_CMYK})).unwrap(); + let k50 = json!({"c": 0, "m": 0, "y": 0, "k": 50}); + let cmy = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + exec(&mut s, "paint.setFill", json!({"ids": [cmy.0], "color": {"c": 50, "m": 50, "y": 50, "k": 0}})); + let k = rect(&mut s, 100.0, 0.0, 100.0, 100.0); + exec(&mut s, "paint.setFill", json!({"ids": [k.0], "color": k50})); + // A pattern whose tile is all K50, filling a band below the squares. + let tile = rect(&mut s, 300.0, 0.0, 10.0, 10.0); + exec(&mut s, "paint.setFill", json!({"ids": [tile.0], "color": k50})); + exec(&mut s, "object.pattern.make", json!({"ids": [tile.0], "name": "K50 Tile", "edit": false})); + let band = rect(&mut s, 0.0, 130.0, 200.0, 40.0); + exec(&mut s, "paint.setFill", json!({"ids": [band.0], "swatch": "K50 Tile"})); + let proof = |preserve_numbers| vectorcraft_render::proof::ProofSetup { + target: vectorcraft_render::proof::ProofTarget::Cmyk(cms::GENERIC_CMYK.into()), + preserve_numbers, + ..Default::default() + }; + let doc = s.doc().unwrap().doc.clone(); + let pixel = |px: &[u8], x: usize, y: usize| [px[(y * 200 + x) * 4], px[(y * 200 + x) * 4 + 1], px[(y * 200 + x) * 4 + 2]]; + // The pixels at the centers of the two squares and in the patterned band. + let shown = |proof: Option| { + let opts = RenderOptions { proof, background: Some([255, 255, 255, 255]), ..Default::default() }; + let px = Renderer::new().render(&doc, 200, 200, Affine::IDENTITY, &opts).pixels; + (pixel(&px, 50, 50), pixel(&px, 150, 50), pixel(&px, 55, 155)) + }; + let (a, b, _) = shown(None); + let (pa, pb, _) = shown(Some(proof(false))); + let (ca, cb, cp) = shown(Some(proof(true))); + let want = |c: Color| cms::active().proof_color(&c, &proof(true)).map(|v| (v * 255.0).round() as i32); + let cmy_want = want(Color::cmyk(0.5, 0.5, 0.5, 0.0)); + let k_want = want(Color::cmyk(0.0, 0.0, 0.0, 0.5)); + // With Simulate Paper Color the art sits on the device's paper, not on white. + let paper = vectorcraft_render::proof::ProofSetup { simulate_paper: true, ..proof(true) }; + let tint = cms::active().proof_srgb([1.0; 3], &paper).map(|v| (v * 255.0).round() as i32); + let opts = RenderOptions { proof: Some(paper), background: Some([255, 255, 255, 255]), ..Default::default() }; + let bare = pixel(&Renderer::new().render(&doc, 200, 200, Affine::IDENTITY, &opts).pixels, 50, 115); + assert_eq!(a, b, "the two builds show as one gray in Device CMYK"); + assert_eq!(pa, pb, "proofed from the pixels, they stay one gray"); + assert!(ca != cb, "proofed from their inks, they print differently: {ca:?} vs {cb:?}"); + let near = |got: [u8; 3], want: [i32; 3]| got.iter().zip(want).all(|(g, w)| (i32::from(*g) - w).abs() <= 2); + assert!(near(ca, cmy_want) && near(cb, k_want), "{ca:?} {cmy_want:?}, {cb:?} {k_want:?}"); + assert!(near(cp, k_want), "the pattern's tile proofs from its inks: {cp:?} vs {k_want:?}"); + assert!(tint != [255; 3] && near(bare, tint), "the bare page shows the paper: {bare:?} vs {tint:?}"); +} + +/// With Preserve CMYK Numbers, an image in an opacity mask keeps its pixels as they are, so the +/// mask covers the same in a pattern's tile as outside one. +#[test] +fn preserve_cmyk_numbers_leaves_mask_images_in_pattern_tiles_as_they_are() { + let _g = restored_settings(); + let mut s = session(); + // A K100 square masked by a blue image, the same at (0, 0) and as a pattern's tile. + let masked = |s: &mut Session, x: f64| { + let obj = rect(s, x, 0.0, 20.0, 20.0); + exec(s, "paint.setFill", json!({"ids": [obj.0], "color": {"c": 0, "m": 0, "y": 0, "k": 100}})); + let blue = rect(s, x, 0.0, 20.0, 20.0); + exec(s, "paint.setFill", json!({"ids": [blue.0], "color": "#0000ff"})); + select(s, &[blue]); + exec(s, "object.rasterize", json!({"ppi": 72})); + let image = s.doc().unwrap().selection.objects[0]; + select(s, &[obj, image]); + exec(s, "transparency.makeOpacityMask", json!({"clip": true})); + obj + }; + masked(&mut s, 0.0); + let tile = masked(&mut s, 300.0); + exec(&mut s, "object.pattern.make", json!({"ids": [tile.0], "name": "Masked Tile", "edit": false})); + let band = rect(&mut s, 0.0, 100.0, 200.0, 40.0); + exec(&mut s, "paint.setFill", json!({"ids": [band.0], "swatch": "Masked Tile"})); + // An unmasked K100 square, for the color the masked one covers the page with. + let solid = rect(&mut s, 100.0, 0.0, 20.0, 20.0); + exec(&mut s, "paint.setFill", json!({"ids": [solid.0], "color": {"c": 0, "m": 0, "y": 0, "k": 100}})); + let proof = vectorcraft_render::proof::ProofSetup { + target: vectorcraft_render::proof::ProofTarget::Cmyk(cms::GENERIC_CMYK.into()), + preserve_numbers: true, + ..Default::default() + }; + let doc = s.doc().unwrap().doc.clone(); + let pixel = |px: &[u8], x: usize, y: usize| [px[(y * 200 + x) * 4], px[(y * 200 + x) * 4 + 1], px[(y * 200 + x) * 4 + 2]]; + // The masked square, the middle of a tile (the tiles start at the art's left and top edges, + // every 20 points), the unmasked square and the bare page. + let shown = |proof: Option| { + let opts = RenderOptions { proof, background: Some([255, 255, 255, 255]), ..Default::default() }; + let px = Renderer::new().render(&doc, 200, 200, Affine::IDENTITY, &opts).pixels; + (pixel(&px, 10, 10), pixel(&px, 50, 130), pixel(&px, 110, 10), pixel(&px, 190, 60)) + }; + let (plain, plain_tile, plain_k, plain_page) = shown(None); + let (proofed, proofed_tile, proofed_k, proofed_page) = shown(Some(proof)); + let near = |a: [u8; 3], b: [u8; 3]| a.iter().zip(b).all(|(a, b)| (i32::from(*a) - i32::from(b)).abs() <= 2); + assert!(plain != [255; 3] && near(plain, plain_tile), "the tile shows the masked square: {plain:?} vs {plain_tile:?}"); + assert!(near(proofed, proofed_tile), "the tile's mask covers as the square's does: {proofed:?} vs {proofed_tile:?}"); + // The proof changes the ink's color but not how much of the page the mask lets it cover. + let channel = |v: [u8; 3], i: usize| f32::from(v[i]); + let cover = (0..3).map(|i| (channel(plain_page, i) - channel(plain, i)) / (channel(plain_page, i) - channel(plain_k, i))).sum::() / 3.0; + assert!(cover > 0.02 && cover < 0.98, "the mask covers part of the square: {cover}"); + let want: [u8; 3] = + std::array::from_fn(|i| (channel(proofed_page, i) + cover * (channel(proofed_k, i) - channel(proofed_page, i))).round() as u8); + assert!(near(proofed, want), "the proofed square keeps the mask's coverage: {proofed:?} vs {want:?}"); +} + /// Edit › Color Settings' color management policies decide what opening a document tagged with /// profiles other than the working spaces does with them: Preserve Embedded Profiles keeps them, /// Off and Preserve Numbers take them off and keep the color numbers, and Convert to Working Space diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index b8114f705c..1413bb17bb 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1278,6 +1278,39 @@ fn polygon_properties_junk() { assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n")); } +/// A live rectangle's and ellipse's Rectangle and Ellipse Angle with junk values, drawn plain, +/// scaled unevenly, flattened to nothing and sheared: never a panic, and the document stays sound. +#[test] +fn rectangle_and_ellipse_angle_junk() { + let mut failures = vec![]; + for (shape, key) in [("shape.rectangle", "rectangleAngle"), ("shape.ellipse", "ellipseAngle")] { + for xf in [ + None, + Some(("object.scale", json!({"sx": 300, "sy": 20}))), + Some(("object.scale", json!({"sx": 1e-300, "sy": 100}))), + Some(("object.shear", json!({"angle": 40}))), + ] { + for v in junk_values() { + let p = json!({ key: v }); + let mut s = Fixture::Multi.session(); + let Ok(_) = no_panic(s.execute(shape, &json!({"x": 60, "y": 60, "width": 80, "height": 50}))) else { continue }; + if let Some((cmd, q)) = &xf { + let _ = no_panic(s.execute(cmd, q)); + } + match catch_quiet(|| no_panic(s.execute("object.setLiveShape", &p))) { + Err(m) => failures.push(format!("PANIC object.setLiveShape {p} [{xf:?}]: {m}")), + Ok(_) => { + if let Err(e) = catch_quiet(|| check_all(&mut s)).unwrap_or_else(|m| Err(format!("panic in checks: {m}"))) { + failures.push(format!("object.setLiveShape {p} [{xf:?}]: {e}")); + } + } + } + } + } + } + assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n")); +} + /// A live line's Line Properties with junk values (the fixtures have no line), on a line, a line /// whose ends meet and one at the coordinate limit: never a panic, and the document stays sound. #[test] diff --git a/crates/engine/tests/direct_handle_mirror.rs b/crates/engine/tests/direct_handle_mirror.rs new file mode 100644 index 0000000000..30326d8e74 --- /dev/null +++ b/crates/engine/tests/direct_handle_mirror.rs @@ -0,0 +1,630 @@ +//! Temporary Cmd/Control symmetry while Direct Selection drags an existing handle. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeId}; +use vectorcraft_engine::{Session, ViewInfo}; +use vectorcraft_geom::{Anchor, AnchorKind, Point}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + +fn run(s: &mut Session, command: &str, params: Value) -> Value { + s.execute(command, ¶ms).unwrap() +} + +fn view() -> ViewInfo { + ViewInfo { + smart_guides: false, + guides: false, + snap_to_point: false, + snap_to_grid: false, + snap_to_pixel: false, + snap_to_glyph: false, + corner_widgets: false, + show_bbox: false, + ..ViewInfo::default() + } +} + +fn session() -> Session { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 900, "height": 700})); + for (key, value) in [("constrainAngle", json!(0)), ("showHandlesMultipleAnchors", json!(true)), ("realTimeDrawing", json!(true))] { + run(&mut s, "prefs.set", json!({"key": key, "value": value})); + } + s +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).unwrap().clone() +} + +fn curve(s: &mut Session, incoming: Point) -> NodeId { + let id = run( + s, + "path.create", + json!({"anchors": [ + {"x": 20, "y": 220}, + {"x": 100, "y": 100, "in": [incoming.x, incoming.y], "out": [180, 100]}, + {"x": 320, "y": 220} + ]}), + ); + let id = NodeId(id["id"].as_u64().unwrap()); + s.select_tool("directSelection", view()).unwrap(); + id +} + +fn anchor(s: &Session, id: NodeId) -> Anchor { + node(s, id).path_data().unwrap().subpaths[0].anchors[1] +} + +fn pointer(s: &mut Session, kind: PointerKind, at: Point, mods: Mods) { + s.pointer(&PointerEvent::new(kind, at.x, at.y).with_mods(mods), view()).unwrap(); +} + +fn press_handle(s: &mut Session, at: Point) { + pointer(s, PointerKind::Down, at, Mods::default()); + assert_eq!(s.tool_id(), "directSelection"); + assert!(s.in_interaction(), "the visible handle press begins Reshape"); +} + +fn near(actual: Point, expected: Point) { + assert!(actual.distance(expected) < 1e-6, "point {actual:?}, expected {expected:?}"); +} + +fn handles(a: Anchor, incoming: Point, outgoing: Point, kind: AnchorKind) { + near(a.h_in, incoming); + near(a.h_out, outgoing); + assert_eq!(a.kind, kind); +} + +fn assert_other_geometry(s: &Session, id: NodeId, before: &Node) { + let after = node(s, id); + let (old, new) = (before.path_data().unwrap(), after.path_data().unwrap()); + assert_eq!(new.subpaths.len(), old.subpaths.len()); + assert_eq!(new.subpaths[0].closed, old.subpaths[0].closed); + assert_eq!(new.subpaths[0].anchors.len(), 3); + assert_eq!(new.subpaths[0].anchors[0], old.subpaths[0].anchors[0]); + assert_eq!(new.subpaths[0].anchors[2], old.subpaths[0].anchors[2]); + assert_eq!(new.subpaths[0].anchors[1].p, old.subpaths[0].anchors[1].p); + assert_eq!(after.appearance, before.appearance); +} + +#[test] +fn direct_handle_baseline_ordinary_smooth_keeps_the_opposite_length() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = node(&s, id); + assert_eq!(anchor(&s, id).kind, AnchorKind::Smooth); + let selection = json!(s.doc().unwrap().selection); + let undo = s.doc().unwrap().history.undo.len(); + press_handle(&mut s, Point::new(180.0, 100.0)); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth); + assert_other_geometry(&s, id, &before); + pointer(&mut s, PointerKind::Up, q, Mods::default()); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(json!(s.doc().unwrap().selection), selection); +} + +#[test] +fn direct_handle_baseline_cmd_added_mid_drag_mirrors_the_opposite() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = node(&s, id); + press_handle(&mut s, Point::new(180.0, 100.0)); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, q, Mods { cmd: true, ..Mods::default() }); + handles(anchor(&s, id), Point::new(20.0, 40.0), q, AnchorKind::Smooth); + assert_other_geometry(&s, id, &before); + pointer(&mut s, PointerKind::Up, q, Mods { cmd: true, ..Mods::default() }); +} + +#[test] +fn direct_handle_cmd_mirror_holds_through_a_space_translation() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + press_handle(&mut s, Point::new(180.0, 100.0)); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + handles(anchor(&s, id), Point::new(20.0, 40.0), q, AnchorKind::Smooth); + // Space moves the anchor and both handles; the opposite handle stays mirrored. + let moved = Point::new(200.0, 190.0); + pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, ..cmd() }); + let a = anchor(&s, id); + near(a.p, Point::new(120.0, 130.0)); + handles(a, Point::new(40.0, 70.0), Point::new(200.0, 190.0), AnchorKind::Smooth); + // Releasing Space without moving keeps the translated, mirrored handles. + pointer(&mut s, PointerKind::Drag, moved, cmd()); + handles(anchor(&s, id), Point::new(40.0, 70.0), Point::new(200.0, 190.0), AnchorKind::Smooth); + let next = Point::new(220.0, 190.0); + pointer(&mut s, PointerKind::Drag, next, cmd()); + assert_mirrored(anchor(&s, id), next, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Up, next, cmd()); +} + +#[test] +fn direct_handle_modifiers_changed_during_a_space_translation_apply_at_once() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + press_handle(&mut s, Point::new(180.0, 100.0)); + pointer(&mut s, PointerKind::Drag, Point::new(180.0, 160.0), cmd()); + let moved = Point::new(200.0, 190.0); + pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, ..cmd() }); + handles(anchor(&s, id), Point::new(40.0, 70.0), moved, AnchorKind::Smooth); + // Releasing Cmd while Space is held gives the opposite handle its own length again. + pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, ..Mods::default() }); + let a = anchor(&s, id); + near(a.p, Point::new(120.0, 130.0)); + handles(a, Point::new(80.0, 100.0), moved, AnchorKind::Smooth); + // Alt while Space is held leaves the opposite handle where the translation put it. + pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, alt: true, ..cmd() }); + handles(anchor(&s, id), Point::new(70.0, 130.0), moved, AnchorKind::Corner); + pointer(&mut s, PointerKind::Up, moved, Mods { alt: true, ..cmd() }); +} + +#[derive(Debug, PartialEq)] +struct Snapshot { + document: Value, + selection: Value, + undo: usize, + redo: usize, +} + +fn snapshot(s: &Session) -> Snapshot { + let st = s.doc().unwrap(); + Snapshot { document: json!(st.doc), selection: json!(st.selection), undo: st.history.undo.len(), redo: st.history.redo.len() } +} + +fn assert_content(s: &Session, expected: &Snapshot) { + let got = snapshot(s); + assert_eq!(got.document, expected.document); + assert_eq!(got.selection, expected.selection); +} + +fn cmd() -> Mods { + Mods { cmd: true, ..Mods::default() } +} + +fn reflected(a: Point, q: Point) -> Point { + a - (q - a) +} + +fn constrained(a: Point, q: Point) -> Point { + a + vectorcraft_geom::constrain_angle_from(q - a, 45.0, 0.0) +} + +fn assert_mirrored(a: Anchor, q: Point, kind: AnchorKind) { + handles(a, reflected(a.p, q), q, kind); +} + +#[test] +fn direct_handle_stationary_cmd_release_repress_commit_and_next_gesture() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = snapshot(&s); + press_handle(&mut s, Point::new(180.0, 100.0)); + let q = Point::new(180.0, 160.0); + for (mods, opposite) in [(cmd(), Point::new(20.0, 40.0)), (Mods::default(), Point::new(60.0, 70.0)), (cmd(), Point::new(20.0, 40.0))] { + pointer(&mut s, PointerKind::Drag, q, mods); + handles(anchor(&s, id), opposite, q, AnchorKind::Smooth); + assert_eq!(s.doc().unwrap().history.undo.len(), before.undo, "previews are not separate edits"); + } + pointer(&mut s, PointerKind::Up, q, cmd()); + let committed = snapshot(&s); + assert_eq!(committed.undo, before.undo + 1); + assert_eq!(committed.selection, before.selection); + run(&mut s, "edit.undo", json!({})); + assert_content(&s, &before); + run(&mut s, "edit.redo", json!({})); + assert_content(&s, &committed); + // Cmd did not install a persistent coupling mode: a later ordinary Smooth drag keeps + // the opposite handle's committed length, rather than matching the newly dragged length. + press_handle(&mut s, q); + let next = Point::new(180.0, 200.0); + pointer(&mut s, PointerKind::Drag, next, Mods::default()); + let a = anchor(&s, id); + near(a.h_out, next); + assert_eq!(a.kind, AnchorKind::Smooth); + assert!((a.h_in.distance(a.p) - 100.0).abs() < 1e-6); + assert!((a.h_in.distance(a.p) - a.h_out.distance(a.p)).abs() > 20.0); + assert!(((a.h_in - a.p).cross(a.h_out - a.p)).abs() < 1e-6); + pointer(&mut s, PointerKind::Up, next, Mods::default()); + assert_eq!(s.doc().unwrap().history.undo.len(), before.undo + 2); +} + +#[test] +fn direct_handle_shift_constrains_before_mirroring_and_alt_takes_priority() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let p = anchor(&s, id).p; + press_handle(&mut s, Point::new(180.0, 100.0)); + let raw = Point::new(180.0, 150.0); + let q = constrained(p, raw); + let shifted = Mods { shift: true, ..cmd() }; + pointer(&mut s, PointerKind::Drag, raw, shifted); + assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, raw, Mods { alt: true, ..shifted }); + handles(anchor(&s, id), Point::new(50.0, 100.0), q, AnchorKind::Corner); + // Removing Alt rebuilds from the original Smooth anchor, not the Corner preview. + pointer(&mut s, PointerKind::Drag, raw, shifted); + assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, raw, Mods { alt: true, ..cmd() }); + handles(anchor(&s, id), Point::new(50.0, 100.0), raw, AnchorKind::Corner); + pointer(&mut s, PointerKind::Up, raw, Mods { alt: true, ..cmd() }); +} + +#[test] +fn direct_handle_corner_with_collapsed_partner_is_reversible_without_changing_kind() { + let mut s = session(); + let id = curve(&mut s, Point::new(100.0, 100.0)); + let before = snapshot(&s); + assert_eq!(anchor(&s, id).kind, AnchorKind::Corner); + press_handle(&mut s, Point::new(180.0, 100.0)); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(anchor(&s, id), q, AnchorKind::Corner); + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + handles(anchor(&s, id), Point::new(100.0, 100.0), q, AnchorKind::Corner); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(anchor(&s, id), q, AnchorKind::Corner); + s.tool_key(vectorcraft_tools::ToolKey::Escape, Mods::default(), view()).unwrap(); + assert_eq!(snapshot(&s), before); +} + +#[test] +fn direct_handle_stationary_drag_still_mirrors_unequal_partner_but_equal_is_noop() { + for (incoming, changes) in [(Point::new(50.0, 100.0), true), (Point::new(20.0, 100.0), false)] { + let mut s = session(); + let id = curve(&mut s, incoming); + let before = snapshot(&s); + let q = Point::new(180.0, 100.0); + press_handle(&mut s, q); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Up, q, cmd()); + if changes { + assert_eq!(s.doc().unwrap().history.undo.len(), before.undo + 1); + run(&mut s, "edit.undo", json!({})); + assert_content(&s, &before); + } else { + assert_eq!(snapshot(&s), before, "an already reflected pair records no edit"); + } + } +} + +#[test] +fn direct_handle_escape_restores_document_selection_and_existing_redo() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + run(&mut s, "shape.rectangle", json!({"x": 500, "y": 400, "width": 25, "height": 30})); + let redo_document = snapshot(&s).document; + run(&mut s, "edit.undo", json!({})); + run(&mut s, "select.set", json!({"ids": [id.0]})); + let before = snapshot(&s); + assert_eq!(before.redo, 1, "a real existing Redo is the cancellation control"); + press_handle(&mut s, Point::new(180.0, 100.0)); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth); + s.tool_key(vectorcraft_tools::ToolKey::Escape, Mods::default(), view()).unwrap(); + assert!(!s.in_interaction()); + assert_eq!(snapshot(&s), before); + pointer(&mut s, PointerKind::Up, q, Mods::default()); + assert_eq!(snapshot(&s), before, "a later release does not commit the canceled preview"); + run(&mut s, "edit.redo", json!({})); + assert_eq!(snapshot(&s).document, redo_document, "the prior Redo still restores its actual content"); +} + +#[test] +fn direct_handle_cmd_before_press_still_lends_selection_and_returns_direct() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = snapshot(&s); + let a = anchor(&s, id); + pointer(&mut s, PointerKind::Down, a.p, cmd()); + assert_eq!(s.tool_id(), "selection", "Cmd before Down keeps the existing Selection loan"); + pointer(&mut s, PointerKind::Up, a.p, cmd()); + assert_eq!(s.tool_id(), "directSelection"); + assert_eq!(anchor(&s, id), a); + assert_eq!(snapshot(&s).document, before.document); + assert_eq!(s.doc().unwrap().history.undo.len(), before.undo); +} + +#[test] +fn direct_handle_cmd_that_lends_direct_selection_from_the_pen_does_not_mirror() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + s.select_tool("pen", view()).unwrap(); + let before = node(&s, id); + let undo = s.doc().unwrap().history.undo.len(); + pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd()); + assert_eq!(s.tool_id(), "directSelection", "Cmd lends the Pen the last selection tool"); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth); + // Cmd let go and pressed again during the drag mirrors, as it does in Direct Selection itself. + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, q, cmd()); + handles(anchor(&s, id), Point::new(20.0, 40.0), q, AnchorKind::Smooth); + assert_other_geometry(&s, id, &before); + pointer(&mut s, PointerKind::Up, q, cmd()); + assert_eq!(s.tool_id(), "pen"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); +} + +#[test] +fn direct_handle_cmd_held_through_a_pen_lent_drag_leaves_the_opposite_length() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + s.select_tool("pen", view()).unwrap(); + pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd()); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + pointer(&mut s, PointerKind::Up, q, cmd()); + assert_eq!(s.tool_id(), "pen"); + handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth); +} + +fn text_anchor(s: &Session, id: NodeId) -> Anchor { + let n = node(s, id); + let vectorcraft_doc::NodeKind::Text(t) = n.kind else { panic!("text on a path") }; + t.type_path().unwrap().subpaths[0].anchors[1] +} + +fn text_properties(s: &Session, id: NodeId) -> Value { + let n = node(s, id); + let vectorcraft_doc::NodeKind::Text(t) = n.kind else { panic!("text on a path") }; + let vectorcraft_doc::TextKind::OnPath { start, end, .. } = &t.kind else { panic!("path text") }; + json!({"runs": t.runs, "para": t.para, "paras": t.paras, "xf": t.xf, "start": start, "end": end, + "effect": t.path_effect, "align": t.path_align, "spacing": t.path_spacing, "appearance": n.appearance}) +} + +fn path_text(s: &mut Session) -> NodeId { + let path = curve(s, Point::new(50.0, 100.0)); + let made = run( + s, + "text.createInPath", + json!({"path": path.0, "mode": "onPath", "text": "Along the original curve", "font": "Source Sans 3", "size": 12}), + ); + let id = NodeId(made["id"].as_u64().unwrap()); + run(s, "type.pathOptions", json!({"id": id.0, "start": 0.15, "end": 0.85})); + run(s, "object.transform", json!({"ids": [id.0], "matrix": [1.5, 0.4, 0.25, 0.9, 250, 80]})); + s.select_tool("directSelection", view()).unwrap(); + id +} + +#[test] +fn direct_handle_affine_path_text_mirrors_in_drawn_space_and_keeps_brackets() { + let mut s = session(); + let id = path_text(&mut s); + let before = snapshot(&s); + let properties = text_properties(&s, id); + assert_eq!(properties["start"], json!(0.15)); + assert_eq!(properties["end"], json!(0.85)); + let a = text_anchor(&s, id); + assert_eq!(a.kind, AnchorKind::Smooth); + near(a.p, Point::new(425.0, 210.0)); + near(a.h_out, Point::new(545.0, 242.0)); + assert!((a.h_in.distance(a.p) - a.h_out.distance(a.p)).abs() > 40.0); + press_handle(&mut s, a.h_out); + let raw = a.p + vectorcraft_geom::Vec2::new(80.0, 60.0); + pointer(&mut s, PointerKind::Drag, raw, cmd()); + assert_mirrored(text_anchor(&s, id), raw, AnchorKind::Smooth); + assert_eq!(text_properties(&s, id), properties); + let shifted = Mods { shift: true, ..cmd() }; + pointer(&mut s, PointerKind::Drag, raw, shifted); + assert_mirrored(text_anchor(&s, id), constrained(a.p, raw), AnchorKind::Smooth); + assert_eq!(text_properties(&s, id), properties); + pointer(&mut s, PointerKind::Up, raw, shifted); + let after = snapshot(&s); + assert_eq!(after.undo, before.undo + 1); + run(&mut s, "edit.undo", json!({})); + assert_content(&s, &before); + run(&mut s, "edit.redo", json!({})); + assert_content(&s, &after); +} + +fn blend_state(s: &Session, id: NodeId) -> (Anchor, Value, Vec) { + let n = node(s, id); + let vectorcraft_doc::NodeKind::Blend { children, spec } = n.kind else { panic!("blend") }; + assert!(spec.spine.is_some(), "the fixture uses an already pinned spine"); + let path = vectorcraft_doc::live::blend_spine(&children, &spec).unwrap().0; + (path.subpaths[0].anchors[1], json!(children), spec.key_anchors.clone()) +} + +fn blend(s: &mut Session) -> NodeId { + let a = run(s, "shape.rectangle", json!({"x": 15, "y": 95, "width": 10, "height": 10}))["id"].as_u64().unwrap(); + let b = run(s, "shape.rectangle", json!({"x": 295, "y": 95, "width": 10, "height": 10}))["id"].as_u64().unwrap(); + let made = run(s, "object.blend.make", json!({"ids": [a, b], "steps": 2})); + let id = NodeId(made["id"].as_u64().unwrap()); + let added = run(s, "object.blend.spine.addAnchor", json!({"id": id.0, "x": 100, "y": 100})); + assert_eq!(added["anchor"], json!(1)); + run(s, "object.blend.spine.convertAnchor", json!({"id": id.0, "anchor": 1, "to": "smooth", "x": 180, "y": 100})); + run(s, "object.blend.spine.moveAnchor", json!({"id": id.0, "anchor": 1, "handle": "in", "x": 50, "y": 100})); + run(s, "select.set", json!({"ids": [id.0]})); + s.select_tool("directSelection", view()).unwrap(); + let (middle, _, keys) = blend_state(s, id); + near(middle.p, Point::new(100.0, 100.0)); + handles(middle, Point::new(50.0, 100.0), Point::new(180.0, 100.0), AnchorKind::Smooth); + assert_eq!(keys, [0, 2]); + // An actual spine-point click makes its handles visible to Direct Selection. + pointer(s, PointerKind::Down, middle.p, Mods::default()); + pointer(s, PointerKind::Up, middle.p, Mods::default()); + assert!(!s.in_interaction()); + id +} + +#[test] +fn direct_handle_pinned_blend_spine_cmd_shift_preserves_keys_and_mapping() { + let mut s = session(); + let id = blend(&mut s); + let before = snapshot(&s); + let (a, keys, mapping) = blend_state(&s, id); + press_handle(&mut s, a.h_out); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(blend_state(&s, id).0, q, AnchorKind::Smooth); + let raw = Point::new(180.0, 150.0); + let shifted = Mods { shift: true, ..cmd() }; + pointer(&mut s, PointerKind::Drag, raw, shifted); + assert_mirrored(blend_state(&s, id).0, constrained(a.p, raw), AnchorKind::Smooth); + // The existing spine Shift-only path is deliberately unconstrained; Cmd's new rule + // must not leak into that old branch after the modifier is released. + pointer(&mut s, PointerKind::Drag, raw, Mods { shift: true, ..Mods::default() }); + near(blend_state(&s, id).0.h_out, raw); + pointer(&mut s, PointerKind::Drag, raw, shifted); + let (after_anchor, after_keys, after_mapping) = blend_state(&s, id); + assert_mirrored(after_anchor, constrained(a.p, raw), AnchorKind::Smooth); + assert_eq!(after_keys, keys, "handle edits leave the actual key art unchanged"); + assert_eq!(after_mapping, mapping); + pointer(&mut s, PointerKind::Up, raw, shifted); + let after = snapshot(&s); + assert_eq!(after.undo, before.undo + 1); + assert_eq!(after.selection, before.selection); + run(&mut s, "edit.undo", json!({})); + assert_content(&s, &before); + run(&mut s, "edit.redo", json!({})); + assert_content(&s, &after); +} + +#[test] +fn direct_handle_incoming_drag_mirrors_outgoing_and_release_restores_ordinary_length() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = snapshot(&s); + let original = node(&s, id); + press_handle(&mut s, Point::new(50.0, 100.0)); + let q = Point::new(40.0, 20.0); + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + handles(anchor(&s, id), q, Point::new(148.0, 164.0), AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, q, cmd()); + handles(anchor(&s, id), q, Point::new(160.0, 180.0), AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + handles(anchor(&s, id), q, Point::new(148.0, 164.0), AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_other_geometry(&s, id, &original); + pointer(&mut s, PointerKind::Up, q, cmd()); + handles(anchor(&s, id), q, Point::new(160.0, 180.0), AnchorKind::Smooth); + assert_eq!(s.doc().unwrap().history.undo.len(), before.undo + 1); + assert_eq!(snapshot(&s).selection, before.selection); + run(&mut s, "edit.undo", json!({})); + assert_content(&s, &before); +} + +/// `command` with `params` is refused with an error containing `message`, and the document, +/// selection and undo history stay as they were. +fn refused(s: &mut Session, command: &str, params: Value, message: &str) { + let before = snapshot(s); + let err = s.execute(command, ¶ms).unwrap_err().to_string(); + assert!(err.contains(message), "{command} {params}: {err}"); + assert_eq!(snapshot(s), before); +} + +#[test] +fn path_set_handle_symmetric_mirrors_refuses_bad_values_and_records_no_step_when_in_place() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let at = |x: f64, y: f64| json!({"id": id.0, "anchor": 1, "which": "out", "x": x, "y": y}); + for bad in [json!("yes"), json!(1)] { + let mut p = at(180.0, 160.0); + p["symmetric"] = bad; + refused(&mut s, "path.setHandle", p, "`symmetric` must be true or false"); + } + let mut both = at(180.0, 160.0); + both["symmetric"] = json!(true); + both["independent"] = json!(true); + refused(&mut s, "path.setHandle", both, "`independent` and `symmetric` cannot both be true"); + + let undo = s.doc().unwrap().history.undo.len(); + let mut mirror = at(180.0, 160.0); + mirror["symmetric"] = json!(true); + run(&mut s, "path.setHandle", mirror.clone()); + handles(anchor(&s, id), Point::new(20.0, 40.0), Point::new(180.0, 160.0), AnchorKind::Smooth); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let placed = snapshot(&s); + run(&mut s, "path.setHandle", mirror); + assert_eq!(snapshot(&s), placed, "both handles already in place record no undo step"); +} + +#[test] +fn symmetric_leaves_the_other_handle_retracted_at_an_open_end() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let first = |s: &Session| node(s, id).path_data().unwrap().subpaths[0].anchors[0]; + let p = first(&s).p; + run(&mut s, "path.setHandle", json!({"id": id.0, "anchor": 0, "which": "out", "x": 60, "y": 180, "symmetric": true})); + handles(first(&s), p, Point::new(60.0, 180.0), AnchorKind::Corner); + + let mut s = session(); + let blend_id = blend(&mut s); + let end = |s: &Session| { + let n = node(s, blend_id); + let vectorcraft_doc::NodeKind::Blend { children, spec } = n.kind else { panic!("blend") }; + vectorcraft_doc::live::blend_spine(&children, &spec).unwrap().0.subpaths[0].anchors[0] + }; + let start = end(&s); + run(&mut s, "object.blend.spine.moveAnchor", json!({"id": blend_id.0, "anchor": 0, "handle": "out", "x": 60, "y": 60, "symmetric": true})); + near(end(&s).h_out, Point::new(60.0, 60.0)); + near(end(&s).h_in, start.h_in); + near(end(&s).h_in, start.p); +} + +#[test] +fn spine_and_type_path_handles_refuse_bad_symmetric_values() { + let mut s = session(); + let id = blend(&mut s); + let spine = |extra: Value| { + let mut p = json!({"id": id.0, "anchor": 1, "handle": "out", "x": 180, "y": 160}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + p + }; + refused(&mut s, "object.blend.spine.moveAnchor", spine(json!({"symmetric": "yes"})), "`symmetric` must be true or false"); + refused( + &mut s, + "object.blend.spine.moveAnchor", + spine(json!({"symmetric": true, "independent": true})), + "`independent` and `symmetric` cannot both be true", + ); + refused( + &mut s, + "object.blend.spine.moveAnchor", + json!({"id": id.0, "anchor": 1, "x": 180, "y": 160, "symmetric": true}), + "`symmetric` places a handle", + ); + + let text = path_text(&mut s); + let a = text_anchor(&s, text); + let at = json!({"id": text.0, "anchor": 1, "which": "out", "x": a.h_out.x, "y": a.h_out.y + 20.0}); + let mut bad = at.clone(); + bad["symmetric"] = json!(0); + refused(&mut s, "text.setPathHandle", bad, "`symmetric` must be true or false"); + let mut both = at; + both["symmetric"] = json!(true); + both["independent"] = json!(true); + refused(&mut s, "text.setPathHandle", both, "`independent` and `symmetric` cannot both be true"); +} + +#[test] +fn direct_handle_cmd_that_lends_direct_selection_from_the_pen_does_not_mirror_type_on_a_path() { + let mut s = session(); + let id = path_text(&mut s); + let a = text_anchor(&s, id); + let length = a.h_in.distance(a.p); + s.select_tool("pen", view()).unwrap(); + pointer(&mut s, PointerKind::Down, a.h_out, cmd()); + assert_eq!(s.tool_id(), "directSelection"); + let q = a.p + vectorcraft_geom::Vec2::new(80.0, 60.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + let held = text_anchor(&s, id); + near(held.h_out, q); + assert!((held.h_in.distance(held.p) - length).abs() < 1e-6, "the other handle keeps its length"); + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(text_anchor(&s, id), q, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Up, q, cmd()); + assert_eq!(s.tool_id(), "pen"); +} diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs index 27ce315d92..b5c069c749 100644 --- a/crates/engine/tests/import_fuzz.rs +++ b/crates/engine/tests/import_fuzz.rs @@ -8465,3 +8465,51 @@ proptest! { prop_assert_eq!(paths, 2, "{:?}", notes); } } + +proptest! { + #![proptest_config(config())] + + /// A stroke's arrowheads (#8188): its arrowhead entries with any scale of any kind, naming a + /// symbol the file defines, one it doesn't or one named in Chinese, the symbol's art any run of + /// paths (frames, samples of the line, heads, open and closed, filled, stroked or neither), at + /// any weight, the style section cut anywhere, the line drawn as any look. Read as a `.ai` and + /// as an EPS, then rendered. + #[test] + fn ai_arrowhead_strokes_never_panic( + scale in prop_oneof![arb_num(), Just("50".to_string())], + kind in prop::sample::select(vec!["Real", "Int", "Bool"]), + named in prop::sample::select(vec!["W", "Missing", "\u{6954}"]), + both in any::(), + art in prop::collection::vec(prop::sample::select(vec![ + "-10 5 m\n10 5 L\n10 -5 L\n-10 -5 L\nn\n", + "0 G\n1 w\n-9 0 m\n4 0 l\nS\n", + "0 G\n0.5 w\n-9 0 m\n4 0 l\nS\n", + "0 g\n2 3 m\n8 0 l\n2 -3 l\nf\n", + "0 G\n1 w\n2 3 m\n8 0 l\n2 -3 l\nS\n", + "0 g\n1e300 0 m\n-1e300 1 l\nf\n", + "0 g\n0 0 m\n0 0 l\nf\n", + ]), 0..6), + width in arb_num(), + cut in 0usize..2000, + look in prop::sample::select(vec!["0 G\n2 w\n0 50 m\n96 50 l\nS\n0 g\n94 53 m\n100 50 l\n94 47 l\nf\n", "0 G\n2 w\n0 50 m\n100 50 l\nS\n", ""]), + ) { + use vectorcraft_testkit::ai; + let symbol = format!("%AI5_Begin_NonPrinting\n%AI14_BeginSymbol\n(W)\n0 A\n0 Xw\n0 Ae\nu\n{}U\n%AI10_EndSymbol\n%AI5_End_NonPrinting--\n", art.concat()); + let start = if both { format!("{scale} /{kind} (BSArrowBeginScale) ,\n/GObjRef : ({named}) /SymbolArt ; (BSArrowBeginSymbol) ,\n") } else { String::new() }; + let styles = format!( + "%AI9_BeginArtStyles\n/KnownStyle :\n(Arrowed) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/Dictionary : /NotRecorded ,\n\ + {start}{scale} /{kind} (BSArrowEndScale) ,\n/GObjRef : ({named}) /SymbolArt ; (BSArrowEndSymbol) ,\n; (kAIBeautifulStrokesParamsDictKey) ,\n\ + /StrokeStyle : 0 R\n0 0 0 1 0 0 0 XA\n0 J 0 j {width} w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n%AI9_EndArtStyles\n\ + %AI9_BeginArtStyleList\n(Arrowed)\n%AI9_EndArtStyleList\n" + ); + let styles: String = styles.chars().take(cut).collect(); + let line = format!("0 Ae\nu\n{look}U\n%_0 50 m\n%_100 50 L\n%_N\n1 (Arrowed) XW\n"); + let data = ai::editing_data(200.0, 100.0, &format!("{symbol}{styles}{}", ai::layer("L", &line))); + survive("arrowhead strokes", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?; + let eps = ai::eps(data.as_bytes(), ai::page_ps()); + survive("arrowhead strokes in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?; + } +} diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 28417f031a..30f3ce2665 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -118,6 +118,68 @@ fn each_arrow_style_draws_its_stroke_arrowhead_at_both_ends() { } } +/// `arrowHead` draws any built-in stroke arrowhead at both ends of the dimension line, and the +/// native file keeps it. The saved `arrowStyle` stays one of the four values versions without +/// `arrowHead` read, and a dimension saved without `arrowHead` draws its arrow style. Options +/// without a stroke head are saved without `arrowHead`. A custom arrowhead, an unknown name and an +/// overlong name are refused. +#[test] +fn every_stroke_arrowhead_draws_as_a_dimension_arrowhead() { + use vectorcraft_doc::{Arrowhead, dimension::ArrowStyle}; + let ends = |s: &Session, id: u64| -> Vec<_> { + let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap(); + let children = n.children().unwrap(); + let strokes = children.iter().filter_map(|n| n.appearance.stroke().map(|s| (s.start_arrow.clone(), s.end_arrow.clone()))); + strokes.filter(|(a, b)| a.is_some() || b.is_some()).collect() + }; + let mut s = session(); + let mut made = vec![]; + for head in Arrowhead::ALL { + let name = serde_json::to_value(&head).unwrap(); + let id = run(&mut s, "dimension.create", json!({"a":[0,0],"b":[72,0],"options":{"arrowHead":name}}))["id"].as_u64().unwrap(); + let drawn = ends(&s, id); + assert!(!drawn.is_empty() && drawn.iter().all(|h| *h == (Some(head.clone()), Some(head.clone()))), "{name}: {drawn:?}"); + let saved = serde_json::to_value(&recipe(&s, id).options).unwrap(); + assert_eq!((&saved["arrowStyle"], &saved["arrowHead"]), (&json!("filled"), &name)); + made.push((id, head)); + } + let bytes = vectorcraft_format::save(&s.doc().unwrap().doc, false); + let mut reopened = Session::new(); + reopened.add_document(vectorcraft_format::load(&bytes).unwrap(), None); + for (id, head) in made { + assert_eq!(recipe(&reopened, id).options.arrowhead(), Some(head)); + } + // A dimension saved before `arrowHead` existed. + let id = run(&mut s, "dimension.create", json!({"a":[0,0],"b":[72,0],"options":{"arrowStyle":"open"}}))["id"].as_u64().unwrap(); + let mut file: Value = serde_json::from_slice(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + fn drop_head(v: &mut Value) { + match v { + Value::Object(m) => { + m.remove("arrowHead"); + m.values_mut().for_each(drop_head); + } + Value::Array(a) => a.iter_mut().for_each(drop_head), + _ => {} + } + } + drop_head(&mut file); + let mut older = Session::new(); + older.add_document(vectorcraft_format::load(&serde_json::to_vec(&file).unwrap()).unwrap(), None); + let o = recipe(&older, id).options; + assert_eq!((o.arrow_style, o.arrow_head.clone(), o.arrowhead()), (ArrowStyle::Open, None, Some(Arrowhead::TriangleOpen))); + // Without a stroke head, the saved and recorded options carry no `arrowHead`, and a null one + // is still taken. + let saved = serde_json::to_value(&recipe(&s, id).options).unwrap(); + assert!(saved.get("arrowHead").is_none(), "{saved}"); + assert!(s.execute("dimension.create", &json!({"a":[0,0],"b":[72,0],"options":{"arrowHead":null}})).is_ok()); + let custom = json!({"Custom":{"name":"Dot","path":{"subpaths":[]}}}); + for bad in [json!("Custom"), json!("Arrowhead"), json!("barbed"), json!(3), json!("Barbed".repeat(20)), custom] { + let p = json!({"a":[0,0],"b":[72,0],"options":{"arrowHead":bad}}); + assert!(s.execute("dimension.create", &p).is_err(), "{bad}"); + } + assert!(s.execute("dimension.create", &json!({"a":[0,0],"b":[72,0],"options":{"arrowStyle":"Barbed"}})).is_err()); +} + #[test] fn dimension_angles_circles_arcs_and_curves() { let mut s = session(); diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index 17177671cf..88daf4d7a1 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -118,7 +118,12 @@ //! `%AI24_EndSymbolList`); each instance as `/SymbolInstance :`, `(name) /SymbolRef ,`, the //! matrix taking the art to art space as `a b c d tx ty /RTransformMatrix`, `;`, then its name //! and opacity mask and a state block as a group's with its opacity and blending mode (an -//! instance with isolation, knockout or knockout shape of its own is written as its art). The +//! instance with isolation, knockout or knockout shape of its own is written as its art). A +//! dynamic symbol's art dictionary also holds `VectorCraftDynamicSymbol` (`/Int`, 1), and the +//! dictionary of an instance with changes of its own (`symbol_overrides`) holds +//! `VectorCraftSymbolOverrides`, a `/String` of the changes as hex-coded JSON: the format's own +//! entries, as other apps' editing data is not documented, read back by this reader and left out by +//! others. The //! definitions are at most the reader's 4,096. In a symbol's art, an instance's matrix and //! a gradient's take the art to the canvas's space turned y up about art space's origin there, //! and a gradient mesh's corners are in that space; an envelope's contents in its dictionary are @@ -191,7 +196,7 @@ //! and instances of //! symbols past 4,096 as their art (symbol art past [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects //! in all left out), instances of symbols the document doesn't have as empty groups, symbols' 9-slice -//! guides, export types and dynamic type left out, gradient meshes the reader wouldn't read back as +//! guides, export types left out, gradient meshes the reader wouldn't read back as //! they are, folded meshes, meshes in pattern tiles and in art cut to a clipping object and every mesh //! on a large canvas as their drawn look, blends the reader wouldn't read back live as //! their steps, other live objects (placed documents included) as their art, @@ -220,6 +225,7 @@ use vectorcraft_pdf::PrivateData; use crate::ps; mod writer; +pub(crate) use writer::{DYNAMIC_KEY, OVERRIDES_KEY, hex_decode}; use writer::Writer; diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 22d3203e3b..602b86910b 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -6394,7 +6394,8 @@ fn instances_the_data_cant_hold_are_written_as_their_art() { let layer = doc.layers[0].id; doc.insert(Some(layer), usize::MAX, changed).unwrap(); doc.insert(Some(layer), usize::MAX, plain).unwrap(); - assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::SYMBOL_ART, writer::SYMBOL_OPTIONS]); + doc.symbols[0].dynamic = false; + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::SYMBOL_ART]); let back = read_back(&doc); assert_eq!(kinds(&back), ["art", "instance"]); let green = back.layers[0].children().unwrap()[0].clone(); @@ -6890,7 +6891,7 @@ fn symbol_options_and_linked_images_in_symbols_are_reported() { let layer = doc.layers[0].id; doc.insert(Some(layer), usize::MAX, one).unwrap(); let out = export_ai_editing(&doc, &opts()).unwrap(); - assert_eq!(out.warnings, [writer::SYMBOL_OPTIONS, writer::LINKS_EMBEDDED]); + assert_eq!(out.warnings, [writer::LINKS_EMBEDDED]); let p = program_shown(&doc); assert!(p.contains("%AI5_BeginRaster") && !p.contains("%AI5_BeginPlace"), "{p}"); let back = read_back(&doc); @@ -15982,3 +15983,56 @@ fn a_mesh_eight_levels_down_is_written_as_a_mesh() { assert_eq!(back.len(), 1, "{back:#?}"); assert_mesh_exact(mesh_of(&back[0]), &want, "eight levels down"); } + +fn dynamic_doc() -> Document { + let mut doc = Document::new(200.0, 100.0); + let art = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + doc.symbols.push(Symbol { dynamic: true, name: "Leaf".into(), art: Arc::new(art) }); + let layer = doc.layers[0].id; + for (x, c) in [(10.0, Color::rgb(1.0, 0.0, 0.0)), (50.0, Color::rgb(0.0, 0.0, 1.0))] { + let mut i = instance(&mut doc, "Leaf", Affine::translate((x, 10.0))); + i.extras_mut().symbol_overrides = vec![vectorcraft_doc::SymbolOverride { fill: Some(solid(c)), opacity: Some(0.5), ..Default::default() }]; + doc.insert(Some(layer), usize::MAX, i).unwrap(); + } + let plain = instance(&mut doc, "Leaf", Affine::translate((90.0, 10.0))); + doc.insert(Some(layer), usize::MAX, plain).unwrap(); + doc +} + +#[test] +fn dynamic_symbols_and_their_instance_changes_survive_a_round_trip() { + let doc = dynamic_doc(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::SYMBOL_CHANGES]); + let back = read_back(&doc); + assert!(back.symbols[0].dynamic); + let kids = back.layers[0].children().unwrap(); + assert!(kids.iter().all(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }))); + let want: Vec<_> = doc.layers[0].children().unwrap().iter().map(|n| n.extras().symbol_overrides.clone()).collect(); + let got: Vec<_> = kids.iter().map(|n| n.extras().symbol_overrides.clone()).collect(); + assert_eq!(got, want); + assert_ne!(got[0], got[1]); + assert!(got[2].is_empty()); +} + +#[test] +fn static_symbols_write_no_dynamic_entries() { + let mut doc = dynamic_doc(); + doc.symbols[0].dynamic = false; + let layer = doc.layers[0].id; + for n in doc.layers[0].children().unwrap().to_vec() { + doc.remove(n.id).unwrap(); + } + for x in [10.0, 50.0] { + let i = instance(&mut doc, "Leaf", Affine::translate((x, 10.0))); + doc.insert(Some(layer), usize::MAX, i).unwrap(); + } + let p = program(&doc); + assert!(!p.contains("VectorCraftDynamicSymbol") && !p.contains("VectorCraftSymbolOverrides")); + assert!(export_ai_editing(&doc, &opts()).unwrap().warnings.is_empty()); + let back = read_back(&doc); + assert!(!back.symbols[0].dynamic); + let kids = back.layers[0].children().unwrap(); + assert_eq!(kids.len(), 2); + assert!(kids.iter().all(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }) && n.extras().symbol_overrides.is_empty())); +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 41254840cb..6c1f4a398f 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -48,8 +48,9 @@ pub(super) use paints::{ GRADIENT_COMPARISONS, GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, SCANNED_DEFINITIONS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name, }; +pub(crate) use symbols::{DYNAMIC_KEY, OVERRIDES_KEY, hex_decode}; #[cfg(test)] -pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS}; +pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_CHANGES, SYMBOL_COUNT, SYMBOL_OPTIONS}; #[cfg(test)] pub(super) use texts::{FONT_RESOLVES, RESOLVE_EACH_RUN, TYPE_ATTRIBUTES}; #[cfg(test)] @@ -286,6 +287,7 @@ pub(super) struct Writer<'a> { symbol_scales: HashMap, /// The entries a symbol's dictionary adds to its art's dictionary, and the art's id. root_entries: Option<(vectorcraft_doc::NodeId, String)>, + instance_entries: Option<(vectorcraft_doc::NodeId, String)>, /// The objects that may be written with an art style, as they were before baking, by id /// ([`styles::styled_objects`]). pub(super) styled: HashMap>, @@ -405,6 +407,7 @@ impl<'a> Writer<'a> { inner_scale: 1.0, symbol_scales: HashMap::new(), root_entries: None, + instance_entries: None, styled: HashMap::new(), symbol_styled: HashMap::new(), pattern_styled: HashMap::new(), @@ -818,7 +821,7 @@ impl<'a> Writer<'a> { mask_window = self.windowed.take(); } } - NodeKind::SymbolInstance { symbol, xf } if self.live_instance_in_room(n, symbol, *xf) => self.symbol_instance(symbol, *xf, xy), + NodeKind::SymbolInstance { symbol, xf } if self.live_instance_in_room(n, symbol, *xf) => self.symbol_instance(n, symbol, *xf, xy), NodeKind::SymbolInstance { symbol, xf } => { if !self.open_group("u") { return; @@ -1016,6 +1019,10 @@ impl<'a> Writer<'a> { Some((id, _)) if *id == n.id => self.root_entries.take().map(|(_, e)| e), _ => None, }; + let entries = match &self.instance_entries { + Some((id, _)) if *id == n.id => entries.or_else(|| self.instance_entries.take().map(|(_, e)| e)), + _ => entries, + }; let role = match &self.blend_role { Some((id, _)) if *id == n.id => self.blend_role.take().map(|(_, e)| e), _ => None, diff --git a/crates/eps/src/ai_editing/writer/symbols.rs b/crates/eps/src/ai_editing/writer/symbols.rs index 4d4bb2acba..a616d748d1 100644 --- a/crates/eps/src/ai_editing/writer/symbols.rs +++ b/crates/eps/src/ai_editing/writer/symbols.rs @@ -14,7 +14,27 @@ use crate::ps; pub(in crate::ai_editing) const SYMBOL_ART: &str = "symbol instances with a fill, appearance changes, isolation, knockout or knockout shape of their own, instances of symbols with 9-slice guides or pattern paint, instances in pattern tiles or in art cut to a clipping object, instances scaled almost flat, instances that turn, mirror or scale symbols holding type, live objects, instances written as their art, shapes with rounded live corners or strokes written as outlines or brush art, instances that scale their symbol more than 100 times, instances on the layers of a large canvas and instances of symbols past 4,096 are written as their art in the editing data for other apps"; pub(in crate::ai_editing) const SYMBOL_OPTIONS: &str = - "the 9-slice guides, export types and dynamic type of symbols are left out of the editing data for other apps"; + "the 9-slice guides and export types of symbols are left out of the editing data for other apps"; +pub(in crate::ai_editing) const SYMBOL_CHANGES: &str = + "the changes of dynamic symbol instances are kept in dictionary entries of their own, which other apps leave out"; +pub(crate) const DYNAMIC_KEY: &str = "VectorCraftDynamicSymbol"; +pub(crate) const OVERRIDES_KEY: &str = "VectorCraftSymbolOverrides"; +const MAX_OVERRIDES_BYTES: usize = 1 << 20; + +pub(crate) fn hex_decode(s: &str) -> Option> { + if !s.len().is_multiple_of(2) || s.len() / 2 > MAX_OVERRIDES_BYTES { + return None; + } + s.as_bytes().chunks(2).map(|c| u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok()).collect() +} + +fn hex_encode(b: &[u8]) -> String { + b.iter().fold(String::with_capacity(b.len() * 2), |mut s, v| { + let _ = write!(s, "{v:02x}"); + s + }) +} + pub(in crate::ai_editing) const MISSING_SYMBOL: &str = "symbol instances of symbols the document doesn't have are written as empty groups in the editing data for other apps"; /// The most an instance may scale its symbol's art, nested instances' scales included: the art's @@ -55,7 +75,8 @@ impl Writer<'_> { /// that keeps the art's area as it is written and scales it as the definition allows /// ([`Self::keeps_scale`]). pub(super) fn live_instance(&mut self, n: &Node, symbol: &str, xf: Affine) -> bool { - let own = vectorcraft_brush::stain(n).is_some() || !n.extras().symbol_overrides.is_empty(); + let dynamic = self.symbol_doc.symbols.iter().any(|s| s.name == symbol && s.dynamic); + let own = vectorcraft_brush::stain(n).is_some() || (!dynamic && !n.extras().symbol_overrides.is_empty()); let group_state = n.isolate || n.knockout != Knockout::Neutral || n.knockout_shape; // The matrix as written (to ten decimals) must still keep the art's area. let m = Affine::new((self.instance_space * xf).as_coeffs().map(|v| (v * 1e10).round() / 1e10)); @@ -153,7 +174,16 @@ impl Writer<'_> { /// canvas's space turned y up about art space's origin there) as `a b c d tx ty /// /RTransformMatrix` (to ten decimals), `;`, then its state block as a group's: `Xy`, `0 0 Xd` /// and `6 () XW` when it has transparency, else `9 () XW`. Its dictionary goes between the two. - pub(super) fn symbol_instance(&mut self, symbol: &str, xf: Affine, xy: Xy) { + pub(super) fn symbol_instance(&mut self, n: &Node, symbol: &str, xf: Affine, xy: Xy) { + let o = &n.extras().symbol_overrides; + if !o.is_empty() + && let Ok(json) = serde_json::to_vec(o) + && json.len() <= MAX_OVERRIDES_BYTES + { + let e = format!("%_{} /String ({OVERRIDES_KEY}) ,\n", ps::bytes(hex_encode(&json).as_bytes())); + self.instance_entries = Some((n.id, e)); + self.warn(SYMBOL_CHANGES); + } let m = self.instance_space * xf; let _ = write!(self.body, "/SymbolInstance :\n{} /SymbolRef ,\n", ps::bytes(symbol.as_bytes())); for v in m.as_coeffs() { @@ -201,7 +231,7 @@ impl Writer<'_> { self.warn(SYMBOL_COUNT); return false; } - if sym.dynamic || doc.symbol_export_type(name) != SymbolExportType::default() || doc.symbol_nine_slice(name).is_some() { + if doc.symbol_export_type(name) != SymbolExportType::default() || doc.symbol_nine_slice(name).is_some() { self.warn(SYMBOL_OPTIONS); } // The art's effects are its own, not those of a drawn look that first places it, and its @@ -260,7 +290,10 @@ impl Writer<'_> { (self.to_art, self.grad_space, self.canvas, self.instance_space) = (Affine::IDENTITY, about_origin, Affine::IDENTITY, about_origin); self.block_end = usize::MAX; let registration = u16::from(doc.symbol_registration(name).0.min(8)) + 1; - let entries = format!("%_{registration} /Int (AI13PatternRegistrationType) ,\n"); + let mut entries = format!("%_{registration} /Int (AI13PatternRegistrationType) ,\n"); + if sym.dynamic { + let _ = writeln!(entries, "%_1 /Int ({DYNAMIC_KEY}) ,"); + } // The canvas draws a symbol's art even when its root is hidden, so the root is written shown. let shown; let root: &Node = if sym.art.visible { diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index c630c9cf43..4c574ce3bb 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -17,6 +17,7 @@ //! objects and points. Anything it doesn't read is an error: the caller opens the file the way it //! did before (the printed page, or the PDF), with a warning saying why. +mod arrowhead; mod blend; mod brush; mod envelope; diff --git a/crates/eps/src/import/ai/arrowhead.rs b/crates/eps/src/import/ai/arrowhead.rs new file mode 100644 index 0000000000..f1a30c08af --- /dev/null +++ b/crates/eps/src/import/ai/arrowhead.rs @@ -0,0 +1,244 @@ +//! Arrowheads a file defines: the art of a symbol that a stroke's arrowhead entry names +//! ([`super::style::StrokeArrows`]), read into a head ([`head`]). +//! +//! Not publicly documented. As the files have it, an arrowhead symbol's art (y down here, as the +//! document's symbols are) points right along a straight, level sample of the line it ends: an +//! open stroked path with no fill whose anchors and handles all lie on that line, 1 pt wide. The +//! sample ends where the line stops under the head. The rest of the art that paints is the head; +//! its tip is its rightmost point, and a symbol unit is one point on a 1 pt stroke at 100 %, so a +//! unit is the head's weight as it is for VectorCraft's own heads. Art that paints nothing (the +//! frame of the symbol's box, hidden or fully transparent art) is left out. + +use vectorcraft_doc::{AppearanceItem, CustomArrowhead, Node, NodeKind, StrokeLayer}; +use vectorcraft_geom::{Affine, FillRule, PathData, Point}; + +/// The most anchors an arrowhead symbol's art is read with, outlined strokes included, before its +/// shapes are united. +const MAX_ART_ANCHORS: usize = 65_536; +/// How deep the groups of an arrowhead symbol's art are read. +const MAX_DEPTH: usize = 16; + +/// The head that symbol art `art` (in the document's symbol space) draws, named `name`. `None` when +/// the art doesn't have exactly one sample of the line, its sample isn't 1 pt wide, it holds +/// anything but paths, compound paths and groups (a clip group, say), has an effect, a brush, an +/// opacity mask, partial opacity or a group with fills or strokes of its own, paints no head, or is +/// too detailed for one; or when the +/// line would stop past the head's tip or farther back than a head can reach +/// ([`CustomArrowhead::MAX_UNITS`]). +pub(super) fn head(name: &str, art: &Node) -> Option { + let mut parts = Parts::default(); + match &art.kind { + // The members of the symbol's group are its art's top level, where the sample is. + NodeKind::Group { children, clip: false } if art.visible && plain(art) && !paints(art) => { + for c in children { + parts.member(c, true, 1)?; + } + } + _ => parts.member(art, true, 0)?, + } + let [(axis, line_end)] = parts.lines.as_slice() else { return None }; + if parts.shapes.is_empty() { + return None; + } + let refs: Vec<(&PathData, FillRule)> = parts.shapes.iter().map(|(p, r)| (p, *r)).collect(); + let area = vectorcraft_pathops::try_unite_all(&refs).ok()?; + let b = area.bounds().filter(|b| b.is_finite() && b.height() > 1e-9)?; + let tip = b.x1; + // Head units: x back from the tip, y across to the right of the way the head points (down). + let h = CustomArrowhead::new(name.to_string(), area.transformed(Affine::new([-1.0, 0.0, 0.0, 1.0, tip, -axis]))); + let h = h.with_stop(tip - line_end); + (!h.path.subpaths.is_empty() && h.stop.is_some()).then_some(h) +} + +/// What an arrowhead symbol's art is made of. +#[derive(Default)] +struct Parts { + /// Each sample of the line: the line's y, and the x where the sample ends. + lines: Vec<(f64, f64)>, + /// The areas the head paints. + shapes: Vec<(PathData, FillRule)>, + anchors: usize, +} + +impl Parts { + /// Read `n`, a member of the art (`top`: of its top level) `depth` groups down. `None` when it + /// is something [`head`] doesn't read. + fn member(&mut self, n: &Node, top: bool, depth: usize) -> Option<()> { + if depth > MAX_DEPTH { + return None; + } + // Hidden or fully transparent art paints nothing. + if !n.visible || n.opacity <= 0.0 { + return Some(()); + } + if !plain(n) { + return None; + } + match &n.kind { + NodeKind::Group { children, clip: false } => { + if paints(n) { + return None; + } + children.iter().try_for_each(|c| self.member(c, false, depth + 1)) + } + NodeKind::Path { guide: true, .. } => Some(()), + NodeKind::Path { path, rule, .. } => self.painted(n, path, *rule, top), + NodeKind::Compound { children, rule } => { + let mut subpaths = vec![]; + for c in children { + subpaths.extend(c.path_data()?.subpaths.iter().cloned()); + } + self.painted(n, &PathData::new(subpaths), *rule, false) + } + _ => None, + } + } + + /// Read the fills and strokes of path or compound path `n`, its outline `path` filled under + /// `rule` (`top`: a member of the art's top level, which may be the sample of the line). + fn painted(&mut self, n: &Node, path: &PathData, rule: FillRule, top: bool) -> Option<()> { + self.room(path.anchor_count())?; + let mut filled = false; + let mut strokes: Vec<&StrokeLayer> = vec![]; + for item in &n.appearance.items { + match item { + AppearanceItem::Fill(f) if f.visible && f.opacity > 0.0 && !f.paint.is_none() => { + if !f.effects.is_empty() || f.opacity < 1.0 { + return None; + } + filled = true; + } + AppearanceItem::Stroke(s) if s.visible && s.opacity > 0.0 && !s.paint.is_none() && s.width > 0.0 => { + if !s.effects.is_empty() || s.brush.is_some() || s.opacity < 1.0 { + return None; + } + strokes.push(s); + } + _ => {} + } + } + if top + && !filled + && let [line] = strokes.as_slice() + && let Some(sample) = sample_line(path) + { + // The sample is 1 pt, the weight of a head at one unit; another weight (art stored + // at another scale, as a Large Canvas file's) gives the units no known size. + if (line.width - 1.0).abs() > 1e-6 { + return None; + } + self.lines.push(sample); + return Some(()); + } + if filled { + self.shapes.push((path.clone(), rule)); + } + for s in strokes { + let outline = vectorcraft_effects::stroke::outline_region(path, rule, s); + self.room(outline.anchor_count())?; + if !outline.subpaths.is_empty() { + self.shapes.push((outline, FillRule::NonZero)); + } + } + Some(()) + } + + /// Count `anchors` more; `None` past [`MAX_ART_ANCHORS`]. + fn room(&mut self, anchors: usize) -> Option<()> { + self.anchors = self.anchors.saturating_add(anchors); + (self.anchors <= MAX_ART_ANCHORS).then_some(()) + } +} + +/// Does `n` draw as its shapes alone: fully opaque, with no effects and no opacity mask applied? +/// A head is one opaque shape, so partly transparent or masked art isn't read as one. +fn plain(n: &Node) -> bool { + n.opacity >= 1.0 && n.appearance.effects.is_empty() && n.extras().mask.as_ref().is_none_or(|m| m.disabled) +} + +/// Does `n` (a group) have fills or strokes of its own that paint? +fn paints(n: &Node) -> bool { + n.appearance.items.iter().any(|i| match i { + AppearanceItem::Fill(f) => f.visible && !f.paint.is_none(), + AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none(), + }) +} + +/// `path` as a sample of the line, when it is one open subpath of two anchors or more whose anchors +/// and handles all lie level with its first anchor: that y, and the x where it ends (its +/// rightmost anchor). +fn sample_line(path: &PathData) -> Option<(f64, f64)> { + let [sub] = path.subpaths.as_slice() else { return None }; + if sub.closed || sub.anchors.len() < 2 { + return None; + } + let y = sub.anchors.first()?.p.y; + let level = |q: Point| q.x.is_finite() && (q.y - y).abs() <= 1e-6 * (1.0 + y.abs()); + if !y.is_finite() || !sub.anchors.iter().all(|a| level(a.p) && level(a.h_in) && level(a.h_out)) { + return None; + } + Some((y, sub.anchors.iter().map(|a| a.p.x).fold(f64::NEG_INFINITY, f64::max))) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use vectorcraft_color::{Color, Paint}; + use vectorcraft_doc::{Appearance, Node, NodeId, OpacityMask}; + use vectorcraft_geom::{PathData, Point, SubPath}; + + use super::head; + + fn path(id: u64, points: &[(f64, f64)], closed: bool, appearance: Appearance) -> Arc { + let points: Vec = points.iter().map(|(x, y)| Point::new(*x, *y)).collect(); + Arc::new(Node::path(NodeId(id), PathData::single(SubPath::polyline(&points, closed)), appearance)) + } + + /// A 1 pt sample of the line from x = −9 to 4 on y = 0. + fn sample() -> Arc { + path(1, &[(-9.0, 0.0), (4.0, 0.0)], false, Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)) + } + + /// A filled wedge from x = 2 back to its tip at x = 8, 3 either side. + fn wedge() -> Arc { + path(2, &[(2.0, -3.0), (8.0, 0.0), (2.0, 3.0)], true, Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0)) + } + + fn art(members: Vec>) -> Node { + Node::group(NodeId(10), members) + } + + #[test] + fn a_wedge_and_its_sample_make_a_head() { + let h = head("W", &art(vec![sample(), wedge()])).expect("a head"); + assert_eq!(h.stop(), 4.0); + } + + #[test] + fn partly_transparent_or_masked_art_makes_no_head() { + // The head would come in opaque and whole, with the bounds of the art. + let half = |n: Arc| Arc::new(Node { opacity: 0.5, ..(*n).clone() }); + let mut faint_fill = (*wedge()).clone(); + let mut ap = (*faint_fill.appearance).clone(); + if let Some(f) = ap.fill_mut() { + f.opacity = 0.5; + } + faint_fill.appearance = ap.into(); + let mut masked = (*wedge()).clone(); + masked.extras_mut().mask = Some(Box::new(OpacityMask { art: sample(), clip: true, invert: false, disabled: false, linked: true })); + let cases = [ + ("a head at half opacity", art(vec![sample(), half(wedge())])), + ("a fill at half opacity", art(vec![sample(), Arc::new(faint_fill)])), + ("a group at half opacity", art(vec![sample(), half(Arc::new(art(vec![wedge()])))])), + ("the art at half opacity", Node { opacity: 0.5, ..art(vec![sample(), wedge()]) }), + ("a head with an opacity mask", art(vec![sample(), Arc::new(masked.clone())])), + ]; + for (why, a) in cases { + assert!(head("W", &a).is_none(), "{why}"); + } + // A disabled mask isn't applied. + masked.extras_mut().mask.as_mut().unwrap().disabled = true; + assert!(head("W", &art(vec![sample(), Arc::new(masked)])).is_some()); + } +} diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index b354022258..11ebe2aac6 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -124,8 +124,8 @@ use vectorcraft_color::swatch::Swatch; use vectorcraft_color::{BlendMode, Paint}; use vectorcraft_doc::cmyk::Inks; use vectorcraft_doc::{ - Appearance, AppearanceItem, Artboard, ColorMode, Dash, Document, FillLayer, ImageBlob, ImageObject, Knockout, LayerColor, LineCap, LineJoin, - LinkInfo, Node, NodeId, NodeKind, OpacityMask, PageBox, PatternDef, StrokeLayer, Unit, + Appearance, AppearanceItem, Artboard, ColorMode, CustomArrowhead, Dash, Document, FillLayer, ImageBlob, ImageObject, Knockout, LayerColor, + LineCap, LineJoin, LinkInfo, Node, NodeId, NodeKind, OpacityMask, PageBox, PatternDef, StrokeLayer, Unit, }; use vectorcraft_geom::{AnchorKind, FillRule, PathData}; @@ -544,6 +544,10 @@ struct Reader<'a> { symbol_bounds: HashMap, /// The symbols read, by their name in the file → their name in the document. symbol_names: HashMap, + /// The heads of the arrowhead symbols the art styles' strokes name, by the symbol's name in + /// the file (`None`: not a symbol read, or not one read as a head), read with the styles + /// ([`Reader::read_arrowheads`]). + arrowheads: HashMap>>, /// The names the symbols read have in the document, and for each name read more than once, /// the number its next copy is tried with. symbol_taken: HashSet, @@ -843,6 +847,7 @@ impl<'a> Reader<'a> { unread: Vec::new(), symbol_bounds: HashMap::new(), symbol_names: HashMap::new(), + arrowheads: HashMap::new(), symbol_taken: HashSet::new(), symbol_suffix: HashMap::new(), symbol_art_bounds: HashMap::new(), diff --git a/crates/eps/src/import/ai/read/containers.rs b/crates/eps/src/import/ai/read/containers.rs index 46743e9d70..2a14ce1c24 100644 --- a/crates/eps/src/import/ai/read/containers.rs +++ b/crates/eps/src/import/ai/read/containers.rs @@ -752,6 +752,8 @@ impl<'a> Reader<'a> { if std::mem::replace(&mut self.symbols_checked, true) { return; } + // The symbols are all read now: the heads of those defined after the styles. + self.read_arrowheads(); // Each symbol's name in the file (none for one named as an earlier one), and the names its // instances use. let files: HashMap<&str, &str> = self.symbol_names.iter().map(|(file, named)| (named.as_str(), file.as_str())).collect(); diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index 67b3e799e2..4c5b48c04d 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -128,6 +128,7 @@ impl<'a> Reader<'a> { // section inside it would replace the file's own. if self.subreader_depth == 0 { self.styles = crate::import::ai::style::art_styles_in(section, &mut self.names); + self.read_arrowheads(); } return Ok(()); } @@ -398,6 +399,7 @@ impl<'a> Reader<'a> { sub.gradients = std::mem::take(&mut self.gradients); sub.global_names = std::mem::take(&mut self.global_names); sub.styles = std::mem::take(&mut self.styles); + sub.arrowheads = std::mem::take(&mut self.arrowheads); sub.nodes = self.nodes; sub.template = self.template; self.lend_budgets(&mut sub); @@ -408,6 +410,7 @@ impl<'a> Reader<'a> { self.names.absorb(std::mem::take(&mut sub.names)); self.global_names = std::mem::take(&mut sub.global_names); self.styles = std::mem::take(&mut sub.styles); + self.arrowheads = std::mem::take(&mut sub.arrowheads); // Unread art in the definition, hidden or not, leaves the tile incomplete. let whole = read.is_ok() && sub.unsupported.is_empty() @@ -429,6 +432,7 @@ impl<'a> Reader<'a> { sub.gradients = std::mem::take(&mut self.gradients); sub.global_names = std::mem::take(&mut self.global_names); sub.styles = std::mem::take(&mut self.styles); + sub.arrowheads = std::mem::take(&mut self.arrowheads); sub.nodes = self.nodes; sub.template = self.template; self.lend_budgets(&mut sub); @@ -444,6 +448,7 @@ impl<'a> Reader<'a> { self.gradients = std::mem::take(&mut sub.gradients); self.global_names = std::mem::take(&mut sub.global_names); self.styles = std::mem::take(&mut sub.styles); + self.arrowheads = std::mem::take(&mut sub.arrowheads); self.names.absorb(std::mem::take(&mut sub.names)); let whole = read.is_ok() && sub.unsupported.is_empty() @@ -597,6 +602,7 @@ impl<'a> Reader<'a> { sub.gradients = std::mem::take(&mut self.gradients); sub.global_names = std::mem::take(&mut self.global_names); sub.styles = std::mem::take(&mut self.styles); + sub.arrowheads = std::mem::take(&mut self.arrowheads); sub.pattern_tiles = std::mem::take(&mut self.pattern_tiles); sub.v7_patterns.clone_from(&self.v7_patterns); sub.nodes = self.nodes; @@ -607,6 +613,7 @@ impl<'a> Reader<'a> { self.gradients = std::mem::take(&mut sub.gradients); self.global_names = std::mem::take(&mut sub.global_names); self.styles = std::mem::take(&mut sub.styles); + self.arrowheads = std::mem::take(&mut sub.arrowheads); self.pattern_tiles = std::mem::take(&mut sub.pattern_tiles); self.names.absorb(std::mem::take(&mut sub.names)); // Art stopped by a trailer, or with an array, type, image, placed file, gradient mesh or @@ -620,7 +627,7 @@ impl<'a> Reader<'a> { || sub.mesh.is_some() || sub.gradient_def.is_some(); let head = sub.symbol.take().unwrap_or_default(); - let registration = head.registration; + let (registration, dynamic) = (head.registration, head.dynamic); let measured = read.is_ok() && !open && sub.unsupported.is_empty() && sub.unknown.is_empty() && sub.frames.len() == 1; let Some(frame) = sub.frames.pop().filter(|_| measured) else { return }; let mut kids = frame.children; @@ -662,7 +669,7 @@ impl<'a> Reader<'a> { } } let named = self.unique_symbol_name(if name.is_empty() { "Symbol" } else { &name }); - self.doc.symbols.push(Symbol { name: named.clone(), art: Arc::new(art), dynamic: false }); + self.doc.symbols.push(Symbol { name: named.clone(), art: Arc::new(art), dynamic }); if let Some(reg) = registration.and_then(symbol_registration) { self.doc.set_symbol_registration(&named, reg); } @@ -788,6 +795,7 @@ impl<'a> Reader<'a> { // version 7 form, lent. sub.gradients = std::mem::take(&mut self.gradients); sub.styles = std::mem::take(&mut self.styles); + sub.arrowheads = std::mem::take(&mut self.arrowheads); sub.pattern_tiles = std::mem::take(&mut self.pattern_tiles); sub.v7_patterns = std::mem::take(&mut self.v7_patterns); sub.global_names = std::mem::take(&mut self.global_names); @@ -799,6 +807,7 @@ impl<'a> Reader<'a> { self.nodes = sub.nodes; self.gradients = std::mem::take(&mut sub.gradients); self.styles = std::mem::take(&mut sub.styles); + self.arrowheads = std::mem::take(&mut sub.arrowheads); self.pattern_tiles = std::mem::take(&mut sub.pattern_tiles); self.v7_patterns = std::mem::take(&mut sub.v7_patterns); self.global_names = std::mem::take(&mut sub.global_names); diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 2eee5a0a15..ae2772a3c9 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -455,6 +455,8 @@ pub fn graphic_styles(data: &[u8], large_canvas: bool, names: &mut obj::Names) - r.large_canvas = large_canvas.then_some(1.0); // The styles come before the art, so an error in the art leaves them read. let _ = r.run(); + // No layer checks the symbols here: the heads of those defined after the styles. + r.read_arrowheads(); let styles = r.graphic_styles().0; let used: Vec<&str> = styles.iter().map(|s| s.name.as_str()).collect(); names.absorb_among(std::mem::take(&mut r.names), &used); @@ -781,6 +783,19 @@ impl<'a> Reader<'a> { { head.registration = Some(*r); } + if self.frames.len() == 1 + && let Some(head) = self.symbol.as_mut() + && o.nums(crate::ai_editing::DYNAMIC_KEY).first().is_some_and(|v| *v != 0.0) + { + head.dynamic = true; + } + if let Some(text) = o.text(crate::ai_editing::OVERRIDES_KEY) + && let Some(bytes) = crate::ai_editing::hex_decode(&text) + && let Ok(list) = serde_json::from_slice::>(&bytes) + && let Some(n) = self.last_object().filter(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })) + { + n.extras_mut().symbol_overrides = list.into_iter().filter(|s| !s.is_empty()).collect(); + } self.constraint_art(o); self.placed_page(o); // A blend's key object or spine. @@ -1183,7 +1198,7 @@ impl<'a> Reader<'a> { continue; } let Some(st) = self.styles.get(&name) else { continue }; - let Some(mut appearance) = appearance_from_art_style(st, &self.gradients) else { continue }; + let Some(mut appearance) = appearance_from_art_style(st, &self.gradients, &self.arrowheads) else { continue }; // A Large Canvas copy's styles are at its art's scale ([`Self::ensure_space`]). if let Some(s) = self.large_canvas.filter(|s| *s != 1.0) { appearance.scale_strokes(s); diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 101d924d60..65875c5a52 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -2,9 +2,12 @@ use super::containers::close; use super::document::slot_of; use super::types::{BLENDS, FLIP, Frame, GRAPH_UNENDED, IGNORED, Kind, MAX_DEPTH, MAX_NODES, MAX_TAG_TEXT, MAX_TAGS, Place, URL_TAG, line_width}; use super::{ - Affine, Appearance, AppearanceItem, Arc, BlendMode, BrushesKept, Dash, FillLayer, FillRule, Global, Gradient, GradientDef, HashMap, HashSet, - Instance, Knockout, LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, Paint, Reader, Rect, ShownNames, StrokeLayer, V, obj, paint, + Affine, Appearance, AppearanceItem, Arc, BlendMode, BrushesKept, CustomArrowhead, Dash, FillLayer, FillRule, Global, Gradient, GradientDef, + HashMap, HashSet, Instance, Knockout, LayerColor, LineCap, LineJoin, Node, NodeId, NodeKind, Paint, Reader, Rect, ShownNames, StrokeLayer, V, + obj, paint, }; +use vectorcraft_doc::{ArrowAlign, Arrowhead}; +use vectorcraft_geom::PathData; impl<'a> Reader<'a> { // ---- operators ------------------------------------------------------------------------- @@ -707,6 +710,30 @@ impl<'a> Reader<'a> { self.note_state(); } + /// Read the heads of the arrowhead symbols the art styles' strokes name into + /// [`Reader::arrowheads`] ([`crate::import::ai::arrowhead::head`]), each symbol once. Called + /// when the styles are read and again when the symbols have all been read ([`Self::check_symbols`]), + /// for a file that defines its symbols after its styles: a name with no symbol read yet is + /// left for then. + pub(super) fn read_arrowheads(&mut self) { + use crate::import::ai::style::StyleItem; + for st in self.styles.values() { + for item in &st.items { + let StyleItem::Stroke { arrows: Some(arrows), .. } = item else { continue }; + for name in arrows.symbols() { + if self.arrowheads.contains_key(name) { + continue; + } + let symbol = self.symbol_names.get(name).and_then(|named| self.doc.symbols.iter().find(|s| &s.name == named)); + if let Some(s) = symbol { + let head = crate::import::ai::arrowhead::head(name, &s.art).map(Arc::new); + self.arrowheads.insert(name.to_string(), head); + } + } + } + } + } + /// Brings [`Reader::brushes_kept`] up to date with the brushes and brush art read so far. fn note_brushes_kept(&mut self) { use super::super::brush; @@ -818,6 +845,7 @@ impl<'a> Reader<'a> { brushes: &self.brush_drafts, kept: &self.brushes_kept.kept, bending: &self.brushes_kept.bending, + arrowheads: &self.arrowheads, space, }, ) @@ -1061,6 +1089,8 @@ struct StylePaints<'a> { kept: &'a [bool], /// The art an Art brush draws as the file does, with its length ([`super::super::brush::bending_art`]). bending: &'a HashMap, + /// The heads of the arrowhead symbols strokes name ([`Reader::arrowheads`]). + arrowheads: &'a HashMap>>, space: Affine, } @@ -1411,7 +1441,7 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p return None; } } - stroke_layer(item)? + stroke_layer(item, paints.arrowheads)? } }; if let Some(look) = st.looks.get(n) { @@ -1430,6 +1460,88 @@ fn styled(object: &Node, look: &Node, st: &crate::import::ai::style::ArtStyle, p if !slot && st.effects.iter().any(|e| e.id == "distort.zigZag") && !draws_look_outline(object, &appearance, look) { return None; } + heads_placed(object, look, appearance, paints.space) +} + +/// What `appearance` paints on path or compound path `object`: its fills' outline and its strokes' +/// areas, heads included, measured exactly (a node's visual bounds allow a head its whole reach on +/// every side). `None` for another object or an appearance that paints nothing. +fn painted_bounds(object: &Node, appearance: &Appearance) -> Option { + let (path, rule) = match &object.kind { + NodeKind::Path { path, rule, .. } => (path.clone(), *rule), + NodeKind::Compound { children, rule } => { + (PathData::new(children.iter().filter_map(|c| c.path_data()).flat_map(|p| p.subpaths.iter().cloned()).collect()), *rule) + } + _ => return None, + }; + let mut out = None; + for item in &appearance.items { + let painted = match item { + AppearanceItem::Fill(f) if f.visible && !f.paint.is_none() => path.bounds(), + AppearanceItem::Stroke(s) if s.visible && !s.paint.is_none() => vectorcraft_effects::stroke::outline_region(&path, rule, s).bounds(), + _ => None, + }; + out = vectorcraft_geom::union_opt(out, painted); + } + out +} + +/// `appearance` (on `object`, whose drawn look is `look`, in a space `space` takes to the +/// document) with its strokes' arrowheads placed as the look draws them: the tips on the ends of +/// the path, or past them by the line's length under each head (Extend), whichever gives the +/// object the look's bounds within a quarter of the least distance a head moves between the two +/// (at least 0.05 pt, at most 0.5 pt). `None` +/// when neither does (the file draws the heads elsewhere: on other subpaths, say), or when both do +/// and any head moves 0.2 pt or more between them (the bounds can't tell which the file draws). +fn heads_placed(object: &Node, look: &Node, mut appearance: Appearance, space: Affine) -> Option { + let k = space.determinant().abs().sqrt(); + let k = if k.is_finite() && k > 0.0 { k } else { 1.0 }; + // How far each head moves between the placements (its line's length under it): the least and + // the most. + let (mut shift, mut most) = (f64::INFINITY, 0.0f64); + for item in &appearance.items { + let AppearanceItem::Stroke(s) = item else { continue }; + for (head, end) in [(&s.start_arrow, false), (&s.end_arrow, true)] { + if let Some(Arrowhead::Custom(c)) = head { + let moves = c.stop() * s.arrow_weight(end) * k; + (shift, most) = (shift.min(moves), most.max(moves)); + } + } + } + if shift.is_infinite() { + return Some(appearance); + } + let want = look.visual_bounds()?; + // Well under the distance between the placements, and under half a point: a look without + // those heads, or with them elsewhere, is off by more. + let tolerance = (shift / 4.0).clamp(0.05, 0.5); + let mut fits = vec![]; + for align in [ArrowAlign::Tip, ArrowAlign::Extend] { + for item in &mut appearance.items { + if let AppearanceItem::Stroke(s) = item { + s.arrow_align = align; + } + } + let mut scaled = appearance.clone(); + scaled.scale_strokes(k); + let got = painted_bounds(object, &scaled)?; + let off = [got.x0 - want.x0, got.y0 - want.y0, got.x1 - want.x1, got.y1 - want.y1].iter().fold(0.0f64, |m, d| m.max(d.abs())); + if off <= tolerance { + fits.push(align); + } + } + // Both fit when the bounds can't tell the placements apart (the end inside the bounds of the + // line's other segments), unless every head moves so little that either draws alike. + let align = match fits.as_slice() { + [one] => *one, + [first, _] if most < 0.2 => *first, + _ => return None, + }; + for item in &mut appearance.items { + if let AppearanceItem::Stroke(s) = item { + s.arrow_align = align; + } + } Some(appearance) } @@ -1559,7 +1671,11 @@ fn draws_look_outline(object: &Node, appearance: &Appearance, look: &Node) -> bo /// A style that is one paint is its fill and stroke ([`crate::import::ai::style::ArtStyle::one_paint`]). /// A style keeps only its gradients' names and angles, so each one's gradient, by VectorCraft's own /// rule, is fitted to the bounds of whatever object the style is applied to, at its angle. -pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle, gradients: &HashMap) -> Option { +pub(super) fn appearance_from_art_style( + st: &crate::import::ai::style::ArtStyle, + gradients: &HashMap, + arrowheads: &HashMap>>, +) -> Option { use crate::import::ai::style::StyleItem; if !st.plain { return None; @@ -1574,7 +1690,7 @@ pub(super) fn appearance_from_art_style(st: &crate::import::ai::style::ArtStyle, StyleItem::Fill(paint) => AppearanceItem::Fill(FillLayer::new(paint.clone())), // A graphic style's brush isn't checked against the file's brushes: it is left out. StyleItem::Stroke { brush: Some(_), .. } => return None, - StyleItem::Stroke { .. } => stroke_layer(item)?, + StyleItem::Stroke { .. } => stroke_layer(item, arrowheads)?, StyleItem::Gradient { name, angle } => AppearanceItem::Fill(FillLayer::new(named_gradient(name.as_deref()?, *angle, gradients)?)), StyleItem::Pattern { .. } => return None, }; @@ -1665,7 +1781,7 @@ pub(crate) fn read_parsed_style(parsed: &ParsedStyle, own_gradient: Option<&Pain .collect(); // No gradient is taken by name: on an object, one that isn't its own is placed where its drawn // look has it. - let mut appearance = appearance_from_art_style(&st, &HashMap::new())?; + let mut appearance = appearance_from_art_style(&st, &HashMap::new(), &HashMap::new())?; for (item, brush) in appearance.items.iter_mut().zip(brushes) { if let (AppearanceItem::Stroke(s), Some(brush)) = (item, brush) { s.brush = Some(brush); @@ -1680,12 +1796,27 @@ pub(crate) fn parsed_moves_with(parsed: &ParsedStyle, object: &Node) -> bool { !parsed.style.moves_outline() || moves_with(object, &parsed.style) } -/// A style's stroke as an appearance item (`None` for a fill). -fn stroke_layer(item: &crate::import::ai::style::StyleItem) -> Option { - let crate::import::ai::style::StyleItem::Stroke { paint, width, cap, join, miter, dash, profile, align, brush } = item else { return None }; +/// A style's stroke as an appearance item, its arrowheads the heads of `arrowheads` by symbol +/// name, each tip on its end of the path (where [`heads_placed`] finds the file draws them on an +/// object; a graphic style keeps that). `None` for a fill, or for a stroke +/// whose arrowhead symbol has no head there or whose head's weight would be under the least one +/// draws at ([`StrokeLayer::arrow_weight`]), so the head would draw larger than in the file. +fn stroke_layer(item: &crate::import::ai::style::StyleItem, arrowheads: &HashMap>>) -> Option { + let crate::import::ai::style::StyleItem::Stroke { paint, width, cap, join, miter, dash, profile, align, brush, arrows } = item else { + return None; + }; let mut layer = StrokeLayer::new(paint.clone(), line_width(*width)); (layer.cap, layer.join, layer.miter_limit, layer.dash, layer.profile, layer.align) = (*cap, *join, *miter, dash.clone(), profile.clone(), *align); layer.brush = brush.as_ref().map(|(name, _)| name.clone()); + if let Some(arrows) = arrows { + let head = |end: &Option<(String, f64)>| -> Option<(Option, f64)> { + let Some((name, pct)) = end else { return Some((None, 100.0)) }; + let head = arrowheads.get(name)?.clone()?; + (layer.width * pct / 100.0 >= StrokeLayer::LEAST_ARROW_WEIGHT).then_some((Some(Arrowhead::Custom(head)), *pct)) + }; + let ((start, start_pct), (end, end_pct)) = (head(&arrows.start)?, head(&arrows.end)?); + (layer.start_arrow, layer.end_arrow, layer.arrow_scale, layer.arrow_align) = (start, end, (start_pct, end_pct), ArrowAlign::Tip); + } Some(AppearanceItem::Stroke(layer)) } @@ -1914,6 +2045,7 @@ mod tests { brushes: &brushes, kept: &[true], bending: &bending, + arrowheads: &HashMap::new(), space: Affine::IDENTITY, }; let look = Node::group(NodeId(1), vec![square(2, Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))]); @@ -1960,6 +2092,7 @@ mod tests { brushes: &[], kept: &[], bending: &bending, + arrowheads: &HashMap::new(), space: Affine::IDENTITY, }; let look = Node::group(NodeId(1), vec![square(2, Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))]); diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index 02d4a3354a..a155d9f505 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -244,6 +244,7 @@ pub(super) struct PatternHead { pub(super) struct SymbolHead { /// `AI13PatternRegistrationType` in the dictionary after the art. pub(super) registration: Option, + pub(super) dynamic: bool, /// Art the reader left out (type, a placed file, non-native art, an image it can't read or /// place, a gradient it can't read): the symbol isn't kept, and its instances come in as the /// page draws them, within the box of the rest. diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index 4941fd62b8..d8ddfd5e4f 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -230,6 +230,8 @@ impl ArtStyle { } } +// A stroke takes about 300 bytes and the other items about 100; a style holds a few of each. +#[allow(clippy::large_enum_variant)] #[derive(Clone, Debug, PartialEq)] pub(super) enum StyleItem { Fill(Paint), @@ -258,9 +260,35 @@ pub(super) enum StyleItem { align: StrokeAlign, /// A brush: its name, and its settings for this object. brush: Option<(String, PathBrush)>, + /// Its arrowheads, as symbols of the file (`None`: it has none). + arrows: Option>, }, } +/// A stroke's arrowheads: each end's symbol (`/GObjRef : (name) /SymbolArt ; (BSArrowBeginSymbol)` +/// or `(BSArrowEndSymbol)` in the stroke's dictionary) by its name in the file, with its scale in +/// percent (`BSArrowBeginScale`, `BSArrowEndScale`; 100 without one). The symbol's art is the head +/// and a sample of the line it ends, which `read::ops` reads into a head once the symbols are read. +#[derive(Clone, Debug, Default, PartialEq)] +pub(super) struct StrokeArrows { + pub start: Option<(String, f64)>, + pub end: Option<(String, f64)>, +} + +impl StrokeArrows { + /// The names of the symbols, start first. + pub fn symbols(&self) -> impl Iterator { + [&self.start, &self.end].into_iter().flatten().map(|(name, _)| name.as_str()) + } +} + +/// The arrowhead entries of a stroke's dictionary that [`stroke_arrows`] reads. Beside heads, any +/// other entry whose key starts with `BSArrow` isn't read, so the stroke keeps its drawn look. +const ARROW_ENTRIES: [&str; 4] = ["BSArrowBeginSymbol", "BSArrowEndSymbol", "BSArrowBeginScale", "BSArrowEndScale"]; + +/// The scales an arrowhead takes, in percent. +const ARROW_SCALES: std::ops::RangeInclusive = 1.0..=1000.0; + /// A fill's or stroke's own state in the stack. #[derive(Clone, Debug, PartialEq)] pub(super) struct ItemLook { @@ -320,6 +348,9 @@ struct Filter { /// The plug-in object it refers to (`/GObjRef : (name) (plug-in) /PluginObject`): its name and /// plug-in name. plugin_object: Option<(String, String)>, + /// The symbols its dictionary refers to (`/GObjRef : (name) /SymbolArt ; (key) ,`): each one's + /// name, by key. + symbols: HashMap, /// `mode opacity … Xy`. xy: Option<(usize, f32)>, /// `… isolate knockout … Xy`. @@ -352,6 +383,7 @@ impl Default for Filter { pattern: None, fill_last: LastPaint::None, plugin_object: None, + symbols: HashMap::new(), xy: None, xy_group: None, data: None, @@ -533,6 +565,11 @@ pub(super) fn art_styles_in(data: &[u8], names: &mut Names) -> HashMap dict_array = Some(vec![]), + // A symbol the dictionary refers to: `/GObjRef : (name) /SymbolArt ; (key) ,`. + b"SymbolArt" => { + symbol_entry(&mut lex, &mut operands, &mut other_entry, names, filters.last_mut().filter(|_| in_basic)); + continue; + } b"PluginObject" if in_basic => { let mut texts = operands.iter().rev().filter_map(|v| names.text(v)); if let (Some(plugin), Some(name), Some(f)) = (texts.next(), texts.next(), filters.last_mut()) { @@ -891,6 +928,7 @@ impl OnePaint { profile: None, align: StrokeAlign::Center, brush: None, + arrows: None, }), _ => return Err(()), } @@ -1485,11 +1523,68 @@ fn stroke_item(f: &Filter, align: StrokeAlign) -> Result, ()> profile: width_profile(&f.arrays), align, brush: None, + arrows: stroke_arrows(f)?, })), _ => Err(()), } } +/// The arrowheads of stroke filter `f` ([`StrokeArrows`]; `None` without any). `Err` for heads +/// beside an arrowhead entry [`ARROW_ENTRIES`] doesn't name, a scale that isn't a number in +/// [`ARROW_SCALES`], or a symbol entry with no symbol's name. +fn stroke_arrows(f: &Filter) -> Result>, ()> { + let end = |symbol: &str, scale: &str| -> Result, ()> { + if !f.kinds.contains_key(symbol) { + return Ok(None); + } + let name = f.symbols.get(symbol).ok_or(())?; + let pct = match f.kinds.get(scale) { + None => Some(100.0), + Some(Kind::Real) => entry(f, scale, Kind::Real)?, + Some(_) => entry(f, scale, Kind::Int)?, + }; + Ok(Some((name.clone(), pct.filter(|p| ARROW_SCALES.contains(p)).ok_or(())?))) + }; + let arrows = StrokeArrows { start: end("BSArrowBeginSymbol", "BSArrowBeginScale")?, end: end("BSArrowEndSymbol", "BSArrowEndScale")? }; + if arrows.start.is_none() && arrows.end.is_none() { + return Ok(None); + } + // Another arrowhead entry may change how the heads draw. + if f.kinds.keys().any(|k| k.starts_with("BSArrow") && !ARROW_ENTRIES.contains(&k.as_str())) { + return Err(()); + } + Ok(Some(Box::new(arrows))) +} + +/// A symbol the dictionary of `filter`, the basic filter being read, refers to, +/// `/GObjRef : (name) /SymbolArt ; (key) ,`, whose `/SymbolArt` `lex` has just read (`operands`: +/// the values before it, read by `names`): the symbol's name by its key in [`Filter::symbols`], the +/// key an entry of another kind. Outside a basic filter (`None`) nothing is read. +fn symbol_entry(lex: &mut Lexer, operands: &mut Vec, other_entry: &mut Option>, names: &mut Names, filter: Option<&mut Filter>) { + let Some(f) = filter else { return }; + let symbol = operands.iter().rev().find_map(|v| names.text(v)); + (*other_entry, *operands) = (None, vec![]); + let at = lex.offset(); + // A comment line is no part of the entry. + let mut next = || loop { + match lex.next_token().map(|t| t.tok) { + Some(Tok::Comment(_)) => continue, + tok => return tok, + } + }; + let (close, key) = (next(), next()); + // Anything else is read as it comes (a `/KnownStyle` starting the next style, say). + let (Some(Tok::Word(b";")), Some(Tok::Str(key))) = (close, key) else { + lex.seek(at); + return; + }; + let key = String::from_utf8_lossy(&key).into_owned(); + f.repeated |= f.kinds.insert(key.clone(), Kind::Other).is_some(); + if let Some(symbol) = symbol { + f.symbols.insert(key, symbol); + } +} + /// A Stroke Offset filter `f`: a stroke whose own style is in its dictionary, aligned inside its /// path when `StrokeOffsetInside` is 1 and outside when it is 0 (its `DisplayString` says which). /// `Err` when that switch is missing or not a switch, or for a stroke [`paint_item`] doesn't read. @@ -1552,6 +1647,7 @@ fn calligraphic_stroke(f: &Filter) -> Option { profile: None, align: StrokeAlign::Center, brush: Some((name.clone(), PathBrush::Calligraphic(super::brush::calligraphic(values, variation, codes)))), + arrows: None, }) } @@ -1633,6 +1729,7 @@ fn art_stroke(f: &Filter) -> Option { profile: None, align: StrokeAlign::Center, brush: Some((name.clone(), PathBrush::Art(settings))), + arrows: None, }) } diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index 066473d43e..4719f814f6 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -1558,8 +1558,10 @@ fn a_style_of_one_paint_reads_as_the_fill_and_stroke_its_xd_turns_on() { }; let stroke = "0 R\n0 1 1 0 K\n1 J 2 j 3 w 4 M [2 1]0 d\n"; let Some(Ok(items)) = one(&format!("0 O\n0 0 1 0 k\n{stroke}1 1 Xd\n")) else { panic!("{:?}", one(stroke)) }; - let [StyleItem::Fill(fill), StyleItem::Stroke { paint, width, cap, join, miter, dash, profile: None, align: StrokeAlign::Center, brush: None }] = - items.as_slice() + let [ + StyleItem::Fill(fill), + StyleItem::Stroke { paint, width, cap, join, miter, dash, profile: None, align: StrokeAlign::Center, brush: None, arrows: _ }, + ] = items.as_slice() else { panic!("{items:?}") }; @@ -1600,3 +1602,30 @@ fn a_style_of_one_paint_reads_as_the_fill_and_stroke_its_xd_turns_on() { assert_eq!(one(&paint), Some(Err(())), "{paint}"); } } + +/// A `/SymbolArt` entry cut short (no `; (key)` after it) leaves what follows to be read: here the +/// next style. +#[test] +fn a_symbol_entry_cut_short_leaves_the_next_style_read() { + let stroke = "/BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + /StrokeStyle : 0 R\n0 0 0 1 0 0 0 XA\n0 J 0 j 1 w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n"; + let text = format!( + "/KnownStyle :\n(Cut) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n{stroke}/GObjRef : (W) /SymbolArt\n\ + /KnownStyle :\n(Next) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n{stroke}; /Dict ;\n /Part ,\n;\n" + ); + let styles = art_styles(text.as_bytes()); + assert!(styles.contains_key("Cut") && styles.contains_key("Next"), "{:?}", styles.keys().collect::>()); + assert!(matches!(styles["Next"].items.as_slice(), [StyleItem::Stroke { arrows: None, .. }]), "{:?}", styles["Next"].items); +} + +/// A comment line inside a `/SymbolArt` entry is skipped: the entry is still read. +#[test] +fn a_comment_inside_a_symbol_entry_is_skipped() { + let text = "/KnownStyle :\n(Arrowed) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n\ + /GObjRef : (W) /SymbolArt\n%a comment\n; (BSArrowEndSymbol) ,\n\ + /StrokeStyle : 0 R\n0 0 0 1 0 0 0 XA\n0 J 0 j 1 w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n;\n"; + let styles = art_styles(text.as_bytes()); + let [StyleItem::Stroke { arrows: Some(arrows), .. }] = styles["Arrowed"].items.as_slice() else { panic!("{:?}", styles["Arrowed"].items) }; + assert_eq!(arrows.end, Some(("W".to_string(), 100.0))); +} diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 1c9595ccee..1fcf87e7a0 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -6638,6 +6638,243 @@ fn a_default_style_with_a_stroke_aligned_outside_comes_in() { assert_eq!(a[0].extras().graphic_style, Some(1)); } +/// An arrowhead symbol's art: an unpainted frame, a 1 pt sample of the line from x = −9 to 4 on +/// y = 0, and the head, a filled wedge from x = 2 back to its tip at x = 8, 3 either side. +const WEDGE_ART: &str = "-10 5 m\n10 5 L\n10 -5 L\n-10 -5 L\n-10 5 L\nn\n0 G\n1 w\n-9 0 m\n4 0 l\nS\n0 g\n2 3 m\n8 0 l\n2 -3 l\nf\n"; + +/// The end arrowhead entries of a stroke's dictionary: symbol `Wedge` at 50 %. +const END_WEDGE: &str = "50 /Real (BSArrowEndScale) ,\n/GObjRef : (Wedge) /SymbolArt ; (BSArrowEndSymbol) ,\n"; + +/// An art style named `name`: a black stroke of weight `width` whose stroke dictionary holds +/// `entries`, as a stroke's arrowheads are written. +fn arrow_style(name: &str, entries: &str, width: f64) -> String { + format!( + "/KnownStyle :\n({name}) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n\ + /Dictionary : /NotRecorded ,\n1 /Int (BSAdvStrokeDictionaryVersion) ,\n{entries}; (kAIBeautifulStrokesParamsDictKey) ,\n\ + /StrokeStyle : 0 R\n0 0 0 1 0 0 0 XA\n0 J 0 j {width} w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n\ + /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n" + ) +} + +/// The drawn look of a 2 pt line from (0, 50) to (100, 50) with [`END_WEDGE`] (weight 1) on its end, +/// the tip on the end: the line to 4 before it, under the head from x = 94 to 100, 3 either side. +const END_WEDGE_LOOK: &str = "0 G\n2 w\n0 50 m\n96 50 l\nS\n0 g\n94 53 m\n100 50 l\n94 47 l\nf\n"; + +/// A line from (0, 50) to (100, 50) drawn as `look`, read as itself with the art style `name`. +fn arrowed_line(name: &str, look: &str) -> String { + format!("0 Ae\nu\n{look}U\n%_0 50 m\n%_100 50 L\n%_N\n1 ({name}) XW\n") +} + +/// A file with the arrowhead symbol `Wedge` (art `symbol_art`), the art style `Arrowed` +/// ([`arrow_style`] with `entries` and `width`), listed, and a line drawn with it as `look`. +fn arrowed_file(symbol_art: &str, entries: &str, width: f64, look: &str) -> String { + named_arrowed_file("Wedge", symbol_art, entries, width, look) +} + +/// [`arrowed_file`] with the symbol named `name`. +fn named_arrowed_file(name: &str, symbol_art: &str, entries: &str, width: f64, look: &str) -> String { + format!( + "{}{}{}", + symbols(&symbol(name, symbol_art, 5)), + styles_and_list(&[arrow_style("Arrowed", entries, width)], &["Arrowed"]), + layer(&arrowed_line("Arrowed", look)) + ) +} + +/// The object `r` reads, its path, and its stroke. +fn arrowed(r: &Structure) -> (Arc, vectorcraft_doc::StrokeLayer) { + let a = art(&r.doc); + assert_eq!(a.len(), 1, "{a:#?}"); + assert!(matches!(a[0].kind, NodeKind::Path { .. }), "the object, not its look: {:#?} {:?}", a[0], r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("drawn look")), "{:?}", r.warnings); + let s = a[0].appearance.stroke().expect("a stroke").clone(); + (a[0].clone(), s) +} + +/// The bounds of the area stroke `s` paints along path `n` (its heads included). +fn painted(n: &Node, s: &vectorcraft_doc::StrokeLayer) -> Rect { + let NodeKind::Path { path, rule, .. } = &n.kind else { panic!("a path") }; + vectorcraft_effects::stroke::outline_region(path, *rule, s).bounds().unwrap() +} + +#[test] +fn a_strokes_arrowhead_symbols_are_its_arrowheads() { + // GUARDS: a stroke's arrowheads (#8188) were left out: the line came in without its heads. + use vectorcraft_doc::{ArrowAlign, Arrowhead}; + let r = read_ok(&arrowed_file(WEDGE_ART, END_WEDGE, 2.0, END_WEDGE_LOOK)); + let (object, s) = arrowed(&r); + assert_eq!((s.width, s.arrow_scale, s.arrow_align), (2.0, (100.0, 50.0), ArrowAlign::Tip)); + assert!(s.start_arrow.is_none(), "{:?}", s.start_arrow); + let Some(Arrowhead::Custom(head)) = &s.end_arrow else { panic!("a head of the symbol's art: {:?}", s.end_arrow) }; + assert_eq!(head.name, "Wedge"); + // In head units, one a symbol unit: 6 long from the tip, 3 either side, the line stopping 4 + // back from the tip, where the sample ends. + let b = head.path.bounds().expect("an outline"); + for (got, want) in [(b.x0, 0.0), (b.x1, 6.0), (b.y0, -3.0), (b.y1, 3.0), (head.stop(), 4.0)] { + assert!((got - want).abs() < 1e-6, "{b:?}, stop {}", head.stop()); + } + // Drawn with the tip on the line's end: a head of weight 1 (2 pt at 50 %), 6 pt long. + let end = object.path_data().unwrap().subpaths[0].anchors.last().unwrap().p; + let drawn = painted(&object, &s); + assert!((drawn.x1 - end.x).abs() < 1e-6 && (drawn.height() - 6.0).abs() < 1e-6, "{drawn:?} for an end at {end:?}"); + // The listed graphic style has the head too. + let style = r.doc.graphic_styles[0].appearance.stroke().expect("the style's stroke"); + assert!(matches!(&style.end_arrow, Some(Arrowhead::Custom(h)) if h == head), "{:?}", style.end_arrow); +} + +#[test] +fn a_strokes_start_arrowhead_points_back_and_keeps_its_side() { + use vectorcraft_doc::Arrowhead; + // A head with one barb, below the line in the symbol (its space is y down): on the right of + // the way it points. At the start of a 1 pt line drawn left to right it points left, the barb + // above the line (the file's y up), the line starting 4 in. + let barb = "0 G\n1 w\n-9 0 m\n4 0 l\nS\n0 g\n2 3 m\n8 0 l\n2 0 l\nf\n"; + let entries = "/GObjRef : (Wedge) /SymbolArt ; (BSArrowBeginSymbol) ,\n"; + let look = "0 G\n1 w\n4 50 m\n100 50 l\nS\n0 g\n6 53 m\n0 50 l\n6 50 l\nf\n"; + let r = read_ok(&arrowed_file(barb, entries, 1.0, look)); + let (object, s) = arrowed(&r); + assert_eq!(s.arrow_scale, (100.0, 100.0)); + assert!(s.end_arrow.is_none()); + let Some(Arrowhead::Custom(head)) = &s.start_arrow else { panic!("{:?}", s.start_arrow) }; + let b = head.path.bounds().unwrap(); + assert!(b.y0.abs() < 1e-6 && (b.y1 - 3.0).abs() < 1e-6, "right of the way it points: {b:?}"); + // Drawn: the tip on the start, and 3 pt of head on the barb's side of the line (above it: the + // document's y down) against the line's half point on the other. + let start = object.path_data().unwrap().subpaths[0].anchors.first().unwrap().p; + let drawn = painted(&object, &s); + assert!((drawn.x0 - start.x).abs() < 1e-6, "{drawn:?} for a start at {start:?}"); + assert!((start.y - drawn.y0 - 3.0).abs() < 1e-6 && (drawn.y1 - start.y - 0.5).abs() < 1e-6, "{drawn:?} for a start at {start:?}"); +} + +#[test] +fn a_stroke_takes_both_heads_at_their_own_scales() { + use vectorcraft_doc::Arrowhead; + // The start at 100 % written as a whole number (weight 2: 12 long, 6 either side, the line 8 + // in), the end at 50 %, both of a symbol named in Chinese ("wedge"). + let entries = "100 /Int (BSArrowBeginScale) ,\n/GObjRef : (楔) /SymbolArt ; (BSArrowBeginSymbol) ,\n\ + 50 /Real (BSArrowEndScale) ,\n/GObjRef : (楔) /SymbolArt ; (BSArrowEndSymbol) ,\n"; + let look = "0 G\n2 w\n8 50 m\n96 50 l\nS\n0 g\n12 56 m\n0 50 l\n12 44 l\nf\n94 53 m\n100 50 l\n94 47 l\nf\n"; + let r = read_ok(&named_arrowed_file("楔", WEDGE_ART, entries, 2.0, look)); + let (object, s) = arrowed(&r); + assert_eq!(s.arrow_scale, (100.0, 50.0)); + for head in [&s.start_arrow, &s.end_arrow] { + assert!(matches!(head, Some(Arrowhead::Custom(h)) if h.name == "楔"), "{head:?}"); + } + let drawn = painted(&object, &s); + assert!((drawn.width() - 100.0).abs() < 1e-6 && (drawn.height() - 12.0).abs() < 1e-6, "{drawn:?}"); +} + +#[test] +fn heads_drawn_past_the_path_extend_it() { + use vectorcraft_doc::ArrowAlign; + // The file draws the head's tip 4 past the end (the line's length under it at weight 1): the + // line keeps its length. + let look = "0 G\n2 w\n0 50 m\n100 50 l\nS\n0 g\n98 53 m\n104 50 l\n98 47 l\nf\n"; + let r = read_ok(&arrowed_file(WEDGE_ART, END_WEDGE, 2.0, look)); + let (object, s) = arrowed(&r); + assert_eq!(s.arrow_align, ArrowAlign::Extend); + let end = object.path_data().unwrap().subpaths[0].anchors.last().unwrap().p; + assert!((painted(&object, &s).x1 - end.x - 4.0).abs() < 1e-6); +} + +#[test] +fn arrowheads_this_does_not_read_keep_the_drawn_look() { + let two_lines = format!("{WEDGE_ART}0 G\n1 w\n-9 0 m\n4 0 l\nS\n"); + let no_line = "0 g\n2 3 m\n8 0 l\n2 -3 l\nf\n"; + let thin_line = WEDGE_ART.replace("1 w", "0.5 w"); + let missing = "/GObjRef : (Elsewhere) /SymbolArt ; (BSArrowEndSymbol) ,\n"; + let unknown = format!("{END_WEDGE}1 /Int (BSArrowSomethingElse) ,\n"); + let too_large = "2000 /Real (BSArrowEndScale) ,\n/GObjRef : (Wedge) /SymbolArt ; (BSArrowEndSymbol) ,\n"; + let line_only = "0 G\n2 w\n0 50 m\n100 50 l\nS\n"; + let cases: [(&str, &str, &str, f64, &str); 8] = [ + ("a symbol the file doesn't define", WEDGE_ART, missing, 2.0, END_WEDGE_LOOK), + ("an arrowhead entry this doesn't read", WEDGE_ART, &unknown, 2.0, END_WEDGE_LOOK), + ("a scale out of range", WEDGE_ART, too_large, 2.0, END_WEDGE_LOOK), + ("a head lighter than the least weight drawn", WEDGE_ART, END_WEDGE, 0.25, END_WEDGE_LOOK), + ("a symbol without a sample of the line", no_line, END_WEDGE, 2.0, END_WEDGE_LOOK), + ("a symbol with two samples of the line", &two_lines, END_WEDGE, 2.0, END_WEDGE_LOOK), + ("a sample of the line that isn't 1 pt", &thin_line, END_WEDGE, 2.0, END_WEDGE_LOOK), + ("heads drawn neither on nor past the ends", WEDGE_ART, END_WEDGE, 2.0, line_only), + ]; + for (why, symbol_art, entries, width, look) in cases { + let r = read_ok(&arrowed_file(symbol_art, entries, width, look)); + let a = art(&r.doc); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{why}: {:?} {a:#?}", r.warnings); + assert!(!matches!(a[0].kind, NodeKind::Path { .. }), "{why}: the look, not the object"); + // A graphic style with an arrowhead it doesn't read isn't read either, rather than read + // without its heads. + let headless = |i: &AppearanceItem| matches!(i, AppearanceItem::Stroke(s) if s.end_arrow.is_none()); + let styles: Vec<_> = r.doc.graphic_styles.iter().filter(|g| g.name == "Arrowed").collect(); + assert!(styles.iter().all(|g| !g.appearance.items.iter().any(headless)), "{why}: {styles:?}"); + } +} + +#[test] +fn heads_whose_placement_the_drawn_bounds_leave_open_keep_the_drawn_look() { + // The line bends back so its end, and a head on it either on the end or 4 past it, lie inside + // the bounds of its earlier segments: those bounds can't tell the two placements apart. + let path = "%_0 50 m\n%_0 0 L\n%_200 0 L\n%_200 100 L\n%_100 100 L\n%_100 50 L\n%_N\n"; + let look = "0 G\n2 w\n0 50 m\n0 0 l\n200 0 l\n200 100 l\n100 100 l\n100 54 l\nS\n0 g\n97 56 m\n100 50 l\n103 56 l\nf\n"; + let line = format!("0 Ae\nu\n{look}U\n{path}1 (Arrowed) XW\n"); + let file = format!( + "{}{}{}", + symbols(&symbol("Wedge", WEDGE_ART, 5)), + styles_and_list(&[arrow_style("Arrowed", END_WEDGE, 2.0)], &["Arrowed"]), + layer(&line) + ); + let r = read_ok(&file); + let a = art(&r.doc); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?} {a:#?}", r.warnings); + assert!(!matches!(a[0].kind, NodeKind::Path { .. }), "the look, not the object"); +} + +#[test] +fn a_head_that_stays_put_leaves_a_moving_heads_placement_open() { + // The bent line of the test above, its end head moving 4 between the placements, and a start + // head whose line runs to its tip (a stop of 0), which stays put: the bounds still can't tell + // where the end head goes. + let flat = WEDGE_ART.replace("-9 0 m\n4 0 l", "-9 0 m\n8 0 l"); + let entries = format!("50 /Real (BSArrowBeginScale) ,\n/GObjRef : (Flat) /SymbolArt ; (BSArrowBeginSymbol) ,\n{END_WEDGE}"); + let path = "%_0 50 m\n%_0 0 L\n%_200 0 L\n%_200 100 L\n%_100 100 L\n%_100 50 L\n%_N\n"; + let look = + "0 G\n2 w\n0 50 m\n0 0 l\n200 0 l\n200 100 l\n100 100 l\n100 54 l\nS\n0 g\n-3 44 m\n0 50 l\n3 44 l\nf\n97 56 m\n100 50 l\n103 56 l\nf\n"; + let line = format!("0 Ae\nu\n{look}U\n{path}1 (Arrowed) XW\n"); + let file = format!( + "{}{}{}", + symbols(&format!("{}{}", symbol("Wedge", WEDGE_ART, 5), symbol("Flat", &flat, 5))), + styles_and_list(&[arrow_style("Arrowed", &entries, 2.0)], &["Arrowed"]), + layer(&line) + ); + let r = read_ok(&file); + let a = art(&r.doc); + assert!(r.warnings.iter().any(|w| w.contains("drawn look")), "{:?} {a:#?}", r.warnings); + assert!(!matches!(a[0].kind, NodeKind::Path { .. }), "the look, not the object"); +} + +#[test] +fn a_style_library_reads_the_heads_of_symbols_defined_after_its_styles() { + // A graphic style library has no layers, so nothing past its styles reads the heads again. + use vectorcraft_doc::Arrowhead; + let data = stream(&format!( + "%AI9_BeginArtStyles\n{}%AI9_EndArtStyles\n{}%AI9_BeginArtStyleList\n(Arrowed)\n%AI9_EndArtStyleList\n", + arrow_style("Arrowed", END_WEDGE, 2.0), + symbols(&symbol("Wedge", WEDGE_ART, 5)) + )); + let (styles, _) = graphic_styles(data.as_bytes(), false, &mut obj::Names::default()); + let stroke = styles.iter().find(|g| g.name == "Arrowed").and_then(|g| g.appearance.stroke()); + assert!(matches!(stroke.and_then(|s| s.end_arrow.as_ref()), Some(Arrowhead::Custom(h)) if h.name == "Wedge"), "{styles:?}"); +} + +#[test] +fn an_arrowhead_entry_without_heads_leaves_the_stroke_read() { + // Only beside heads does an arrowhead entry this doesn't read keep the drawn look. + let r = read_ok(&arrowed_file(WEDGE_ART, "1 /Int (BSArrowSomethingElse) ,\n", 2.0, "0 G\n2 w\n0 50 m\n100 50 l\nS\n")); + let (_, s) = arrowed(&r); + assert!(s.start_arrow.is_none() && s.end_arrow.is_none()); +} + #[test] fn a_symbol_defined_before_the_art_styles_reads_its_styled_objects() { // GUARDS: objects in a symbol defined ahead of `%AI9_BeginArtStyles` (as Illustrator 24 writes diff --git a/crates/eps/src/print/tests.rs b/crates/eps/src/print/tests.rs index 1aaa0866f8..4c922b25e9 100644 --- a/crates/eps/src/print/tests.rs +++ b/crates/eps/src/print/tests.rs @@ -2,7 +2,7 @@ //! reader reads back. use vectorcraft_color::{ - Color, Freeform, FreeformPoint, Gradient, GradientGeom, GradientKind, GradientPaint, GradientSpread, GradientStop, Paint, Swatch, + Color, Freeform, FreeformPoint, Gradient, GradientGeom, GradientKind, GradientMethod, GradientPaint, GradientSpread, GradientStop, Paint, Swatch, }; use vectorcraft_doc::{Appearance, CharStyle, Document, Node, NodeId, NodeKind, StrokeGradientMode, TextObject}; use vectorcraft_geom::{Affine, Point, Rect, Vec2, shapes}; @@ -311,6 +311,32 @@ fn an_overprinting_diamond_gradient_without_a_frame_keeps_the_ink_below_on_a_pos assert_keeps_the_ink_below(&cases); } +#[test] +fn an_overprinting_gradient_with_stops_written_between_its_stops_keeps_the_ink_below_on_a_postscript_plate() { + // None of the cyan from 0.3 to 0.6: the stops written between those two stops (along a + // Perceptual or hue mix, or at a Classic gradient's off-centre midpoint) are paper white too. + let (inked, none) = (Color::cmyk(0.6, 0.3, 0.0, 0.0), Color::cmyk(0.0, 0.3, 0.0, 0.0)); + let stops = [(0.0, inked), (0.3, none), (0.6, none), (1.0, inked)]; + let c = Point::new(100.0, 50.0); + let around = GradientGeom { start: c, end: c + Vec2::new(70.0, -20.0), aspect: 0.7, focal: None }; + let across = GradientGeom { start: Point::new(30.0, 40.0), end: Point::new(170.0, 60.0), aspect: 1.0, focal: None }; + let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)); + let shapes = [(GradientKind::Linear, across, "linear"), (GradientKind::Radial, around, "radial"), (GradientKind::Diamond, around, "diamond")]; + let mut cases = vec![]; + for method in [GradientMethod::Classic, GradientMethod::Perceptual, GradientMethod::HueClockwise, GradientMethod::HueCounterclockwise] { + for (kind, geom, shape) in shapes { + let mut fill = gradient(kind, &stops, geom, GradientSpread::Pad); + if let Paint::Gradient(g) = &mut fill { + g.gradient.method = method; + g.gradient.stops[1].midpoint = 0.3; + } + cases.push((format!("{shape}, {}", method.label()), overprinting(fill, Paint::None), cyan.clone(), "Cyan")); + } + } + let cases: Vec<_> = cases.iter().map(|(name, art, under, ink)| (name.as_str(), art.clone(), under.clone(), *ink)).collect(); + assert_keeps_the_ink_below(&cases); +} + /// [`keeps_the_ink_below`] for each of `cases` (a name, the art, the paint under it and the ink /// of the plate) at Level 3 and Level 2, with every case that fails named. fn assert_keeps_the_ink_below(cases: &[(&str, Node, Paint, &str)]) { diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 5641900186..1cb52b4559 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -570,6 +570,143 @@ pub fn arc(a: Point, b: Point, slope: f64, closed: bool, _base_along_x: bool) -> PathData::single(SubPath::new(anchors, closed)) } +/// A circular arc from `start` to `end`: its circle's `center` and `radius`, and the turn from +/// `start` to `end` about the center in radians, positive the way the angle `atan2(y, x)` grows +/// (clockwise on the y-down page). The turn is never 0 and never a whole turn. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CircularArc { + pub start: Point, + pub end: Point, + pub center: Point, + pub radius: f64, + pub sweep: f64, +} + +impl CircularArc { + /// The arc from `start` to `end` that passes through `through`. `None` when two of the points + /// are the same or the three lie on one line ([`circle_through`]). + pub fn through(start: Point, end: Point, through: Point) -> Option { + let (center, radius) = circle_through(start, end, through)?; + let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x); + let a = angle(start); + let to_end = (angle(end) - a).rem_euclid(TAU); + let to_through = (angle(through) - a).rem_euclid(TAU); + // The turn that goes past `through` on its way to `end`. + let sweep = if to_through < to_end { to_end } else { to_end - TAU }; + Self::checked(start, end, center, radius, sweep) + } + + /// The arc that leaves `start` heading along `direction` (its tangent there) and ends at + /// `end`. `None` when `start` and `end` are the same, `direction` is zero, or `end` lies on the + /// line through `start` along `direction` (no circle touches that line at `start` and passes + /// through `end`). The same test as [`circle_through`] decides that: twice the area of the + /// triangle `start`, `end` and `start + direction` scaled to the chord's length is at most + /// 10⁻¹⁰ of the chord's length squared. + pub fn leaving(start: Point, direction: Vec2, end: Point) -> Option { + let len = direction.hypot(); + let chord = end - start; + let c2 = chord.hypot2(); + if !(len.is_finite() && len > 0.0 && c2.is_finite() && c2 > 0.0) { + return None; + } + let t = direction / len; + // Twice the triangle's area with the tangent as long as the chord. + let cross = t.cross(chord); + if cross.is_nan() || (cross * c2.sqrt()).abs() <= 1e-10 * c2 { + return None; + } + // The center lies on the normal at `start` on the side `end` is: `start + n * s` with + // `|n * s - chord| = |s|`, so `s = |chord|² / (2 n·chord)`. + let n = Vec2::new(-t.y, t.x); + let s = c2 / (2.0 * n.dot(chord)); + let center = start + n * s; + let radius = s.abs(); + let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x); + let a = angle(start); + let to_end = (angle(end) - a).rem_euclid(TAU); + // Leaving along `t`: the turn grows when `t` points the way the angle grows at `start`. + let grows = Vec2::new(-(start.y - center.y), start.x - center.x).dot(t) > 0.0; + let sweep = if grows { to_end } else { to_end - TAU }; + Self::checked(start, end, center, radius, sweep) + } + + /// The arc that ends at `end` arriving along `direction` and starts at `start`: [`Self::leaving`] + /// from `end` back along `-direction`, turned round. + pub fn arriving(start: Point, end: Point, direction: Vec2) -> Option { + let back = Self::leaving(end, -direction, start)?; + Some(Self { start, end, center: back.center, radius: back.radius, sweep: -back.sweep }) + } + + fn checked(start: Point, end: Point, center: Point, radius: f64, sweep: f64) -> Option { + let ok = center.is_finite() && radius.is_finite() && radius > 0.0 && sweep.is_finite() && sweep != 0.0 && sweep.abs() < TAU; + ok.then_some(Self { start, end, center, radius, sweep }) + } + + /// The point at `t` (0 at `start`, 1 at `end`) along the arc. + pub fn at(&self, t: f64) -> Point { + let a = (self.start.y - self.center.y).atan2(self.start.x - self.center.x) + self.sweep * t; + Point::new(self.center.x + self.radius * a.cos(), self.center.y + self.radius * a.sin()) + } + + /// The open path of the arc: an anchor at `start`, at `end`, and between them as many smooth + /// anchors, evenly spaced, as keep each cubic piece to a quarter turn at most. The ends are the + /// given points exactly. + pub fn to_path(&self) -> PathData { + let quarter = std::f64::consts::FRAC_PI_2; + // A quarter turn and a hair more is still one piece. + let pieces = ((self.sweep.abs() / quarter) - 1e-9).ceil().clamp(1.0, 4.0) as u32; + let step = self.sweep / f64::from(pieces); + // The handle length of a cubic that follows a circle through the turn `step`, per unit + // of radius; negative when the arc runs the other way. + let k = 4.0 / 3.0 * (step / 4.0).tan(); + let a0 = (self.start.y - self.center.y).atan2(self.start.x - self.center.x); + let mut anchors = Vec::with_capacity(pieces as usize + 1); + for i in 0..=pieces { + let a = a0 + step * f64::from(i); + let p = if i == 0 { + self.start + } else if i == pieces { + self.end + } else { + Point::new(self.center.x + self.radius * a.cos(), self.center.y + self.radius * a.sin()) + }; + // The handle along the tangent the way the arc runs. + let d = Vec2::new(-a.sin(), a.cos()) * (self.radius * k); + let h_in = if i == 0 { p } else { p - d }; + let h_out = if i == pieces { p } else { p + d }; + let kind = if i == 0 || i == pieces { AnchorKind::Corner } else { AnchorKind::Smooth }; + anchors.push(Anchor { p, h_in, h_out, kind }); + } + PathData::single(SubPath::new(anchors, false)) + } + + /// [`Self::to_path`] with a smooth anchor at `via`, a point on the arc such as the one + /// [`Self::through`] passes through, so the path passes through it exactly: the arc to `via` + /// and the arc on from it, each cut into quarter turns at most. A `via` at an end, or off the + /// stretch between the ends, gives [`Self::to_path`]. + pub fn to_path_via(&self, via: Point) -> PathData { + let angle = |p: Point| (p.y - self.center.y).atan2(p.x - self.center.x); + let turn = (angle(via) - angle(self.start)).rem_euclid(TAU); + // The turn from `start` to `via` the way the arc runs. + let to_via = if self.sweep > 0.0 { turn } else { turn - TAU }; + let share = to_via / self.sweep; + if !(share > 0.0 && share < 1.0) || via == self.start || via == self.end { + return self.to_path(); + } + let first = Self { end: via, sweep: to_via, ..*self }.to_path(); + let second = Self { start: via, sweep: self.sweep - to_via, ..*self }.to_path(); + let (Some(a), Some(b)) = (first.subpaths.into_iter().next(), second.subpaths.into_iter().next()) else { return self.to_path() }; + let mut anchors: Vec = a.anchors.iter().copied().collect(); + let mut rest = b.anchors.iter().copied(); + if let (Some(joint), Some(next)) = (anchors.last_mut(), rest.next()) { + joint.h_out = next.h_out; + joint.kind = AnchorKind::Smooth; + } + anchors.extend(rest); + PathData::single(SubPath::new(anchors, false)) + } +} + /// Logarithmic spiral with decay per full wind (`segments` quarter turns). pub fn spiral(center: Point, radius: f64, decay_percent: f64, segments: u32, clockwise: bool) -> PathData { let decay = (decay_percent / 100.0).clamp(0.05, 0.9999); @@ -846,6 +983,144 @@ mod tests { assert!(c.distance(Point::new(4.0, 3.0) + far) < 1e-6 && (radius - 5.0).abs() < 1e-6, "{c:?} {radius}"); } + /// Every point of `path`'s cubics lies on the arc's circle (to 3·10⁻⁴ of the radius, the + /// quarter-turn cubic's error), and the path runs from the arc's start to its end. + fn assert_on_circle(arc: &CircularArc) { + use kurbo::ParamCurve; + let path = arc.to_path(); + let sp = &path.subpaths[0]; + assert!(!sp.closed); + assert_eq!(sp.anchors.first().map(|a| a.p), Some(arc.start)); + assert_eq!(sp.anchors.last().map(|a| a.p), Some(arc.end)); + for seg in path.to_bezpath().segments() { + for i in 0..=8 { + let p = seg.eval(f64::from(i) / 8.0); + assert!((p.distance(arc.center) - arc.radius).abs() <= 3e-4 * arc.radius, "{p:?} off the circle"); + } + } + } + + /// The arc through a third point: from (0, 0) to (8, 0) through (4, -2) (above the chord on the + /// page) bulges up; through (4, 2) it bulges down; each has the circle through the three points + /// and goes past the third point. Through (4, 10) it is the larger part of its circle. + #[test] + fn the_arc_through_a_point_passes_through_it() { + let (a, b) = (Point::ORIGIN, Point::new(8.0, 0.0)); + for (c, major) in + [(Point::new(4.0, -2.0), false), (Point::new(4.0, 2.0), false), (Point::new(4.0, 10.0), true), (Point::new(-1.0, -3.0), true)] + { + let arc = CircularArc::through(a, b, c).unwrap(); + let (center, radius) = circle_through(a, b, c).unwrap(); + assert!(arc.center.distance(center) < 1e-12 && (arc.radius - radius).abs() < 1e-12); + assert_eq!(arc.sweep.abs() > PI, major, "{c:?}: {}", arc.sweep); + // The third point is on the arc: some point along it is the third point. + let nearest = (0..=10_000).map(|i| arc.at(f64::from(i) / 10_000.0).distance(c)).fold(f64::INFINITY, f64::min); + assert!(nearest < 0.01, "{c:?}: {nearest}"); + assert!(arc.at(0.0).distance(a) < 1e-12 && arc.at(1.0).distance(b) < 1e-9); + assert_on_circle(&arc); + } + // A half circle: two pieces, its middle anchor at the third point. + let arc = CircularArc::through(a, b, Point::new(4.0, -4.0)).unwrap(); + let path = arc.to_path(); + assert_eq!(path.subpaths[0].anchors.len(), 3); + assert!(path.subpaths[0].anchors[1].p.distance(Point::new(4.0, -4.0)) < 1e-12); + assert_eq!(path.subpaths[0].anchors[1].kind, AnchorKind::Smooth); + // Almost a whole circle: four pieces. + let arc = CircularArc::through(a, Point::new(0.0, 0.01), Point::new(8.0, 0.0)).unwrap(); + assert_eq!(arc.to_path().subpaths[0].anchors.len(), 5); + assert_on_circle(&arc); + } + + /// With an anchor at the third point, the path passes through it exactly, whichever way the + /// arc runs, even where one cubic would miss it (a quarter turn of radius 1000 misses a point + /// 20° along by about 0.27). Each part keeps to a quarter turn, the anchor there is smooth, and + /// a point at an end leaves the path as `to_path` makes it. + #[test] + fn the_path_via_the_third_point_passes_through_it_exactly() { + let center = Point::new(0.0, 0.0); + let on = |deg: f64| Point::new(1000.0 * deg.to_radians().cos(), 1000.0 * deg.to_radians().sin()); + for (a, b, c) in [(0.0, 90.0, 20.0), (90.0, 0.0, 20.0), (0.0, 300.0, 170.0), (300.0, 0.0, 10.0)] { + let arc = CircularArc::through(on(a), on(b), on(c)).unwrap(); + assert!(arc.center.distance(center) < 1e-6); + let path = arc.to_path_via(on(c)); + let sp = &path.subpaths[0]; + let joint = sp.anchors.iter().find(|x| x.p == on(c)).expect("an anchor at the third point"); + assert_eq!(joint.kind, AnchorKind::Smooth); + assert_eq!((sp.anchors.first().map(|x| x.p), sp.anchors.last().map(|x| x.p)), (Some(arc.start), Some(arc.end))); + // No piece turns more than a quarter turn. + let points: Vec = sp.anchors.iter().map(|x| x.p).collect(); + for w in points.windows(2) { + let (u, v) = (w[0] - arc.center, w[1] - arc.center); + assert!(u.cross(v).atan2(u.dot(v)).abs() <= std::f64::consts::FRAC_PI_2 + 1e-9, "{a} {b} {c}"); + } + use kurbo::ParamCurve; + for seg in path.to_bezpath().segments() { + for i in 0..=8 { + let p = seg.eval(f64::from(i) / 8.0); + assert!((p.distance(arc.center) - arc.radius).abs() <= 0.3, "{p:?} off the circle"); + } + } + } + // A third point a hair from an end is still an anchor. + let near = Point::new(1000.0, 0.0000005); + let arc = CircularArc::through(on(0.0), on(90.0), near).unwrap(); + assert!(arc.to_path_via(near).subpaths[0].anchors.iter().any(|x| x.p == near)); + let arc = CircularArc::through(on(0.0), on(90.0), on(20.0)).unwrap(); + assert_eq!(arc.to_path_via(on(0.0)), arc.to_path()); + assert_eq!(arc.to_path_via(on(180.0)), arc.to_path()); + } + + /// The arc that leaves its start along a direction: from (0, 0) heading up the page (-y) to + /// (8, 0) is the upper half circle about (4, 0); heading down, the lower one. Its tangent at the + /// start is the direction, and arriving at the end mirrors it. + #[test] + fn the_arc_leaving_along_a_direction_has_that_tangent() { + let (a, b) = (Point::ORIGIN, Point::new(8.0, 0.0)); + let up = CircularArc::leaving(a, Vec2::new(0.0, -3.0), b).unwrap(); + assert!(up.center.distance(Point::new(4.0, 0.0)) < 1e-12 && (up.radius - 4.0).abs() < 1e-12); + assert!(up.at(0.5).distance(Point::new(4.0, -4.0)) < 1e-9, "{:?}", up.at(0.5)); + let down = CircularArc::leaving(a, Vec2::new(0.0, 3.0), b).unwrap(); + assert!(down.at(0.5).distance(Point::new(4.0, 4.0)) < 1e-9, "{:?}", down.at(0.5)); + // Leaving at 45° up and right: a quarter circle, tangent along the direction. + for d in [Vec2::new(1.0, -1.0), Vec2::new(1.0, 1.0), Vec2::new(-1.0, -0.2), Vec2::new(-1.0, 3.0)] { + let arc = CircularArc::leaving(a, d, b).unwrap(); + let first = &arc.to_path().subpaths[0].anchors[0]; + let tangent = first.h_out - first.p; + assert!((tangent.normalize().dot(d.normalize()) - 1.0).abs() < 1e-12, "{d:?}: {tangent:?}"); + assert_on_circle(&arc); + // Arriving along a direction at the end: the tangent into the end is the direction. + let arc = CircularArc::arriving(a, b, d).unwrap(); + let last = arc.to_path().subpaths[0].anchors.last().copied().unwrap(); + let tangent = last.p - last.h_in; + assert!((tangent.normalize().dot(d.normalize()) - 1.0).abs() < 1e-12, "{d:?}: {tangent:?}"); + assert_eq!((arc.start, arc.end), (a, b)); + assert_on_circle(&arc); + } + } + + /// No arc for points that are the same, a third point on the chord's line, a zero or not + /// finite direction, or a direction along the chord's line. + #[test] + fn degenerate_points_give_no_arc() { + let (a, b) = (Point::new(1.0, 2.0), Point::new(5.0, 7.0)); + assert_eq!(CircularArc::through(a, a, b), None); + assert_eq!(CircularArc::through(a, b, b), None); + assert_eq!(CircularArc::through(a, b, a.midpoint(b)), None); + assert_eq!(CircularArc::through(a, b, a + (b - a) * 3.0), None); + assert_eq!(CircularArc::through(a, b, Point::new(f64::INFINITY, 0.0)), None); + assert_eq!(CircularArc::leaving(a, Vec2::new(1.0, 0.0), a), None); + assert_eq!(CircularArc::leaving(a, Vec2::ZERO, b), None); + assert_eq!(CircularArc::leaving(a, Vec2::new(f64::NAN, 1.0), b), None); + assert_eq!(CircularArc::leaving(a, b - a, b), None); + assert_eq!(CircularArc::leaving(a, a - b, b), None); + assert_eq!(CircularArc::arriving(a, b, b - a), None); + // Off the line by 10⁻⁴ over a chord of 2000 still makes an arc. + let (p, q) = (Point::new(-1000.0, 0.0), Point::new(1000.0, 0.0)); + assert!(CircularArc::leaving(p, Vec2::new(2000.0, 1e-4), q).is_some()); + // Off the line by 10⁻¹² of the chord is in line: no arc, rather than a circle 10¹² chords wide. + assert_eq!(CircularArc::leaving(p, Vec2::new(1.0, 1e-12), q), None); + } + /// Two points that are the same, or three on one line, give no circle. #[test] fn coincident_or_collinear_points_give_no_circle() { diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index db6c51d47d..593ca61c64 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -29,6 +29,10 @@ impl Default for Headless { } } +/// Desktop UI commands that the app refuses for every control and MCP request, because each one +/// opens another app (`refuse_automation` in `vectorcraft-ui-egui`). `--connect` does not run them. +const KEYBOARD_ONLY: &[&str] = &["attributes.openUrl", "file.export.svg.browser", "file.saveForWeb.browser", "file.showPackage"]; + /// Commands the desktop app adds on top of the engine; the headless backend implements them too so /// `run_command` behaves the same in both modes. const HOST_COMMANDS: &[(&str, &str, &str)] = &[ @@ -157,6 +161,11 @@ impl Headless { None if vectorcraft_engine::find_command(id).is_some() => { self.session.check_params(id, params).map_err(|e| e.to_string())?; } + None if KEYBOARD_ONLY.contains(&id) => { + return Err(format!( + "`{id}` opens another app: only the person at the keyboard can run it in the desktop app; control and MCP requests are refused, `--connect` included" + )); + } None if crate::ui_catalog::UI_COMMANDS.iter().any(|(cid, ..)| *cid == id) => { return Err(format!( "`{id}` is a desktop UI command (`ui: true`); start `vectorcraft --control 7979` and use `vectorcraft-cli mcp --connect`" diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 870f4a23a3..6a95469d92 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -338,6 +338,23 @@ fn headless_command_list_includes_ui_commands() { assert!(text_of(&r).contains("--connect"), "{r}"); } +/// Desktop commands that the app refuses for every automated request are not offered through +/// `--connect`: the headless error says only the person at the keyboard can run them. +#[test] +fn headless_does_not_send_keyboard_only_commands_to_connect() { + let mut s = server(); + rpc(&mut s, 1, "initialize", json!({"protocolVersion": PROTOCOL_VERSION})); + s.handle_line(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#); + for (n, id) in ["attributes.openUrl", "file.export.svg.browser", "file.saveForWeb.browser", "file.showPackage"].iter().enumerate() { + assert!(crate::ui_catalog::UI_COMMANDS.iter().any(|(cid, ..)| cid == id), "{id} is not a desktop UI command"); + let r = call(&mut s, 10 + n as u64, "command_run", json!({"id": id, "params": {}})); + assert_eq!(r["isError"], true, "{id}: {r}"); + let text = text_of(&r); + assert!(text.contains("only the person at the keyboard"), "{id}: {r}"); + assert!(!text.contains("start `vectorcraft --control"), "{id}: {r}"); + } +} + // ---------- headless end-to-end ---------- #[test] diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index d9415a9549..290623b48b 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -687,6 +687,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "{pinned?: bool} keep the Contextual Task Bar where it is instead of following the selection (true), let it follow the selection again from where it is (false) or toggle (omitted), as the bar's More Options menu does; returns the new state", ), ("window.taskBar.reset", "Reset Bar Position", "", "{} unpin the Contextual Task Bar and put it back under the selection"), + ( + "window.taskBar.actions", + "Bar Actions", + "", + "{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}", + ), + ( + "window.taskBar.resetActions", + "Reset Bar Actions", + "", + "{} 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.dock", "Panels", @@ -837,7 +849,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "retype.find", "Find Matching Fonts", "", - "{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does, or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more that is not true or false, is an error and leaves the list as it was; returns what retype.list returns", + "{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns", ), ( "retype.list", @@ -1158,6 +1170,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} open Saturate for the selection (dialog `saturate`, fields `intensity` −100..100, `preview`): previews live, OK runs edit.colors.saturate as one undo step", ), + ( + "ui.proofSetupDialog", + "Customize…", + "", + "{} open View › Proof Setup › Customize (dialog `proofSetup`, fields `device` (\"workingCmyk\", \"cmyk:\" or \"rgb:\": any CMYK or RGB profile), `preserveNumbers`, `intent` (used while preserveNumbers is off), `simulatePaper` and `simulateBlack` (CMYK devices only), `preview` (on): Preview shows the proof on the canvas, OK runs view.proofSetup with these and proof: true, Cancel puts the earlier proof view back; on the desktop only, Save… writes these to a picked proof setup file with view.proofSetup.save and Load… fills them from one with view.proofSetup.read, both starting in the Proof Setups folder (Load… once a save has made it), whose setups View › Proof Setup lists below Customize…)", + ), ( "ui.indexedColorDialog", "Convert to Indexed Color…", @@ -1555,7 +1573,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, 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, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); 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, 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, harmony, harmonyRule, vision}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, 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; 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, harmony, harmonyRule, vision}", ), ( "ui.savePdfDialog", diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 125126790c..1cfb3038cd 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -16,7 +16,11 @@ //! range reaches, or a tab) are point type of their own, and an underline or strikethrough is carried across the space between. //! It is also carried on to the end of the last character's advance. Type on more than one line //! is placed a line at a time: each line is aligned by its own advances and split as a single -//! line is. +//! line is. A character cell runs from the font's OS/2 usWinAscent above the baseline to its +//! usWinDescent below it, and top or bottom aligned text has the top or the bottom of its cells +//! at the reference point. Text drawn in the opaque background mode (the mode a playback starts +//! in) has one rectangle of the background color behind the character cells of each line, as +//! far as its advances reach. //! - Clip regions and clip paths become clipping groups around what they clip; a rectangle around //! the whole picture clips nothing and is left out. //! @@ -541,22 +545,38 @@ impl Mapper { // one for every character: a NUL's advance goes to the character before it, or moves the // start when the string begins with one. let advances = t.dx.len() == t.text.chars().count() && t.dx.iter().all(|d| d.is_finite()); - let (mut s, mut dx, mut lead) = (String::new(), Vec::new(), 0.0f64); + let (mut s, mut dx) = (String::new(), Vec::new()); + // How far before and after its start each character's advances (its own and the NULs' + // after it) reach (text units): an advance may be negative. And the advance of the NULs + // that move the start, with how far they reach. + let mut reach = Vec::new(); + let mut lead = Lead::default(); for (c, d) in t.text.chars().zip(t.dx.iter().map(|d| f64::from(*d)).chain(std::iter::repeat(0.0))) { if c != '\0' { s.push(c); dx.push(d); - } else if let Some(last) = dx.last_mut() { + reach.push((d.min(0.0), d.max(0.0))); + } else if let (Some(last), Some(r)) = (dx.last_mut(), reach.last_mut()) { *last += d; + *r = (r.0.min(*last), r.1.max(*last)); } else { - lead += d; + lead.by += d; + lead.reach = (lead.reach.0.min(lead.by), lead.reach.1.max(lead.by)); } } if !advances { dx.clear(); - lead = 0.0; + reach.clear(); + lead = Lead::default(); } - if s.trim().is_empty() || t.color[3] == 0 { + // The leading NULs, of the text or of a string of NULs alone. + let first = lead; + // Type that draws nothing still fills its character cells on an opaque background. + let background = t.background.filter(|c| c[3] > 0); + let shows = !s.trim().is_empty() && t.color[3] > 0; + // A string of NULs only fills the cells across its advances. + let nuls = s.is_empty() && first.reach.0 < first.reach.1 && background.is_some(); + if (s.is_empty() && !nuls) || !(shows || background.is_some()) { return; } // Text space → document without the move: its vertical scale gives the type size, and what @@ -613,11 +633,26 @@ impl Mapper { if !dx.is_empty() { style.kerning = Some(0.0); } - // Where the baseline is below the reference point. + // The character cell above and below the baseline (points): the face's OS/2 usWinAscent + // and usWinDescent at the type size (its own ascent and descent when it has no OS/2 + // table), as tall as a positive height asks. + let cell = face + .as_ref() + .map(|face| { + let (a, d) = face.win_ascent_descent().unwrap_or_else(|| face.vertical_metrics()); + (a / face.units_per_em() * size, d / face.units_per_em() * size) + }) + .filter(|(a, d)| a.is_finite() && d.is_finite() && *a >= 0.0 && *d >= 0.0 && a + d > 0.0) + .unwrap_or_else(|| { + let c = if h > 0.0 { size / 0.85 } else { size }; + (0.8 * c, 0.2 * c) + }); + // Where the baseline is below the reference point: the top or the bottom of the cell is at + // the reference point. let drop = match t.v_align { VAlign::Baseline => 0.0, - VAlign::Bottom => -0.2 * size, - VAlign::Top => 0.8 * size, + VAlign::Bottom => -cell.1, + VAlign::Top => cell.0, }; let origin = self.xf * Point::new(t.transform[4], t.transform[5]); let base = Affine::translate(origin.to_vec2()) * shape; @@ -633,19 +668,65 @@ impl Mapper { }; let whole = point(&s); let opacity = f32::from(t.color[3]) / 255.0; + let line = Line { + base, + drop, + align: &t.h_align, + decorated: f.underline || f.strike, + shows, + color: t.color, + opacity, + background, + cell, + point: &point, + }; + // The backgrounds of every line and piece, and the type added after them so that none of + // them covers it. + let mut out = TextOut::default(); if dx.is_empty() { let mut text = whole; + let laid = vectorcraft_text::layout(db, &text); text.xf = base * Affine::translate((0.0, drop)); - text.cached_bounds = Some(vectorcraft_text::layout(db, &text).bounds); - let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text))); - n.opacity = opacity; - self.push(chain, n); - return; + text.cached_bounds = Some(laid.bounds); + if background.is_some() { + // How far one line's glyphs reach each way, and the sum of their advances, its + // trailing blanks included. + let along = laid.glyphs.iter().fold((f64::INFINITY, f64::NEG_INFINITY, 0.0), |(from, to, width), g| { + let (a, b) = (g.origin.x, g.origin.x + g.advance); + (from.min(a.min(b)), to.max(a.max(b)), width + g.advance) + }); + let one = laid.lines.len() == 1 && along.0.is_finite() && along.1.is_finite() && along.2.is_finite(); + // The cells of one line run as far as its glyphs' advances reach, or for blanks + // alone, which draw no type, where the alignment puts a line that long. + // Those of more than one line run across each line's glyphs. NULs alone span + // their advances, where the alignment puts them. + let cells = if nuls { + let start = aligned(first.by * k, 0.0, &t.h_align) - first.by * k; + cell_rect(start + first.reach.0 * k, start + first.reach.1 * k, 0.0, cell) + } else if one { + let (x0, x1) = if shows { + (along.0, along.1) + } else { + let x0 = aligned(0.0, along.2, &t.h_align); + (x0, x0 + along.2) + }; + cell_rect(x0, x1, laid.glyphs.first().map_or(0.0, |g| g.origin.y), cell) + } else { + cells(&laid, &s, cell, &t.h_align, shows && line.decorated) + }; + out.backs.extend(self.background(&line, cells, text.xf)); + } + if shows { + let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text))); + n.opacity = opacity; + out.texts.push(n); + } + return self.add_text(&chain, out); } // Text units grow by `k` along the baseline in the text object's own space. let dx: Vec = dx.iter().map(|d| d * k).collect(); + let reach: Vec<(f64, f64)> = reach.iter().map(|(lo, hi)| (lo * k, hi * k)).collect(); let chars: Vec = s.chars().collect(); - let line = Line { base, drop, align: &t.h_align, decorated: f.underline || f.strike, color: t.color, opacity, point: &point, chain: &chain }; // Type on more than one line is placed a line at a time, each line aligned by its own // advances (layout leaves the tracking after a line's last character out of the width it // aligns, and each line ends with its own) and its underline carried on to its own end. @@ -655,25 +736,68 @@ impl Mapper { // a search. let starts: Vec = s.char_indices().map(|(at, _)| at).collect(); let count = |to: usize| starts.partition_point(|at| *at < to); - let first = laid.lines.first().map_or(0.0, |l| l.baseline); + let top = laid.lines.first().map_or(0.0, |l| l.baseline); for (n, l) in laid.lines.iter().enumerate() { let (from, to) = (count(l.start), count(l.end)); - let (Some(cs), Some(dx)) = (chars.get(from..to), dx.get(from..to)) else { continue }; + let (Some(cs), Some(dx), Some(reach)) = (chars.get(from..to), dx.get(from..to), reach.get(from..to)) else { continue }; // A leading NUL's advance comes before the first line only. - let lead = if n == 0 { lead * k } else { 0.0 }; - let down = l.baseline - first; - self.line(&line, cs, dx, lead, if down.is_finite() { down } else { 0.0 }); + let lead = if n == 0 { first.scaled(k) } else { Lead::default() }; + let down = l.baseline - top; + self.line(&line, cs, Advances { dx, reach, lead }, if down.is_finite() { down } else { 0.0 }, &mut out); } } else { - self.line(&line, &chars, &dx, lead * k, 0.0); + self.line(&line, &chars, Advances { dx: &dx, reach: &reach, lead: first.scaled(k) }, 0.0, &mut out); + } + self.add_text(&chain, out); + } + + /// Adds a text record's backgrounds and then its type, leaving out backgrounds when there is + /// no room for both. + fn add_text(&mut self, chain: &[Arc], out: TextOut) { + let TextOut { mut backs, texts } = out; + let keep = MAX_NODES.saturating_sub(self.out.len()).saturating_sub(texts.len()); + if backs.len() > keep { + backs.truncate(keep); + self.warn(TOO_MANY); + } + for n in backs.into_iter().chain(texts) { + self.push(chain.to_vec(), n); } } - /// One line of text with advances `dx` (points along the baseline) for its characters `chars`, - /// `down` below the first line's baseline: in pieces, each a text object of its own, a new - /// piece after each cluster that tracking can't space by its advance. - fn line(&mut self, line: &Line, chars: &[char], dx: &[f64], lead: f64, down: f64) { - if chars.is_empty() || (chars.iter().all(|c| c.is_whitespace()) && !line.decorated) { + /// Character cells `cells`, placed by `xf`, filled with the line's background when it has one. + fn background(&self, line: &Line, mut cells: BezPath, xf: Affine) -> Option { + let bg = line.background?; + if cells.elements().is_empty() { + return None; + } + cells.apply_affine(xf); + self.path_node(cells, Some(bg), None, false) + } + + /// One line of text with advances `adv` (points along the baseline) for its characters + /// `chars`, `down` below the first line's baseline: in pieces, each a text object of its own, + /// a new piece after each cluster that tracking can't space by its advance. + fn line(&mut self, line: &Line, chars: &[char], adv: Advances, down: f64, out: &mut TextOut) { + let Advances { dx, reach, lead } = adv; + // The line's cells, one rectangle behind every piece, run as far each way as its + // advances reach (an advance may be negative), from where the leading NULs' advances + // start, which the alignment puts where it puts a line as long as its advances. A line + // of leading NULs alone fills the cells across their advances. + let start = aligned(lead.by, dx.iter().sum(), line.align); + if line.background.is_some() { + let (mut lo, mut hi, mut pos) = (lead.reach.0 - lead.by, lead.reach.1 - lead.by, 0.0f64); + for (d, r) in dx.iter().zip(reach) { + (lo, hi) = (lo.min(pos + r.0), hi.max(pos + r.1)); + pos += d; + } + let xf = line.base * Affine::translate((0.0, line.drop + down)); + out.backs.extend(self.background(line, cell_rect(start + lo, start + hi, 0.0, line.cell), xf)); + } + let blank = |cs: &[char]| cs.iter().all(|c| c.is_whitespace()); + // A piece's type draws when it shows: blanks only when underlined or struck through. + let draws = |cs: &[char]| line.shows && (!blank(cs) || line.decorated); + if chars.is_empty() || !draws(chars) { return; } let db = vectorcraft_text::FontDb::global(); @@ -684,13 +808,13 @@ impl Mapper { // Along the baseline (the text object's own space), where the next piece starts from the // reference point: the line as long as its advances (a leading NUL's included), where the // alignment puts it. - let mut at = aligned(lead, dx.iter().sum(), line.align); + let mut at = start; let last = pieces.len().saturating_sub(1); for (i, (from, to)) in pieces.into_iter().enumerate() { - let piece: String = chars.get(from..to).unwrap_or_default().iter().collect(); + let cs = chars.get(from..to).unwrap_or_default(); + let piece: String = cs.iter().collect(); let dx = dx.get(from..to).unwrap_or_default(); - // Blanks of their own draw nothing unless they are underlined or struck through. - if piece.trim().is_empty() && !line.decorated { + if !draws(cs) { at += dx.iter().sum::(); continue; } @@ -715,12 +839,12 @@ impl Mapper { let gap = if (split && i < last) || (i == last && line.decorated) { gaps(&laid, db, &text, x0 + span) } else { BezPath::new() }; let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text.clone()))); n.opacity = line.opacity; - self.push(line.chain.to_vec(), n); + out.texts.push(n); if !gap.elements().is_empty() { let mut gap = gap; gap.apply_affine(text.xf); if let Some(n) = self.path_node(gap, Some(line.color), None, false) { - self.push(line.chain.to_vec(), n); + out.texts.push(n); } } } @@ -785,16 +909,95 @@ fn aligned(lead: f64, span: f64, align: &HAlign) -> f64 { /// What every piece of a text record's lines shares: the text space (`base`, with the baseline /// `drop` below the reference point), the alignment, whether the type is underlined or struck -/// through, its color and opacity, a point type object of a string in its style, and its clips. +/// through, whether the type shows, its color and opacity, its background and the character cell +/// above and below the baseline (points), and a point type object of a string in its style. struct Line<'a> { base: Affine, drop: f64, align: &'a HAlign, decorated: bool, + shows: bool, color: [u8; 4], opacity: f32, + background: Option<[u8; 4]>, + cell: (f64, f64), point: &'a dyn Fn(&str) -> TextObject, - chain: &'a [Arc], +} + +/// What a text record draws: the backgrounds behind its character cells, and its type (with the +/// bars that carry an underline or strikethrough on), added after them. +#[derive(Default)] +struct TextOut { + backs: Vec, + texts: Vec, +} + +/// One line's advances (points along the baseline): each character's own, how far before and +/// after its start the advances from it to the next character reach, and the leading NULs'. +struct Advances<'a> { + dx: &'a [f64], + reach: &'a [(f64, f64)], + lead: Lead, +} + +/// The NULs that move a line's start: their advance, and how far before and after the line's +/// start they reach. +#[derive(Clone, Copy, Default)] +struct Lead { + by: f64, + reach: (f64, f64), +} + +impl Lead { + /// The same NULs with their advances grown by `k`. + fn scaled(self, k: f64) -> Lead { + Lead { by: self.by * k, reach: (self.reach.0 * k, self.reach.1 * k) } + } +} + +/// The character cell from `x0` to `x1` along a baseline at `y`, `cell.0` above and `cell.1` +/// below it (points); empty when it has no area. +fn cell_rect(x0: f64, x1: f64, y: f64, cell: (f64, f64)) -> BezPath { + let r = Rect::new(x0, y - cell.0, x1, y + cell.1).abs(); + if r.width() > 0.0 && r.height() > 0.0 && r.is_finite() { shapes::rectangle(r).to_bezpath() } else { BezPath::new() } +} + +/// The character cells of `laid` (the type `s` laid out on more than one line), `cell.0` above +/// and `cell.1` below each baseline (points), as one rectangle a line: across the line as layout +/// places it and across its glyphs' advances, its trailing blanks included (layout leaves them +/// out of the width it aligns). A line of blanks alone runs across its glyphs' advances when +/// the type draws its underline or strikethrough (`decorated`), and otherwise as wide as their +/// advances, where `align` puts a line that long. +fn cells(laid: &vectorcraft_text::TextLayout, s: &str, cell: (f64, f64), align: &HAlign, decorated: bool) -> BezPath { + // Each line's baseline, the sum of its glyphs' advances, how far before and after the + // reference point they reach, and whether they are all blanks. Glyphs come line by line. + type Row = (usize, f64, f64, (f64, f64), bool); + let mut lines: Vec = Vec::new(); + for g in &laid.glyphs { + let blank = s.get(g.byte..).and_then(|r| r.chars().next()).is_none_or(char::is_whitespace); + let (from, to) = (g.origin.x.min(g.origin.x + g.advance), g.origin.x.max(g.origin.x + g.advance)); + match lines.last_mut() { + Some((line, _, width, reach, all)) if *line == g.line => { + *width += g.advance; + *reach = (reach.0.min(from), reach.1.max(to)); + *all &= blank; + } + _ => lines.push((g.line, g.origin.y, g.advance, (from, to), blank)), + } + } + let mut bp = BezPath::new(); + for (line, y, width, reach, blank) in lines { + let (x0, x1) = match laid.lines.get(line) { + Some(l) if !blank => (l.x0.min(reach.0), l.x1.max(reach.1)), + _ if decorated => reach, + _ => { + let x0 = aligned(0.0, width, align); + (x0, x0 + width) + } + }; + bp.extend(cell_rect(x0, x1, y, cell)); + } + bp } /// The most times [`advanced`] lays the type out again to correct its tracking. diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 01883c740b..217b962dbe 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -274,7 +274,9 @@ fn hand_built_emf_plays_like_gdi() { let lines = &children[1]; assert_eq!(lines.appearance.items.len(), 1); assert!(near(lines.geometric_bounds().unwrap(), Rect::new(0.0, 0.0, 5.0 * mm, 5.0 * mm), 0.01)); - let NodeKind::Text(t) = &children[2].kind else { panic!("text") }; + // The background mode starts opaque: the text's cells are filled white behind it. + assert_eq!(fill_rgb(&children[2]), Some([255, 255, 255])); + let NodeKind::Text(t) = &children[3].kind else { panic!("text") }; assert_eq!(t.plain_text(), "Hi"); let st = &t.runs[0].style; assert_eq!((st.font_family.as_str(), st.font_style.as_str()), ("Arial", "Bold")); @@ -884,6 +886,38 @@ fn wmf_font_width_becomes_horizontal_scale() { assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale); } +#[test] +fn wmf_text_fills_its_cells_in_the_opaque_background_mode() { + // CREATEFONTINDIRECT and SELECTOBJECT: a 0.1 inch em; SETBKCOLOR green; SETBKMODE `mode` + // (none when 0); TEXTOUT "Hi" at (720, 360), top aligned. + let backgrounds = |mode: i16| { + let mut font = le16(&[-144, 0, 0, 0, 400]); + font.extend([0u8; 8]); + font.extend(b"Source Sans 3".iter().copied().chain(std::iter::repeat_n(0, 19))); + let mut text = le16(&[2]); + text.extend(b"Hi"); + text.extend(le16(&[360, 720])); + let mut records = vec![(0x02FB, font), (0x012D, le16(&[0])), (0x0201, 0x0000_ff00u32.to_le_bytes().to_vec())]; + if mode != 0 { + records.push((0x0102, le16(&[mode, 0]))); + } + records.push((0x0521, text)); + paths(&import(&hand_wmf(1440, 1440, &records)).unwrap().document) + }; + let mm = 72.0 / 25.4; + // A file that never sets the mode, and one that sets OPAQUE: one green rectangle whose top + // is at the reference point and whose left edge is at the start of the text. + for mode in [0, 2] { + let p = backgrounds(mode); + assert_eq!(p.len(), 1, "{mode}"); + assert_eq!(fill_rgb(&p[0]), Some([0, 255, 0]), "{mode}"); + let b = p[0].geometric_bounds().unwrap(); + assert!((b.x0 - 12.7 * mm).abs() < 0.01 && (b.y0 - 6.35 * mm).abs() < 0.01 && b.x1 > b.x0 && b.y1 > b.y0, "{mode}: {b:?}"); + } + // TRANSPARENT: no background. + assert!(backgrounds(1).is_empty()); +} + #[test] fn a_clip_whose_box_holds_the_picture_still_clips() { // A diamond around the middle of the picture, whose box holds the whole frame but which cuts @@ -1001,7 +1035,8 @@ fn clipped_text_is_clipped_to_its_rectangle() { let mut font = le(&[2, -1000, 0, 0, 0, 400]); font.extend([0, 1, 1, 0, 0, 0, 0, 0]); font.extend("Arial".encode_utf16().chain(std::iter::repeat_n(0, 27)).flat_map(u16::to_le_bytes)); - let mut records = vec![(82, font), (37, le(&[2])), (84, text)]; + // SETBKMODE TRANSPARENT: no background behind the text. + let mut records = vec![(18, le(&[1])), (82, font), (37, le(&[2])), (84, text)]; let back = import(&hand_emf(5000, 3000, &records)).unwrap(); let layer = back.document.layers[0].children().unwrap(); assert_eq!(layer.len(), 1); @@ -1030,6 +1065,156 @@ fn clipped_text_is_clipped_to_its_rectangle() { assert!(matches!(children[1].kind, NodeKind::Text(_))); } +/// The layer of an EMF that sets the background color green, the background mode `mode` (none +/// when 0) and the text alignment `align`, then draws `s` at (`x`, 1500) in `font` with the +/// advances `dx`. +fn on_background(mode: i32, align: i32, x: i32, font: Vec, s: &str, dx: &[i32]) -> Vec> { + let mut records = vec![(25, le(&[0x0000_ff00])), (22, le(&[align])), (82, font), (37, le(&[2])), (84, text_out(x, s, dx))]; + if mode > 0 { + records.insert(0, (18, le(&[mode]))); + } + import(&hand_emf(5000, 3000, &records)).unwrap().document.layers[0].children().unwrap().clone() +} + +#[test] +fn opaque_backgrounds_fill_behind_the_character_cells() { + let mm = 72.0 / 25.4; + let aligned = on_background; + // TA_BASELINE: the baseline at (10, 15) mm. + let drawn = |mode: i32, font: Vec, s: &str, dx: &[i32]| aligned(mode, 24, 1000, font, s, dx); + let opaque = |font: Vec, s: &str, dx: &[i32]| drawn(2, font, s, dx); + // "Hi" with advances of 20 and 10 mm in a 10 mm em: the cells run across the advances, from + // the face's usWinAscent above the baseline to its usWinDescent below it, behind the type. + let layer = opaque(arial(), "Hi", &[2000, 1000]); + assert_eq!(layer.len(), 2); + assert_eq!(fill_rgb(&layer[0]), Some([0, 255, 0])); + let NodeKind::Text(t) = &layer[1].kind else { panic!("text") }; + let face = vectorcraft_text::FontDb::global().style_face(&t.runs[0].style).unwrap(); + let (a, d) = face.win_ascent_descent().unwrap(); + let em = face.units_per_em(); + let b = layer[0].geometric_bounds().unwrap(); + assert!(near(b, Rect::new(10.0 * mm, (15.0 - 10.0 * a / em) * mm, 40.0 * mm, (15.0 + 10.0 * d / em) * mm), 0.01), "{b:?}"); + // TA_TOP and TA_BOTTOM put the top and the bottom of the cell at the reference point: the + // baseline is usWinAscent below it, or usWinDescent above it. + for (align, top) in [(0, 15.0), (8, 15.0 - 10.0 * (a + d) / em)] { + let layer = aligned(2, align, 1000, arial(), "Hi", &[2000, 1000]); + let b = layer[0].geometric_bounds().unwrap(); + assert!((b.y0 - top * mm).abs() < 0.01 && (b.height() - 10.0 * (a + d) / em * mm).abs() < 0.01, "{align}: {b:?}"); + let NodeKind::Text(t) = &layer[1].kind else { panic!("text") }; + let baseline = (t.xf * vectorcraft_geom::Point::ZERO).y; + assert!((baseline - (top + 10.0 * a / em) * mm).abs() < 0.01, "{align}: {baseline}"); + } + // A leading NUL's advance is filled too: right aligned at 50 mm, "\0Hi" fills from 10 mm. + let b = aligned(2, 26, 5000, arial(), "\0Hi", &[1000, 2000, 1000])[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 50.0 * mm).abs() < 0.01, "{b:?}"); + // A positive height is the cell: 10 mm from top to bottom. + let mut font = le(&[2, 1000, 0, 0, 0, 400]); + font.extend([0; 8]); + font.extend("Arial".encode_utf16().chain(std::iter::repeat_n(0, 27)).flat_map(u16::to_le_bytes)); + let b = opaque(font, "Hi", &[2000, 1000])[0].geometric_bounds().unwrap(); + assert!((b.height() - 10.0 * mm).abs() < 0.01, "{b:?}"); + // Without advances the cells run across the glyphs' own advances. + let layer = opaque(arial(), "Hi", &[]); + let NodeKind::Text(t) = &layer[1].kind else { panic!("text") }; + let (xs, end) = glyph_xs(t); + let b = layer[0].geometric_bounds().unwrap(); + assert!((b.x0 - xs[0]).abs() < 0.01 && (b.x1 - end).abs() < 0.01, "{b:?} {xs:?} {end}"); + // Type split where an advance is further than tracking reaches: one background across the + // whole line's advances comes before both pieces of type. + let layer = opaque(arial(), "Hiy", &[12000, 500, 1000]); + let kinds: Vec = layer.iter().map(|n| matches!(n.kind, NodeKind::Text(_))).collect(); + assert_eq!(kinds, [false, true, true]); + let b = layer[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 145.0 * mm).abs() < 0.01, "{b:?}"); +} + +#[test] +fn opaque_backgrounds_reach_as_far_as_the_advances() { + let mm = 72.0 / 25.4; + let aligned = on_background; + // TA_BASELINE: the baseline at (10, 15) mm. + let drawn = |mode: i32, font: Vec, s: &str, dx: &[i32]| aligned(mode, 24, 1000, font, s, dx); + let opaque = |font: Vec, s: &str, dx: &[i32]| drawn(2, font, s, dx); + // Two lines: a rectangle behind each, not one block over the space between them. + let layer = opaque(arial(), "Hi\nHi", &[]); + let NodeKind::Path { path, .. } = &layer[0].kind else { panic!("a path") }; + let rects = path.to_bezpath().elements().iter().filter(|e| matches!(e, vectorcraft_geom::PathEl::MoveTo(_))).count(); + assert_eq!(rects, 2); + // Without advances, one line's cells run across its glyphs' advances, trailing spaces + // included: right aligned, they run from the "H" to the end of the space after the "i". + let layer = aligned(2, 26, 4000, arial(), "Hi ", &[]); + let NodeKind::Text(t) = &layer[1].kind else { panic!("text") }; + let (xs, end) = glyph_xs(t); + let b = layer[0].geometric_bounds().unwrap(); + assert!(xs.len() == 3, "{xs:?} {end}"); + assert!((b.x0 - xs[0]).abs() < 0.01 && (b.x1 - end).abs() < 0.01, "{b:?} {xs:?} {end}"); + // Layout aligns a line without its trailing spaces: right aligned at 40 mm, the space after + // the "i" runs on past it. On more than one line, the cells also run across the trailing + // spaces, as far as on one line. + assert!(end > 41.0 * mm, "{end}"); + let b = aligned(2, 26, 4000, arial(), "Hi \nHi", &[])[0].geometric_bounds().unwrap(); + assert!((b.x1 - end).abs() < 0.01, "{b:?} {end}"); + // Leading NULs on a line of their own fill their cells across their advances, before the + // next line: from 10 to 30 mm. + let layer = opaque(arial(), "\0\nA", &[2000, 0, 1000]); + let first = layer[0].geometric_bounds().unwrap(); + assert!((first.x0 - 10.0 * mm).abs() < 0.01 && (first.x1 - 30.0 * mm).abs() < 0.01, "{first:?}"); + assert!(matches!(layer[1].kind, NodeKind::Path { .. }) && matches!(layer[2].kind, NodeKind::Text(_)), "{layer:?}"); + // An underlined line of blanks between two others draws its bar across its glyphs, and its + // cells run across the same glyphs. + let layer = opaque(font_of("Arial", true), "A\n \nB", &[]); + let (NodeKind::Path { path, .. }, NodeKind::Text(t)) = (&layer[0].kind, &layer[1].kind) else { panic!("a path and type") }; + let mut rects: Vec<(f64, f64, f64)> = Vec::new(); + for el in path.to_bezpath().elements() { + let p = match el { + vectorcraft_geom::PathEl::MoveTo(p) => { + rects.push((p.x, p.x, p.y)); + *p + } + vectorcraft_geom::PathEl::LineTo(p) => *p, + _ => continue, + }; + if let Some(r) = rects.last_mut() { + *r = (r.0.min(p.x), r.1.max(p.x), r.2.min(p.y)); + } + } + rects.sort_by(|a, b| a.2.total_cmp(&b.2)); + let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let spaces: Vec<(f64, f64)> = + laid.glyphs.iter().filter(|g| g.line == 1).map(|g| ((t.xf * g.origin).x, (t.xf * g.origin).x + g.advance)).collect(); + let (from, to) = spaces.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), (x0, x1)| (a.min(*x0), b.max(*x1))); + assert!(rects.len() == 3 && (rects[1].0 - from).abs() < 0.01 && (rects[1].1 - to).abs() < 0.01, "{rects:?} {spaces:?}"); + // NULs whose advances go forward and back again still fill as far as they reach. + let layer = opaque(arial(), "\0\0", &[1000, -1000]); + assert_eq!(layer.len(), 1); + let b = layer[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 20.0 * mm).abs() < 0.01, "{b:?}"); + let b = opaque(arial(), "H\0i", &[3000, -2000, 1000])[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 40.0 * mm).abs() < 0.01, "{b:?}"); + // An advance that goes back: the cells reach as far as the advances go, here to 30 mm. + let b = opaque(arial(), "Hi", &[2000, -1000])[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 30.0 * mm).abs() < 0.01, "{b:?}"); + // NULs alone fill across their advances. + let layer = opaque(arial(), "\0", &[2000]); + assert_eq!(layer.len(), 1); + let b = layer[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && (b.x1 - 30.0 * mm).abs() < 0.01, "{b:?}"); + // Blanks on an opaque background still fill their cells, from the reference point on; on a + // transparent one nothing is left. + let layer = opaque(arial(), " \t", &[]); + assert_eq!(layer.len(), 1); + let b = layer[0].geometric_bounds().unwrap(); + assert!((b.x0 - 10.0 * mm).abs() < 0.01 && b.x1 > 10.0 * mm, "{b:?}"); + assert!(drawn(1, arial(), " \t", &[]).is_empty()); + // NULs alone in an underlined font fill their cells and add no type. + let layer = opaque(font_of("Arial", true), "\0", &[2000]); + assert!(layer.len() == 1 && matches!(layer[0].kind, NodeKind::Path { .. }), "{layer:?}"); + // A file that never sets the mode draws in the opaque mode a playback starts in. + let layer = drawn(0, arial(), "Hi", &[]); + assert_eq!(fill_rgb(&layer[0]), Some([0, 255, 0])); + assert!(drawn(1, arial(), "Hi", &[]).iter().all(|n| matches!(n.kind, NodeKind::Text(_)))); +} + /// The first text object of `d`. fn first_text(d: &Document) -> TextObject { all(d) @@ -1195,8 +1380,8 @@ fn multiline_text_with_advances_aligns_each_line() { } assert!(drops.iter().all(|d| (d - drops[0]).abs() < 0.01), "{drops:?}"); // Underlined and left aligned, each line's underline ends with its own advances: no bar runs on - // past either line. - let records = vec![(82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hi\nHi", &[2000, 1000, 0, 2000, 1000]))]; + // past either line (on a transparent background, SETBKMODE). + let records = vec![(18, le(&[1])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hi\nHi", &[2000, 1000, 0, 2000, 1000]))]; let back = import(&hand_emf(5000, 3000, &records)).unwrap(); assert!(all(&back.document).iter().all(|n| !matches!(n.kind, NodeKind::Path { .. }))); for (align, x, second) in [(6, 2500, [15.0, 30.0]), (2, 4000, [20.0, 35.0])] { @@ -1254,8 +1439,9 @@ fn wmf_text_is_spaced_by_its_advances() { fn split_type_keeps_its_underline_and_right_to_left_order() { let mm = 72.0 / 25.4; // Underlined "Hiy" with an advance further than tracking reaches after the "H": the bar runs on - // from the end of the "H"'s underline to where "iy" starts, at 130 mm. - let records = vec![(82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))]; + // from the end of the "H"'s underline to where "iy" starts, at 130 mm. The background is + // transparent (SETBKMODE) throughout. + let records = vec![(18, le(&[1])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))]; let back = import(&hand_emf(20000, 3000, &records)).unwrap(); assert_eq!(texts_at(&back.document), vec![("H".to_string(), vec![10.0]), ("iy".to_string(), vec![130.0, 135.0])]); let bars: Vec = @@ -1265,7 +1451,7 @@ fn split_type_keeps_its_underline_and_right_to_left_order() { assert!(b.x0 > 10.0 * mm && b.x0 < 130.0 * mm && (b.x1 - 130.0 * mm).abs() < 0.01 && b.height() < 2.0 * mm, "{b:?}"); // The "H" and the "i" before the split are tracked apart and draw a bar each: only the bar that // ends the piece runs on, from the end of the "i" to 130 mm. - let records = vec![(82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[1000, 12000, 1000]))]; + let records = vec![(18, le(&[1])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[1000, 12000, 1000]))]; let back = import(&hand_emf(20000, 3000, &records)).unwrap(); assert_eq!(texts_at(&back.document), vec![("Hi".to_string(), vec![10.0, 20.0]), ("y".to_string(), vec![140.0])]); let gaps: Vec = all(&back.document).into_iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).collect(); @@ -1276,12 +1462,12 @@ fn split_type_keeps_its_underline_and_right_to_left_order() { let b = gaps[0].geometric_bounds().unwrap(); assert!(b.x0 > 20.0 * mm && (b.x1 - 140.0 * mm).abs() < 0.01, "{b:?}"); // Without an underline, nothing but the type. - let records = vec![(82, arial()), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))]; + let records = vec![(18, le(&[1])), (82, arial()), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))]; let back = import(&hand_emf(20000, 3000, &records)).unwrap(); assert!(all(&back.document).iter().all(|n| !matches!(n.kind, NodeKind::Path { .. }))); // A last advance further than tracking reaches, right aligned at 140 mm: the "H" and the "i" // start at 10 and 20 mm, and the underline runs on from the "i" to 140 mm. - let records = vec![(22, le(&[2])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(14000, "Hi", &[1000, 12000]))]; + let records = vec![(18, le(&[1])), (22, le(&[2])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(14000, "Hi", &[1000, 12000]))]; let back = import(&hand_emf(20000, 3000, &records)).unwrap(); assert_eq!(texts_at(&back.document), vec![("Hi".to_string(), vec![10.0, 20.0])]); let bars: Vec = diff --git a/crates/render/src/brush_fx.rs b/crates/render/src/brush_fx.rs index 5844a2ef7f..1660ae6caa 100644 --- a/crates/render/src/brush_fx.rs +++ b/crates/render/src/brush_fx.rs @@ -321,6 +321,64 @@ mod tests { } } + /// A proof that preserves the colors' numbers proofs an art brush's own colors, as it proofs + /// the document's: the brush's blue shows as the simulated device shows that color's numbers. + #[test] + fn a_proof_that_preserves_numbers_proofs_brush_art() { + use vectorcraft_brush::{ArtBrush, ArtScale, Brush, BrushKind, Colorization}; + use vectorcraft_color::cms; + + let mut d = doc_with_line(Some("Blue art"), 1.0); + let blue = Color::rgb(0.0, 0.0, 1.0); + let art = + Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, -10.0, 10.0, 10.0)), Appearance::basic(Paint::solid(blue), Paint::None, 0.0)); + let brush = Brush { + name: "Blue art".into(), + kind: BrushKind::Art(ArtBrush { art, scale: ArtScale::Stretch, colorization: Colorization::None, ..Default::default() }), + }; + vectorcraft_brush::store(&mut d, &[brush]); + let proof = cms::ProofSetup { target: cms::ProofTarget::Cmyk(cms::DEVICE_CMYK.into()), preserve_numbers: true, ..Default::default() }; + let want = cms::active().proof_color(&blue, &proof).map(|v| (v * 255.0).round() as i32); + let opts = RenderOptions { proof: Some(proof), background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut r = Renderer::new(); + for _ in 0..2 { + let px = r.render(&d, 200, 100, Affine::IDENTITY, &opts).pixel(100, 50); + assert!(want != [0, 0, 255], "{want:?}"); + assert!(px.iter().zip(want).all(|(p, w)| (i32::from(*p) - w).abs() <= 2), "{px:?} vs {want:?}"); + } + } + + /// A proof that preserves the colors' numbers keeps the channels a CMYK document's filters run + /// on: an art brush's Color Halftone screens ink channels with the proof on, as with it off. + #[test] + fn a_proof_that_preserves_numbers_keeps_cmyk_filter_channels() { + use vectorcraft_brush::{ArtBrush, ArtScale, Brush, BrushKind, Colorization}; + use vectorcraft_color::cms; + + let mut d = doc_with_line(Some("Halftone art"), 40.0); + d.color_mode = vectorcraft_doc::ColorMode::Cmyk; + let grey = Color::cmyk(0.3, 0.3, 0.3, 0.2); + let mut art = + Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, -10.0, 10.0, 10.0)), Appearance::basic(Paint::solid(grey), Paint::None, 0.0)); + art.appearance.effects = + vec![vectorcraft_doc::Effect { id: "pixelate.colorHalftone".into(), params: serde_json::json!({"maxRadius": 4}), visible: true }]; + let brush = Brush { + name: "Halftone art".into(), + kind: BrushKind::Art(ArtBrush { art, scale: ArtScale::Stretch, colorization: Colorization::None, ..Default::default() }), + }; + vectorcraft_brush::store(&mut d, &[brush]); + let shown = |proof: Option| { + let opts = RenderOptions { proof, background: Some([255, 255, 255, 255]), ..Default::default() }; + Renderer::new().render(&d, 200, 100, Affine::IDENTITY, &opts).pixels + }; + let plain = shown(None); + assert!(plain.chunks(4).any(|p| p[..3] != [255, 255, 255]), "the brush draws"); + // The working CMYK space proofed from its own numbers shows the colors as they are shown. + let proofed = shown(Some(cms::ProofSetup { target: cms::ProofTarget::WorkingCmyk, preserve_numbers: true, ..Default::default() })); + let differ = plain.chunks(4).zip(proofed.chunks(4)).filter(|(a, b)| a.iter().zip(b.iter()).any(|(x, y)| x.abs_diff(*y) > 8)).count(); + assert!(differ * 100 < plain.len() / 4, "{differ} of {} pixels differ", plain.len() / 4); + } + /// Object opacity fades a brushed stroke's art as a whole, with or without a dash and a fill: /// the same as the object at full opacity inside a group at that opacity. #[test] diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index 95f2727386..fe6933fea3 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -124,7 +124,7 @@ impl Renderer { let channels = match f.ink.base() { Ink::Cmy => effects::pixel::Channels::CmyPlane, Ink::K => effects::pixel::Channels::KPlane, - Ink::Display | Ink::RichBlack if f.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk => effects::pixel::Channels::Cmyk, + Ink::Display | Ink::RichBlack | Ink::Proofed(_) if f.doc.color_mode == vectorcraft_doc::ColorMode::Cmyk => effects::pixel::Channels::Cmyk, _ => effects::pixel::Channels::Rgb, }; // What the content reads (as the raster kept for it found it, else found now), with the diff --git a/crates/render/src/ink.rs b/crates/render/src/ink.rs index 7bcc117a23..4d72af8095 100644 --- a/crates/render/src/ink.rs +++ b/crates/render/src/ink.rs @@ -12,6 +12,9 @@ //! colours; RGB colours and placed images are separated into the working CMYK space first. //! //! RGB documents, and CMYK documents without transparency, draw screen colours ([`Ink::Display`]). +//! A proof that preserves the colors' numbers draws each screen colour as the proof shows it +//! ([`Ink::Proofed`]); a CMYK document that blends in CMYK keeps its ink planes, and [`compose`] +//! shows their inks through the proof. use std::cell::RefCell; use std::collections::HashMap; @@ -44,6 +47,10 @@ pub(crate) enum Ink { RichBlack, /// Source-color adjustment before the display/ink conversion. Float bits keep cache keys exact. Darkened(InkSpace, u32, bool), + /// Screen colours as a proof that preserves the colors' numbers shows them + /// ([`crate::proof::preserves`], [`Cms::proof_color`]): the proof [`proofed_ink`] registered + /// under this number, so the caches keep what each proof draws apart. + Proofed(u32), } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -52,6 +59,68 @@ pub(crate) enum InkSpace { Cmy, K, RichBlack, + Proofed(u32), +} + +/// What [`Ink::Proofed`] paints with: its number, the color settings and the proof setup. +type Proof = (u32, Arc, vectorcraft_color::cms::ProofSetup, u64); + +/// The proofs [`proofed_ink`] registered last, the newest last: a few, for renderers drawing with +/// different ones. +static PROOFS: Mutex>> = Mutex::new(Vec::new()); +/// The last number [`proofed_ink`] gave out. +static PROOF_NUMBER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +thread_local! { + /// The proof [`Ink::rgb`] used last on this thread, so a frame does not look it up for each + /// color it paints. + static LAST_PROOF: RefCell>> = const { RefCell::new(None) }; +} + +/// Keeps the proof [`proofed_ink`] registered for a frame while the frame is drawn: a proof that +/// something holds stays registered. +pub(crate) struct ProofHold(#[allow(dead_code)] Arc); + +/// The ink a frame drawn with a proof that preserves the colors' numbers paints screen colours +/// with: the same [`Ink::Proofed`] number for the same proof setup, active color settings and +/// loaded profiles ([`cms::profiles_generation`]), and a new one when any of them changes. The +/// proof stays registered while the hold returned with it is kept. +pub(crate) fn proofed_ink(proof: &vectorcraft_color::cms::ProofSetup) -> (Ink, ProofHold) { + let (c, profiles) = (cms::active(), cms::profiles_generation()); + let mut proofs = PROOFS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(p) = proofs.iter().find(|p| Arc::ptr_eq(&p.1, &c) && p.2 == *proof && p.3 == profiles) { + return (Ink::Proofed(p.0), ProofHold(p.clone())); + } + let number = PROOF_NUMBER.fetch_add(1, Ordering::Relaxed).wrapping_add(1); + // Past a few, the oldest proof nothing holds (no frame, no thread's last proof) goes. + if proofs.len() >= 8 + && let Some(i) = proofs.iter().position(|p| Arc::strong_count(p) == 1) + { + proofs.remove(i); + } + let p = Arc::new((number, c, proof.clone(), profiles)); + proofs.push(p.clone()); + (Ink::Proofed(number), ProofHold(p)) +} + +/// The proof setup `ink` proofs with ([`Ink::Proofed`], darkened or not), while it is registered. +pub(crate) fn proof_of(ink: Ink) -> Option { + let Ink::Proofed(number) = ink.base() else { return None }; + PROOFS.lock().unwrap_or_else(|e| e.into_inner()).iter().find(|p| p.0 == number).map(|p| p.2.clone()) +} + +/// Display sRGB of `c` as the proof [`proofed_ink`] registered under `number` shows it; a proof +/// no longer registered shows the colour as it is. +fn proofed_rgb(number: u32, c: &Color) -> [f32; 3] { + let proof = LAST_PROOF.with(|l| l.borrow().clone().filter(|p| p.0 == number)).or_else(|| { + let p = PROOFS.lock().unwrap_or_else(|e| e.into_inner()).iter().find(|p| p.0 == number).cloned(); + LAST_PROOF.with(|l| l.borrow_mut().clone_from(&p)); + p + }); + match proof { + Some(p) => p.1.proof_color(c, &p.2), + None => c.to_rgb(), + } } impl Ink { @@ -61,6 +130,7 @@ impl Ink { Self::Darkened(InkSpace::Cmy, _, _) => Self::Cmy, Self::Darkened(InkSpace::K, _, _) => Self::K, Self::Darkened(InkSpace::RichBlack, _, _) => Self::RichBlack, + Self::Darkened(InkSpace::Proofed(n), _, _) => Self::Proofed(n), other => other, } } @@ -74,6 +144,11 @@ impl Ink { } } + /// Whether this ink adjusts the source colors first ([`Ink::Darkened`]). + pub(crate) fn is_darkened(self) -> bool { + matches!(self, Self::Darkened(..)) + } + fn darkness(self) -> Option { match self { Self::Darkened(_, bits, _) => Some(f32::from_bits(bits)), @@ -96,6 +171,7 @@ impl Ink { Self::Cmy => InkSpace::Cmy, Self::K => InkSpace::K, Self::RichBlack => InkSpace::RichBlack, + Self::Proofed(n) => InkSpace::Proofed(n), _ => InkSpace::Display, }; Self::Darkened(space, amount.to_bits(), black) @@ -151,6 +227,7 @@ impl Ink { match (self, *c) { (Ink::RichBlack, Color::Cmyk { c, m, y, k }) if is_pure_black([c, m, y, k]) => [0.0; 3], (Ink::Display | Ink::RichBlack, _) => c.to_rgb(), + (Ink::Proofed(n), _) => proofed_rgb(n, c), _ => self.plane(inks(c)), } } @@ -178,7 +255,7 @@ impl Ink { pub(crate) fn fixed8(self, [r, g, b, a]: [u8; 4]) -> [u8; 4] { match self.base() { - Ink::Display | Ink::RichBlack => [r, g, b, a], + Ink::Display | Ink::RichBlack | Ink::Proofed(_) => [r, g, b, a], _ => { let lab = lab::srgb_to_lab([r, g, b].map(|v| v as f32 / 255.0)); let [r, g, b] = self.plane(inks(&Color::Lab { l: lab.l, a: lab.a, b: lab.b })).map(q); @@ -319,6 +396,32 @@ fn cached(slot: &Cached, build: impl FnOnce(&Cms) -> T) -> (Arc, u64) { (t, g) } +/// A table [`proofed_lut`] made, with the color settings, proof setup and profiles generation it +/// was made for. +type ProofedLut = (Arc, vectorcraft_color::cms::ProofSetup, u64, Arc); + +/// The tables [`proofed_lut`] made last, the newest last. +static PROOFED: Mutex> = Mutex::new(Vec::new()); + +/// Ink amounts → their display sRGB as `proof` shows a CMYK color of those inks +/// ([`Cms::proof_color`]), for the active color settings and loaded profiles. Cached. +fn proofed_lut(proof: &vectorcraft_color::cms::ProofSetup) -> Arc { + let (c, profiles) = (cms::active(), cms::profiles_generation()); + let mut kept = PROOFED.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((.., t)) = kept.iter().find(|(o, p, g, _)| Arc::ptr_eq(o, &c) && p == proof && *g == profiles) { + return t.clone(); + } + let t = Arc::new(InkLut(CmykLut::build(|[cy, m, y, k]| { + let [px, py, pz] = lab::srgb_to_xyz(c.proof_color(&Color::Cmyk { c: cy, m, y, k }, proof)); + [px, py, pz, 0.0] + }))); + if kept.len() >= KEPT_TABLES { + kept.remove(0); + } + kept.push((c, proof.clone(), profiles, t.clone())); + t +} + /// [`compose`] puts at least this many pixels in each band but the last. const BAND_PIXELS: usize = 1 << 16; @@ -331,12 +434,19 @@ const BAND_PIXELS: usize = 1 << 16; /// each other band (this thread does when that one can't start). Returns the picture and the number /// of threads that composed it. pub(crate) fn compose(cmy: &[u8], k: &[u8], opts: &RenderOptions, threads: u16) -> (Vec, usize) { - let (lut, _) = cached(&DISPLAY, InkLut::build); - let bg = opts.background.map(|b| (Ink::Cmy.fixed8(b), Ink::K.fixed8(b), b)); + // With a proof that preserves the numbers, the inks show as the proof's device shows them, + // and the background as it shows white paper. + let lut = match crate::proof::preserving(opts) { + Some(p) => proofed_lut(p), + None => cached(&DISPLAY, InkLut::build).0, + }; + let bg = opts.background.map(|b| (Ink::Cmy.fixed8(b), Ink::K.fixed8(b), crate::proof::under_art(opts, b))); let mut out = vec![0; cmy.len().min(k.len()) / 4 * 4]; let pixels = out.len() / 4; let bands = (pixels / BAND_PIXELS).clamp(1, usize::from(threads).max(1)); - let band = |o: &mut [u8], p: &[u8], q: &[u8]| compose_band(o, p, q, &lut, bg, opts.rich_black); + // A proof shows its device's black, not Appearance of Black's rich black. + let rich_black = opts.rich_black && crate::proof::preserving(opts).is_none(); + let band = |o: &mut [u8], p: &[u8], q: &[u8]| compose_band(o, p, q, &lut, bg, rich_black); if bands == 1 { band(&mut out, cmy, k); return (out, 1); @@ -469,9 +579,9 @@ fn plane_key(key: &ImageKey, plane: Ink, generation: u64) -> ImageKey { /// The key [`ink_image`] gives image pixels `key` painted with `ink`. pub(crate) fn ink_key(key: &ImageKey, ink: Ink) -> ImageKey { if ink.darkness().is_some() { - let generation = if matches!(ink.base(), Ink::Display | Ink::RichBlack) { 0 } else { separation().1 }; + let generation = if matches!(ink.base(), Ink::Display | Ink::RichBlack | Ink::Proofed(_)) { 0 } else { separation().1 }; plane_key(key, ink, generation) - } else if matches!(ink, Ink::Display | Ink::RichBlack) { + } else if matches!(ink, Ink::Display | Ink::RichBlack | Ink::Proofed(_)) { key.clone() } else { plane_key(key, ink, separation().1) @@ -489,7 +599,7 @@ fn darkened_image(key: &ImageKey, pm: &Arc, ink: Ink, amount: f32, blob: return (want, p); } let base = ink.base(); - let display = matches!(base, Ink::Display | Ink::RichBlack); + let display = matches!(base, Ink::Display | Ink::RichBlack | Ink::Proofed(_)); let raw_cmyk = key_inks(key, blob).filter(|i| (i.width, i.height) == (u32::from(pm.width()), u32::from(pm.height()))); let sep = (!display).then(separation); let shown = (display && raw_cmyk.is_some()).then(display_lut); @@ -499,7 +609,8 @@ fn darkened_image(key: &ImageKey, pm: &Arc, ink: Ink, amount: f32, blob: continue; } let rgb = if ink.black_endpoint() { - base.rgb(&Color::gray(1.0)) + // Like the other pixels, a proofed black stays in display space; the plates proof it. + if display { Ink::Display } else { base }.rgb(&Color::gray(1.0)) } else if let Some(raw) = raw_cmyk.as_ref().and_then(|v| v.data.as_chunks::<4>().0.get(i)) { let mut inks = raw.map(|v| f32::from(v) / 255.0); inks[3] = (inks[3] + amount).min(1.0); @@ -527,7 +638,7 @@ pub(crate) fn ink_image(key: &ImageKey, pm: &Arc, ink: Ink, blob: Option if let Some(amount) = ink.darkness() { return darkened_image(key, pm, ink, amount, blob, touch); } - if matches!(ink, Ink::Display | Ink::RichBlack) { + if matches!(ink, Ink::Display | Ink::RichBlack | Ink::Proofed(_)) { return (key.clone(), pm.clone()); } let (luts, generation) = separation(); @@ -601,6 +712,38 @@ mod tests { assert_eq!(pm.data()[0].r, 204, "source pixels remain unchanged"); } + /// A fully darkened image drawn with a proof that preserves the colors' numbers shows black as + /// that proof shows it: proofed once, as its other darkened pixels are. + #[test] + fn a_proofed_black_endpoint_image_is_proofed_once() { + // Simulate Black Ink shows black as a gray, so a second proof would lighten it again. + let proof = cms::ProofSetup { target: cms::ProofTarget::WorkingCmyk, preserve_numbers: true, simulate_black: true, ..Default::default() }; + let (ink, _hold) = proofed_ink(&proof); + let dark = ink.darkened(1.0); + assert!(dark.black_endpoint()); + let key = ImageKey { + content: Arc::from("proofed-black-endpoint-regression"), + adjust: None, + grey: false, + tint: None, + ink: Ink::Display, + luts: (0, 0), + plates: 0, + mip: 0, + tile: None, + }; + let pm = Arc::new(Pixmap::from_parts(vec![PremulRgba8 { r: 204, g: 102, b: 51, a: 255 }], 1, 1)); + let (k, p) = ink_image(&key, &pm, dark, None, false); + let doc = Document::new(10.0, 10.0); + let Some(lut) = crate::proof::ink_plate_lut(dark, &doc) else { panic!("a preserving proof has plate tables") }; + let (_, shown) = crate::proof::plate_image(&lut, &k, &p, None, false); + // A pixel darkened to black in display space, proofed once. + let want = cms::active().proof_srgb([0.0; 3], &proof).map(|v| (v * 255.0).round() as i32); + let px = shown.data()[0]; + let got = [px.r, px.g, px.b].map(i32::from); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 2), "{got:?} vs {want:?}"); + } + #[test] fn tables_of_two_color_settings_are_kept_side_by_side() { // Two documents drawn in turn through their own settings each keep their tables. diff --git a/crates/render/src/pattern.rs b/crates/render/src/pattern.rs index 317a423681..94b8e8576e 100644 --- a/crates/render/src/pattern.rs +++ b/crates/render/src/pattern.rs @@ -191,6 +191,9 @@ fn rasterize( let symbols = doc.symbol_boxes().quick(); r.stamp += 1; let px_rect = Rect::new(0.0, 0.0, w as f64, h as f64); + // A tile drawn for a proof that preserves the colors' numbers shows its images through that + // proof too. + let plates = crate::proof::ink_plate_lut(ink, doc); for o in def.offsets_covering(region) { let v = view * def.instance_xf(o); let frame = Frame { @@ -203,7 +206,7 @@ fn rasterize( opts: &opts, ink, output: v, - plates: None, + plates: plates.as_deref(), }; for a in &def.art { r.draw_arc(&mut ctx, &frame, a); diff --git a/crates/render/src/proof.rs b/crates/render/src/proof.rs index e809afb4ee..dd7d28eb23 100644 --- a/crates/render/src/proof.rs +++ b/crates/render/src/proof.rs @@ -2,6 +2,9 @@ //! //! * **Proof Colors** post-processes the rendered frame: every pixel goes display sRGB → proof //! space (CMYK press or RGB/colour-blindness simulation) → display, through a cached 17³ LUT. +//! With Preserve CMYK or RGB Numbers ([`preserves`]) each color is proofed from its own numbers +//! as it is painted instead ([`crate::ink::Ink::Proofed`]), and placed images from their own +//! inks or pixels ([`plate_image`]). //! * **Separations Preview** recolours the *document* before rendering: each paint colour is split //! into process inks (colour-managed), or a spot ink at the colour's tint when it's linked to a //! spot swatch (solid colours and gradient stops alike), with the process plates a gradient stop @@ -45,6 +48,21 @@ pub(crate) fn overprints(opts: &RenderOptions) -> bool { opts.overprint_preview || opts.proof.as_ref().is_some_and(|p| p.separations.is_some()) } +/// Whether Proof Colors sends the colors' own numbers to the device it simulates (Preserve CMYK +/// or RGB Numbers on a CMYK or RGB device, outside Separations Preview): each color is proofed as +/// it is painted ([`crate::ink::Ink::Proofed`]) and placed images from their own inks or pixels +/// ([`plate_image`]), and the drawn frame is not proofed again ([`post`]). +pub(crate) fn preserves(proof: &ProofSetup) -> bool { + proof.preserve_numbers + && proof.separations.is_none() + && matches!(proof.target, ProofTarget::WorkingCmyk | ProofTarget::Cmyk(_) | ProofTarget::Rgb(_)) +} + +/// The proof of [`RenderOptions::proof`] when it [`preserves`] the colors' numbers. +pub(crate) fn preserving(opts: &RenderOptions) -> Option<&ProofSetup> { + opts.proof.as_ref().filter(|p| preserves(p)) +} + /// What the `visible` plates print of `ink`, as display sRGB, without the spot inks over several /// plates: with one plate visible its ink as a grey (black = 100%), else the visible process inks /// through the proof profile. @@ -141,10 +159,26 @@ pub(crate) struct PlateLut { } impl PlateLut { - /// What the visible plates show of process inks `cmyk`, as display sRGB. + /// What the visible plates show of process inks `cmyk`, as display sRGB; with Preserve + /// Numbers outside Separations Preview, the inks as the proof's device shows them. fn shown(&self, cmyk: [f32; 4]) -> [f32; 3] { - let visible = self.proof.separations.as_deref().unwrap_or_default(); - plate_rgb(&self.cms, &self.proof, visible, &Inks { cmyk, spot: None, registration: false }) + match self.proof.separations.as_deref() { + Some(visible) => plate_rgb(&self.cms, &self.proof, visible, &Inks { cmyk, spot: None, registration: false }), + None => { + let [c, m, y, k] = cmyk; + self.cms.proof_color(&Color::Cmyk { c, m, y, k }, &self.proof) + } + } + } + + /// What display pixel `rgb` shows as: its inks separated with the proof's intent through the + /// visible plates, or with Preserve Numbers outside Separations Preview, its numbers as the + /// proof's device shows them. + fn shown_rgb(&self, rgb: [f32; 3]) -> [f32; 3] { + match self.proof.separations { + Some(_) => self.shown(self.cms.srgb_to_cmyk(rgb, self.proof.intent)), + None => self.cms.proof_srgb(rgb, &self.proof), + } } } @@ -154,10 +188,19 @@ static PLATE_LUTS: Mutex>> = Mutex::new(Vec::new()); /// The last [`PlateLut::generation`] handed out. static PLATE_GENERATION: AtomicU64 = AtomicU64::new(0); +/// The tables the placed images of `doc` show through in art drawn with `ink` apart from a frame's +/// options (a pattern's tiles): with a proof that preserves the colors' numbers +/// ([`crate::ink::Ink::Proofed`]), that proof's ([`plate_lut`]); else `None`. +pub(crate) fn ink_plate_lut(ink: crate::ink::Ink, doc: &Document) -> Option> { + let proof = crate::ink::proof_of(ink)?; + plate_lut(&RenderOptions { proof: Some(proof), ..Default::default() }, doc) +} + /// The tables the placed images of `doc` show Separations Preview's visible plates through with -/// `opts`, or `None` when it is off. +/// `opts`, or their colors as a proof that [`preserves`] the numbers shows them; `None` when +/// neither is on. pub(crate) fn plate_lut(opts: &RenderOptions, doc: &Document) -> Option> { - let proof = opts.proof.as_ref().filter(|p| p.separations.is_some())?; + let proof = opts.proof.as_ref().filter(|p| p.separations.is_some() || preserves(p))?; let (c, profiles) = (cms::active(), cms::profiles_generation()); // The spot ones are the spot plates of `vectorcraft_doc::inks::plates`; their colors are part // of the tables' identity, so a swatch edit shows. @@ -191,12 +234,17 @@ pub(crate) fn plate_image(lut: &PlateLut, key: &ImageKey, pm: &Pixmap, blob: Opt return (want, p); } // An image placed from a DCS file shows its own plates, spot plates included. - if let Some(s) = blob.filter(|b| crate::ink::shows_own_inks(key) && b.is_separated()).and_then(ImageBlob::separated) { + if let Some(s) = + blob.filter(|b| lut.proof.separations.is_some() && crate::ink::shows_own_inks(key) && b.is_separated()).and_then(ImageBlob::separated) + { let out = images::store().insert(want.clone(), Arc::new(plates_shown(lut, &s, pm))); return (want, out); } let size = (u32::from(pm.width()), u32::from(pm.height())); - let raw = crate::ink::key_inks(key, blob).filter(|i| (i.width, i.height) == size); + // A proof that preserves the numbers shows darkened pixels (a shadow's) as they are drawn, + // not the image's own inks. + let darkened = lut.proof.separations.is_none() && key.ink.is_darkened(); + let raw = crate::ink::key_inks(key, blob).filter(|i| !darkened && (i.width, i.height) == size); let mut out = pm.clone(); match raw { Some(inks) => { @@ -213,7 +261,7 @@ pub(crate) fn plate_image(lut: &PlateLut, key: &ImageKey, pm: &Pixmap, blob: Opt } } None => { - let t = lut.rgb.get_or_init(|| ProofLut::build(|rgb| lut.shown(lut.cms.srgb_to_cmyk(rgb, lut.proof.intent)))); + let t = lut.rgb.get_or_init(|| ProofLut::build(|rgb| lut.shown_rgb(rgb))); for px in out.data_mut().iter_mut().filter(|p| p.a > 0) { let a = f32::from(px.a); let un = |v: u8| (f32::from(v) / a).min(1.0); @@ -500,7 +548,7 @@ fn prepare_node(n: &Arc, earlier: Option<(&Arc, &Arc)>, how: & /// Soft-proof the rendered (premultiplied RGBA8) pixels in place. pub(crate) fn post(pixels: &mut [u8], opts: &RenderOptions) { let Some(proof) = opts.proof.as_ref() else { return }; - if proof.separations.is_some() || matches!(proof.target, ProofTarget::MonitorRgb | ProofTarget::Srgb) { + if proof.separations.is_some() || preserves(proof) || matches!(proof.target, ProofTarget::MonitorRgb | ProofTarget::Srgb) { return; } let lut = cms::active().proof_lut(proof); @@ -525,6 +573,16 @@ pub(crate) fn post(pixels: &mut [u8], opts: &RenderOptions) { } } +/// Solid color `[r, g, b, a]` (straight alpha) under the art of a frame drawn with `opts`: with a +/// proof that [`preserves`] the numbers, whose art [`prepare`] proofs before drawing, as the +/// proof's device shows it (white paper takes Simulate Paper Color's tint), so the art's +/// transparency and edges mix with it as they print; else as it is. +pub(crate) fn under_art(opts: &RenderOptions, [r, g, b, a]: [u8; 4]) -> [u8; 4] { + let Some(proof) = preserving(opts) else { return [r, g, b, a] }; + let [r, g, b] = cms::active().proof_srgb([r, g, b].map(|v| f32::from(v) / 255.0), proof).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + [r, g, b, a] +} + /// View-level proof state (View → Proof Setup / Proof Colors / Overprint Preview, Separations /// Preview panel). Process-wide: the app has one proof state for all windows. #[derive(Clone, Debug, Default, PartialEq)] diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index ba9e36138a..297feb3e76 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -149,7 +149,16 @@ impl Renderer { let inv = view.inverse(); let visible = inv.transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64)); let px = 1.0 / view.determinant().abs().sqrt().max(1e-12); - let screen = if opts.rich_black { Ink::RichBlack } else { Ink::Display }; + // A proof that preserves the colors' numbers proofs each colour as it is painted; the hold + // keeps that proof registered until the frame is drawn. + let (screen, _proof) = match proof::preserving(opts) { + Some(p) => { + let (ink, hold) = ink::proofed_ink(p); + (ink, Some(hold)) + } + None if opts.rich_black => (Ink::RichBlack, None), + None => (Ink::Display, None), + }; let symbols = doc.symbol_boxes().quick(); let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view; let plates = proof::plate_lut(opts, doc); @@ -169,10 +178,13 @@ impl Renderer { return Rendered { width: w as u32, height: h as u32, pixels }; } let mut pixels = if inks || self.blends_in_cmyk(doc, opts) { - // Blending in CMYK: one frame per ink plane, then their inks shown on screen. - let cmy = self.draw_frame(&Frame { ink: Ink::Cmy, ..frame }, w, h); + // Blending in CMYK: one frame per ink plane, then their inks shown on screen (through a + // proof that preserves the numbers, when one is on: the planes hold the inks as they + // are, images included). + let planes = if proof::preserving(opts).is_some() { None } else { frame.plates }; + let cmy = self.draw_frame(&Frame { ink: Ink::Cmy, plates: planes, ..frame }, w, h); let stats = self.stats; - let k = self.draw_frame(&Frame { ink: Ink::K, ..frame }, w, h); + let k = self.draw_frame(&Frame { ink: Ink::K, plates: planes, ..frame }, w, h); self.stats = stats; if inks { ink::amounts(&cmy, &k) @@ -268,9 +280,16 @@ impl Renderer { ctx.set_aliasing_threshold(opts.anti_alias.threshold()); self.raster = raster_settings(opts); if opts.artboards && !opts.outline { - // Paper: white on screen, no ink on the ink planes. + // Paper: white on screen, no ink on the ink planes; with a proof that preserves the + // colors' numbers, the device's paper. ctx.set_transform(f.view); - ctx.set_paint(peniko::Color::WHITE); + match screen_under_art(f, [255; 4]) { + [255, 255, 255, _] => ctx.set_paint(peniko::Color::WHITE), + paper => { + let [r, g, b, a] = f.ink.fixed8(paper); + ctx.set_paint(peniko::Color::from_rgba8(r, g, b, a)); + } + } for ab in &f.doc.artboards { ctx.fill_rect(&ab.rect); } @@ -295,7 +314,7 @@ impl Renderer { } let mut pixels = pm.data_as_u8_slice().to_vec(); if let Some(bg) = opts.background { - over_background(&mut pixels, f.ink.fixed8(bg)); + over_background(&mut pixels, f.ink.fixed8(screen_under_art(f, bg))); } pixels } @@ -465,6 +484,13 @@ fn raster_settings(opts: &RenderOptions) -> vello_cpu::RasterizerSettings { vello_cpu::RasterizerSettings { render_mode, ..Default::default() } } +/// Solid color `rgba` (straight alpha) under the art of frame `f`: on screen as +/// [`proof::under_art`] gives it; the ink planes paint it as it is, and [`ink::compose`] shows it +/// through the proof. +fn screen_under_art(f: &Frame, rgba: [u8; 4]) -> [u8; 4] { + if matches!(f.ink.base(), Ink::Cmy | Ink::K) { rgba } else { proof::under_art(f.opts, rgba) } +} + /// Premultiplied RGBA `pixels` drawn over the solid color `background` (`[r, g, b, a]`, straight). pub(crate) fn over_background(pixels: &mut [u8], [r, g, b, a]: [u8; 4]) { let alpha = u32::from(a); diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index 3e79641a51..2a876c1073 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -308,7 +308,11 @@ impl Renderer { let image_left_out = self.image_left_out.replace(false); let failures = crate::paint::decode_failures(); let pattern_images_left_out = crate::pattern::images_left_out(); - self.draw_kept_node(&mut mctx, &Frame { mt: false, ink: Ink::Display, ..*f }, &m.art); + // A proof that preserves the colors' numbers leaves the mask's images as they are, as it + // leaves its colors: the frame's, or the ink's in a pattern's tile drawn for that proof. + let preserving = crate::proof::preserving(f.opts).is_some() || crate::ink::proof_of(f.ink).is_some_and(|p| crate::proof::preserves(&p)); + let plates = if preserving { None } else { f.plates }; + self.draw_kept_node(&mut mctx, &Frame { mt: false, ink: Ink::Display, plates, ..*f }, &m.art); let incomplete = self.image_left_out.unwrap_or(false) || crate::pattern::images_left_out() > pattern_images_left_out || (!f.opts.mark_undecoded_images && crate::paint::decode_failures() > failures); diff --git a/crates/text/Cargo.toml b/crates/text/Cargo.toml index c0fc17876a..07695b034c 100644 --- a/crates/text/Cargo.toml +++ b/crates/text/Cargo.toml @@ -10,7 +10,7 @@ workspace = true [dependencies] # The shared font catalog from craft-libs main (it has the outline, bidi and caret helpers used here). -craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3", default-features = false } +craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false } vectorcraft-geom = { workspace = true } vectorcraft-doc = { workspace = true } kurbo = { workspace = true } diff --git a/crates/text/src/fontdb/face.rs b/crates/text/src/fontdb/face.rs index 5c21fbb4f1..d6e114a33f 100644 --- a/crates/text/src/fontdb/face.rs +++ b/crates/text/src/fontdb/face.rs @@ -372,6 +372,12 @@ impl FontFace { /// `usWinDescent`, at the face's location in a variable font), in font units; `None` when the /// font has no OS/2 table or the sum isn't positive. pub fn win_cell_height(&self) -> Option { + self.win_ascent_descent().map(|(a, d)| a + d) + } + /// The face's character cell on Windows above and below the baseline (the OS/2 table's + /// `usWinAscent` and `usWinDescent`, at the face's location in a variable font), in font + /// units; `None` when the font has no OS/2 table or the sum isn't positive. + pub fn win_ascent_descent(&self) -> Option<(f64, f64)> { use skrifa::raw::TableProvider; let f = self.skrifa()?; let o = f.os2().ok()?; @@ -380,8 +386,8 @@ impl FontFace { let varied = |tag: &[u8; 4]| { f.mvar().ok().and_then(|m| m.metric_delta(skrifa::Tag::new(tag), self.location().coords()).ok()).map_or(0.0, |d| d.to_f64()) }; - let h = f64::from(o.us_win_ascent()) + varied(b"hcla") + f64::from(o.us_win_descent()) + varied(b"hcld"); - (h > 0.0 && h.is_finite()).then_some(h) + let (a, d) = (f64::from(o.us_win_ascent()) + varied(b"hcla"), f64::from(o.us_win_descent()) + varied(b"hcld")); + (a + d > 0.0 && (a + d).is_finite()).then_some((a, d)) } /// The average width of the face's characters (the OS/2 table's `xAvgCharWidth`), in font /// units; `None` when the font has no OS/2 table or gives no positive width. diff --git a/crates/text/src/tests.rs b/crates/text/src/tests.rs index 38a8d97f69..94709cbb23 100644 --- a/crates/text/src/tests.rs +++ b/crates/text/src/tests.rs @@ -875,7 +875,8 @@ fn on_path_align_takes_a_variable_font_instances_em_box() { } /// A variable font's instance takes its Windows character cell from the `usWinAscent` and -/// `usWinDescent` its `MVAR` table varies: 200 units taller in Bold. +/// `usWinDescent` its `MVAR` table varies: 200 units taller in Bold, 120 above the baseline and +/// 80 below it. #[test] fn win_cell_height_takes_a_variable_font_instances_mvar() { use crate::test_fonts::{PATH_ALIGN_VARIABLE_FAMILY, path_align_font}; @@ -885,6 +886,10 @@ fn win_cell_height_takes_a_variable_font_instances_mvar() { let cell = |font_style: &str| db.style_face(&st(font_style)).and_then(|f| f.win_cell_height()).unwrap(); let (regular, bold) = (cell("Regular"), cell("Bold")); assert!((bold - regular - 200.0).abs() < 1e-6, "Regular {regular}, Bold {bold}"); + let split = |font_style: &str| db.style_face(&st(font_style)).and_then(|f| f.win_ascent_descent()).unwrap(); + let ((ra, rd), (ba, bd)) = (split("Regular"), split("Bold")); + assert!((ba - ra - 120.0).abs() < 1e-6 && (bd - rd - 80.0).abs() < 1e-6, "Regular {ra}/{rd}, Bold {ba}/{bd}"); + assert!((ra + rd - regular).abs() < 1e-6); } /// In vertical type, Align to Path moves the glyphs half an em, with their horizontal scale and not diff --git a/crates/tools/src/bbox.rs b/crates/tools/src/bbox.rs index b8723f909e..2d605b1123 100644 --- a/crates/tools/src/bbox.rs +++ b/crates/tools/src/bbox.rs @@ -127,6 +127,18 @@ pub fn move_delta(from: Point, to: Point, shift: bool, base: f64) -> Vec2 { if shift { vectorcraft_geom::constrain_angle_from(d, 45.0, base) } else { d } } +/// How far to slide along the line of unit direction `u` to take away the offset `pull` on one +/// axis (a snap of a move Shift keeps to that line): on an axis the line runs along, the shorter +/// way of the two; 0 when it runs along neither. +pub(crate) fn slide_along(pull: Vec2, u: Vec2) -> f64 { + [(pull.x, u.x), (pull.y, u.y)] + .into_iter() + .filter(|(_, c)| c.abs() > 1e-9) + .map(|(p, c)| p / c) + .min_by(|a, b| a.abs().total_cmp(&b.abs())) + .unwrap_or(0.0) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index ed22d1be9b..25781411f2 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -49,6 +49,7 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ &[ t("lineSegment", "Line Segment Tool", Some("\\"), "tool-line"), t("arc", "Arc Tool", None, "tool-arc"), + t(crate::three_point_arc::ID, "Three-Point Arc Tool", None, "tool-three-point-arc"), t("spiral", "Spiral Tool", None, "tool-spiral"), t("rectangularGrid", "Rectangular Grid Tool", None, "tool-rect-grid"), t("polarGrid", "Polar Grid Tool", None, "tool-polar-grid"), diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index e1c0c88dae..c14dfd4c2b 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -78,6 +78,8 @@ struct HandleDrag { offset: Vec2, space: bool, independent: bool, + /// The opposite handle mirrors this one ([`DirectSelectionTool::mirrors`]). + symmetric: bool, translated: bool, } @@ -261,9 +263,27 @@ pub struct DirectSelectionTool { frame_click: Option<(NodeId, AnchorRef)>, /// Where the pointer last hovered: the type on a path bracket under it draws thicker. bracket_hover: Option, + /// The Cmd/Ctrl press that lent this tool for one gesture (`lentByCmd`) is still + /// held: it does not mirror a dragged handle. Once Cmd/Ctrl is let go, pressing it again does. + lent_cmd: bool, } impl DirectSelectionTool { + /// Whether a handle drag with `ev`'s modifiers mirrors the opposite handle: Cmd/Ctrl held + /// without Alt, unless it is still the press that lent this tool for one gesture while another + /// tool, such as the Pen, is chosen. + fn mirrors(&self, ev: &PointerEvent) -> bool { + ev.mods.cmd && !ev.mods.alt && !self.lent_cmd + } + + /// Forget the lending Cmd/Ctrl once an event comes without it. The session takes Cmd/Ctrl off + /// the press it lends the tool for, while the drags after it still carry it. + fn track_lent_cmd(&mut self, ev: &PointerEvent) { + if ev.kind != PointerKind::Down { + self.lent_cmd &= ev.mods.cmd; + } + } + pub fn new(group: bool) -> Self { Self { group, @@ -291,6 +311,7 @@ impl DirectSelectionTool { frame_revision: (0, 0), frame_click: None, bracket_hover: None, + lent_cmd: false, } } @@ -441,6 +462,21 @@ fn spine_anchor(cx: &ToolContext, (id, ai): (NodeId, usize)) -> Option Vec { + let q = if symmetric && ev.mods.shift { + spine_anchor(cx, (id, anchor)).map_or(p, |a| a.p + vectorcraft_geom::constrain_angle_from(p - a.p, 45.0, cx.constrain_angle)) + } else { + p + }; + let mut params = json!({"id": id.0, "anchor": anchor, "handle": if out {"out"} else {"in"}, "x": q.x, "y": q.y, "independent": ev.mods.alt}); + if symmetric { + params["symmetric"] = json!(true); + } + vec![Action::Preview("object.blend.spine.moveAnchor".into(), params)] +} + /// Blend `id`'s spine, built once for callers that look up several of its points. fn spine_path(cx: &ToolContext, id: NodeId) -> Option { match &cx.doc.node(id)?.kind { @@ -789,10 +825,15 @@ impl Tool for DirectSelectionTool { } /// Direct Selection picks the gradient mesh points the Eyedropper held (`meshPoints`); Group /// Selection, which selects whole objects, does not. + /// The session sets `lentByCmd` on the tool Cmd/Ctrl lends for one gesture + /// ([`DirectSelectionTool::mirrors`]). fn set_option(&mut self, key: &str, value: &Value) { if key == "meshPoints" && !self.group { self.mesh.set_options(value); } + if key == "lentByCmd" { + self.lent_cmd = value.as_bool().unwrap_or(false); + } } /// Escape during a drag (anchors, handles, segments, objects, type areas, blend spines, mesh /// points, corner widgets, the brackets of type on a path, a marquee) cancels it: what it moved @@ -851,6 +892,7 @@ impl Tool for DirectSelectionTool { } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.bracket_hover = (ev.kind == PointerKind::Move).then_some(ev.pos); + self.track_lent_cmd(ev); if let Some(out) = self.guide.pointer(cx, ev) { return out; } @@ -908,6 +950,7 @@ impl Tool for DirectSelectionTool { offset: Vec2::ZERO, space: false, independent: false, + symmetric: false, translated: false, }) } @@ -1012,10 +1055,11 @@ impl Tool for DirectSelectionTool { self.snapped = snapped(q.to_vec2(), p.to_vec2(), ev.mods.shift, &guides); self.guides = guides; let cmd = if cx.doc.node(id).is_some_and(is_path_type) { "text.setPathHandle" } else { "path.setHandle" }; - vec![Action::Preview( - cmd.into(), - json!({"id": id.0, "subpath": si, "anchor": ai, "which": if out {"out"} else {"in"}, "x": q.x, "y": q.y, "independent": ev.mods.alt}), - )] + let mut params = json!({"id": id.0, "subpath": si, "anchor": ai, "which": if out {"out"} else {"in"}, "x": q.x, "y": q.y, "independent": ev.mods.alt}); + if self.mirrors(ev) { + params["symmetric"] = json!(true); + } + vec![Action::Preview(cmd.into(), params)] } (PointerKind::Drag, State::SpinePoint { id, anchor, from, start, began }) => { let mut out = vec![]; @@ -1053,10 +1097,7 @@ impl Tool for DirectSelectionTool { )); out } - (PointerKind::Drag, State::SpineHandle { id, anchor, out }) => vec![Action::Preview( - "object.blend.spine.moveAnchor".into(), - json!({"id": id.0, "anchor": anchor, "handle": if out {"out"} else {"in"}, "x": p.x, "y": p.y, "independent": ev.mods.alt}), - )], + (PointerKind::Drag, State::SpineHandle { id, anchor, out }) => drag_spine_handle(cx, ev, (id, anchor, out), p, self.mirrors(ev)), (PointerKind::Drag, State::Mesh) => self.mesh.drag_to(p).unwrap_or_default(), (PointerKind::Up, State::Mesh) => { self.state = State::Idle; @@ -1568,15 +1609,20 @@ impl DirectSelectionTool { self.snapped = snapped(q.to_vec2(), input.to_vec2(), ev.mods.shift, &guides); self.guides = guides; drag.handle = q; - drag.independent = ev.mods.alt; } } + // Alt and Cmd/Ctrl take effect on every event, while Space is held too. + drag.independent = ev.mods.alt; + drag.symmetric = self.mirrors(ev); drag.last = p; drag.space = ev.mods.space; let mut params = json!({ "id": id.0, "subpath": si, "anchor": ai, "which": if out { "out" } else { "in" }, "x": drag.handle.x, "y": drag.handle.y, "independent": drag.independent, }); + if drag.symmetric { + params["symmetric"] = json!(true); + } if drag.translated { params["at"] = json!([drag.at.x, drag.at.y]); } diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 9483943af6..f06c5cd5a6 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -48,6 +48,7 @@ pub mod sidewidget; pub mod slice; pub mod symbolism; pub mod text; +pub mod three_point_arc; pub mod touchtype; pub mod trace_split; pub mod typewidget; @@ -392,6 +393,7 @@ pub fn create(id: &str) -> Box { quickpen::ID => Box::new(quickpen::QuickPenTool::default()), // Not in the toolbar: `file.place.queue` loads it. "place" => Box::new(place::PlaceTool::default()), + three_point_arc::ID => Box::new(three_point_arc::ThreePointArcTool::default()), other => symbolism::create(other) .or_else(|| builder::create(other)) .or_else(|| draw2::create(other)) diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index acfd13d3ae..6d1615cef8 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -45,7 +45,7 @@ use vectorcraft_doc::hit::{Hit, HitKind, hit_test, marquee_in_view, objects_at, use vectorcraft_doc::{NodeId, OrientedBox}; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; -use crate::bbox::{Handle, hit_handle, in_rotate_zone, move_delta, rotate_for_drag, scale_for_drag}; +use crate::bbox::{Handle, hit_handle, in_rotate_zone, move_delta, rotate_for_drag, scale_for_drag, slide_along}; use crate::blendwidget::{self, BlendWidgetDrag}; use crate::corners::{self, CornerDrag, over_widget}; use crate::guides::{PointSnap, Targets, distance_guides, hold_on_path}; @@ -397,16 +397,7 @@ impl MoveSnap { return (d, vec![]); } let u = d / len; - // The way along the line that takes away the offset `pull` on one axis: on the axis the - // line runs along, the shorter way of the two. - let along = |pull: Vec2| { - [(pull.x, u.x), (pull.y, u.y)] - .into_iter() - .filter(|(_, c)| c.abs() > 1e-9) - .map(|(p, c)| p / c) - .min_by(|a, b| a.abs().total_cmp(&b.abs())) - .unwrap_or(0.0) - }; + let along = |pull: Vec2| slide_along(pull, u); 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); diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index e823b5c9b1..3d3f2a3873 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -45,9 +45,13 @@ const ROWS: &[Row] = &[ "affectsDensity", ], ), + // The graphic style the Symbol Styler and the Symbol Sprayer's User Defined Style apply, set + // from the Graphic Styles panel. + (&["symbolSprayer", "symbolStyler"], Some("symbolismStyle"), &["style"]), (&["mirrorCut"], None, &["axis", "keep"]), (&["puppetWarp"], None, &["showMesh", "expand"]), (&["arc"], None, &["closed", "lengthX", "lengthY", "reference", "baseAlong", "slope", "fillArc"]), + (&[crate::three_point_arc::ID], None, &["direction"]), (&["spiral"], None, &["decay", "segments", "clockwise"]), // The grids' Tool Options: the dividers and switches the drag uses, the Default Size and // Reference Point a click's dialog opens with. diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index a4fc04e0cc..165ced795e 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -48,6 +48,8 @@ pub struct SymbolismTool { active: bool, hover: Option, alt: bool, + /// Shift was held when the drag began (the Shifter, Sizer, Stainer and Styler have a Shift form). + shift: bool, /// Brush diameter in points. pub diameter: f64, /// 1..10. @@ -113,6 +115,7 @@ impl SymbolismTool { active: false, hover: None, alt: false, + shift: false, diameter: 80.0, intensity: 5.0, density: 5.0, @@ -196,6 +199,9 @@ impl SymbolismTool { v["proportional"] = json!(self.proportional); v["affectsDensity"] = json!(self.affects_density); } + if self.shift && matches!(tool, "shift" | "size" | "stain" | "style") { + v["shift"] = json!(true); + } ("symbol.adjust".into(), v) } } @@ -230,6 +236,7 @@ impl Tool for SymbolismTool { self.previewed = 1; self.active = true; self.alt = ev.mods.alt; + self.shift = ev.mods.shift; let (c, v) = self.command(cx); vec![Action::Begin(self.label().into()), Action::Preview(c, v)] } @@ -577,6 +584,39 @@ mod tests { assert!(v["method"] == "random" && v.get("proportional").is_none(), "{v}"); } + /// A drag begun with Shift sends `shift` with the Shifter, Sizer, Stainer and Styler, and only + /// with them; one begun without it sends none. + #[test] + fn shift_reaches_the_tools_that_have_a_shift_form() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let shifted = Mods { shift: true, ..Default::default() }; + for (id, sends) in [ + ("symbolShifter", true), + ("symbolSizer", true), + ("symbolStainer", true), + ("symbolStyler", true), + ("symbolScruncher", false), + ("symbolSpinner", false), + ("symbolScreener", false), + ("symbolSprayer", false), + ] { + let mut t = SymbolismTool::new(id); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 5.0, 5.0).with_mods(shifted)); + let Action::Preview(_, v) = &a[1] else { panic!("{a:?}") }; + assert_eq!(v.get("shift"), sends.then_some(&json!(true)), "{id}"); + // The drag keeps the Shift it began with. + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 60.0, 5.0)); + let Action::Preview(_, v) = &a[0] else { panic!("{a:?}") }; + assert_eq!(v.get("shift"), sends.then_some(&json!(true)), "{id} drag"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 60.0, 5.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 5.0, 5.0)); + let Action::Preview(_, v) = &a[1] else { panic!("{a:?}") }; + assert!(v.get("shift").is_none(), "{id} without Shift: {v}"); + } + } + /// With Use Pressure Pen a drag sample where the pen stays is kept when the pressure changes; /// without it, or with the same pressure, the drag keeps thinning the samples by distance. #[test] diff --git a/crates/tools/src/three_point_arc.rs b/crates/tools/src/three_point_arc.rs new file mode 100644 index 0000000000..60314cbe1f --- /dev/null +++ b/crates/tools/src/three_point_arc.rs @@ -0,0 +1,337 @@ +//! The Three-Point Arc tool draws an open circular arc between two ends it is given +//! (`shape.threePointArc`). +//! +//! The ends come first: a drag from one to the other, or a click on each. Shift keeps the second +//! end at 45° steps from the first (from General › Constrain Angle). A third point then shapes the +//! arc, placed by a click or by a press dragged to it: the arc passes through it, or, with the +//! `direction` option on, the arc leaves the first end heading toward it (Alt: the arc arrives at +//! the second end along the line from that end to the point, and Shift keeps the line at 45° +//! steps). `direction` is set in the tool's Tool Options and kept with the preferences; `]` (with +//! or without Shift) switches it while the ends are placed. Every point snaps to Smart Guides. +//! Until the third point is placed, the tool shows the arc as a dashed outline with its ends, its +//! center as a small cross, the direction line in direction mode and, with Measurement Labels on, +//! the radius by the pointer. Where no arc fits (the third point lies on the line through the +//! ends) or the arc would reach past the canvas, the tool shows "Arc too large" by the pointer +//! (nothing while the pointer is on an end) and a click there draws nothing. The arc is one undo +//! step. Escape, a press dropped part way, and an edit, Undo or Redo made outside the tool drop +//! the ends; a second click on the first end (a double-click) places nothing. + +use serde_json::{Value, json}; +use vectorcraft_doc::MAX_COORD; +use vectorcraft_geom::shapes::CircularArc; +use vectorcraft_geom::{PathData, Point, Vec2}; + +use crate::guides::{DrawSnap, Leave}; +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +pub const ID: &str = "threePointArc"; + +/// How far (screen points) the pointer travels from a press before the press counts as a drag. +const DRAG_PX: f64 = 2.0; +/// Half the length (screen points) of each arm of the cross at the arc's center. +const CROSS_PX: f64 = 4.0; +/// How near (screen points) the first end a second click counts as a click on it. +const REACH_PX: f64 = 3.0; +/// The label the tool shows by the pointer where no arc fits. +pub const TOO_LARGE: &str = "Arc too large"; + +/// The press in progress. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Press { + /// The first end, placed at `at` by a press at `from` (before snapping): a release after a + /// drag places the second end there. The drag is measured from `from`. + Start { at: Point, from: Point, dragged: bool }, + /// The second end, pressed after a click placed the first: the release places it. + End, + /// The third point, pressed once both ends are placed: the release draws the arc. + Third, +} + +#[derive(Default)] +pub struct ThreePointArcTool { + snap: DrawSnap, + /// The third point gives the arc's direction at an end instead of a point it passes through. + direction: bool, + start: Option, + end: Option, + press: Option, + /// Where the pointer is, snapped: the point the next press or release places. + pointer: Option, + /// Alt was held at the last pointer event: in direction mode, the direction is at the second end. + at_end: bool, + /// Where the pointer was at its last event, pressed or hovering, before snapping, and the keys + /// held then. + raw: Option<(Point, Mods)>, +} + +/// The arc from `start` to `end` shaped by `third`, as `shape.threePointArc` draws it: through +/// `third`, or with `direction`, heading toward `third` from `start` (or, with `at_end`, arriving +/// at `end` along the line from `end` to `third`). None where no arc fits or the arc would reach +/// past the canvas. With it, the path the command draws. +pub fn arc_of(start: Point, end: Point, third: Point, direction: bool, at_end: bool) -> Option<(CircularArc, PathData)> { + let (arc, path) = match (direction, at_end) { + (false, _) => CircularArc::through(start, end, third).map(|arc| (arc, arc.to_path_via(third))), + (true, false) => CircularArc::leaving(start, third - start, end).map(|arc| (arc, arc.to_path())), + (true, true) => CircularArc::arriving(start, end, end - third).map(|arc| (arc, arc.to_path())), + }?; + // The curve is measured, not its handles, which can reach past the canvas while the curve stays + // inside, as the document's own range check measures a path. + let inside = |x: f64, y: f64| x.abs() <= MAX_COORD && y.abs() <= MAX_COORD; + let on_canvas = path.bounds().is_some_and(|r| inside(r.x0, r.y0) && inside(r.x1, r.y1)); + on_canvas.then_some((arc, path)) +} + +/// The command the tool runs for the arc from `start` to `end` shaped by `third`. +fn command(start: Point, end: Point, third: Point, direction: bool, at_end: bool) -> (String, Value) { + let pair = |p: Point| json!([p.x, p.y]); + let params = if direction { + json!({ "start": pair(start), "end": pair(end), "toward": pair(third), "at": if at_end { "end" } else { "start" } }) + } else { + json!({ "start": pair(start), "end": pair(end), "through": pair(third) }) + }; + ("shape.threePointArc".into(), params) +} + +impl ThreePointArcTool { + fn clear(&mut self) { + self.start = None; + self.end = None; + self.press = None; + self.pointer = None; + self.snap.clear(); + } + + /// How the point being placed keeps to the points before it: the second end to the first, and + /// in direction mode the third point to the end its direction line starts from. + fn leave(&self, cx: &ToolContext, mods: Mods) -> Option { + match (self.start, self.end) { + (Some(a), None) => Some(Leave::segment(cx, a, mods.shift)), + (Some(a), Some(b)) if self.direction => Some(Leave::segment(cx, if mods.alt { b } else { a }, mods.shift)), + _ => None, + } + } + + /// The pressed pointer moved to `ev`, or Shift or Alt changed: the point being placed follows + /// it. A change of keys alone does not make the press a drag. + fn follow(&mut self, cx: &ToolContext, ev: &PointerEvent) { + let moved = self.raw.is_none_or(|(p, _)| p != ev.pos); + self.raw = Some((ev.pos, ev.mods)); + match &mut self.press { + Some(Press::Start { at, from, dragged }) => { + *dragged |= moved && ev.pos.distance(*from) >= cx.tol(DRAG_PX); + let leave = Leave::segment(cx, *at, ev.mods.shift); + self.pointer = Some(self.snap.drag(cx, ev.pos, Some(&leave))); + } + Some(Press::End | Press::Third) => { + let leave = self.leave(cx, ev.mods); + self.pointer = Some(self.snap.drag(cx, ev.pos, leave.as_ref())); + } + None => {} + } + } + + /// The arc as the tool shows it now, and its path: both ends placed and the pointer on a point + /// that fits. + fn arc(&self) -> Option<(CircularArc, PathData)> { + arc_of(self.start?, self.end?, self.pointer?, self.direction, self.at_end) + } +} + +impl Tool for ThreePointArcTool { + fn id(&self) -> &'static str { + ID + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { + if !ev.pos.is_finite() { + return vec![]; + } + if self.end.is_some() { + self.at_end = ev.mods.alt; + } + match ev.kind { + PointerKind::Move => { + self.raw = Some((ev.pos, ev.mods)); + let leave = self.leave(cx, ev.mods); + self.pointer = Some(self.snap.hover(cx, ev.pos, &[], leave.as_ref())); + vec![] + } + PointerKind::Down => { + self.raw = Some((ev.pos, ev.mods)); + let leave = self.leave(cx, ev.mods); + match (self.start, self.end) { + (None, _) => { + let at = self.snap.press(cx, ev.pos, &[], None); + self.start = Some(at); + self.press = Some(Press::Start { at, from: ev.pos, dragged: false }); + self.pointer = Some(at); + } + (Some(a), None) => { + let at = self.snap.press(cx, ev.pos, &[], leave.as_ref()); + // The second click of a double-click lands on the first end. + if at.distance(a) <= cx.tol(REACH_PX) { + self.press = None; + return vec![]; + } + self.press = Some(Press::End); + self.pointer = Some(at); + } + (Some(_), Some(_)) => { + self.pointer = Some(self.snap.press(cx, ev.pos, &[], leave.as_ref())); + self.press = Some(Press::Third); + } + } + vec![] + } + PointerKind::Drag => { + self.follow(cx, ev); + vec![] + } + PointerKind::Up => { + // A release away from the last drag event places the point where it is let go, and + // a release with Shift or Alt changed places it as those keys keep it. + let same = self.raw.is_some_and(|(p, m)| p == ev.pos && (m.shift, m.alt) == (ev.mods.shift, ev.mods.alt)); + if self.press.is_some() && !same { + self.follow(cx, ev); + } + match (self.press.take(), self.start, self.pointer) { + (Some(Press::Start { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.end = Some(b), + (Some(Press::End), Some(a), Some(b)) if b.distance(a) > cx.tol(REACH_PX) => self.end = Some(b), + (Some(Press::Third), Some(a), Some(c)) => { + let Some(b) = self.end else { return vec![] }; + // Where no arc fits, nothing is drawn and the ends stay for another try. + if self.arc().is_none() { + self.snap.clear(); + return vec![]; + } + let (name, params) = command(a, b, c, self.direction, self.at_end); + self.clear(); + return vec![Action::Exec(name, params)]; + } + _ => {} + } + // A placed end: the guides of the press go. + self.snap.clear(); + vec![] + } + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], + } + } + + fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { + match key { + ToolKey::Escape => self.clear(), + ToolKey::BracketRight if self.start.is_some() => { + self.direction = !self.direction; + // A press in progress: the point being placed keeps to the new mode. + // A hovering pointer: the third point it shows keeps to the new mode too. + match (self.press, self.raw) { + (Some(_), Some((p, mods))) => self.follow(cx, &PointerEvent::new(PointerKind::Drag, p.x, p.y).with_mods(mods)), + (None, Some((p, mods))) if self.end.is_some() && self.pointer.is_some() => { + let leave = self.leave(cx, mods); + self.pointer = Some(self.snap.hover(cx, p, &[], leave.as_ref())); + } + _ => {} + } + } + _ => {} + } + vec![] + } + + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + matches!(key, ToolKey::Escape | ToolKey::BracketRight) && self.start.is_some() + } + + /// An end placed: Escape drops it. + fn ends_on_escape(&self, _cx: &ToolContext) -> bool { + self.start.is_some() + } + + fn busy(&self) -> bool { + self.start.is_some() + } + + /// A dropped press (a second finger, a canceled touch) drops the ends placed so far. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + self.clear(); + vec![] + } + + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { + self.clear(); + vec![] + } + + fn hover_ended(&mut self, _cx: &ToolContext) { + if self.press.is_none() { + self.pointer = None; + self.snap.clear(); + } + } + + /// An edit, Undo or Redo made outside the tool, or another document, drops the ends. + fn history_moved(&mut self) { + self.clear(); + } + + fn overlays(&self, cx: &ToolContext) -> Vec { + let mut o = self.snap.guides().to_vec(); + let color = crate::draw2::FEEDBACK; + match (self.start, self.end, self.pointer) { + // Placing the second end: the chord so far. + (Some(a), None, Some(b)) if b != a => o.push(Overlay::Line { a, b, color, dashed: true }), + (Some(a), Some(b), Some(p)) => { + if self.direction { + o.push(Overlay::Line { a: if self.at_end { b } else { a }, b: p, color, dashed: false }); + } + match self.arc() { + Some((arc, path)) => { + o.push(Overlay::Path { path: path.to_bezpath(), color, width: 1.0, dashed: true }); + let (c, arm) = (arc.center, 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 cx.measurement_labels { + o.push(Overlay::Measure { p, text: format!("R: {}", cx.len(arc.radius)) }); + } + } + // A pointer on an end gives no third point yet, so no label. + None if p.distance(a) <= cx.tol(REACH_PX) || p.distance(b) <= cx.tol(REACH_PX) => {} + None => o.push(Overlay::Label { p, text: TOO_LARGE.into(), color }), + } + } + _ => {} + } + for p in self.start.iter().chain(self.end.iter()) { + o.push(Overlay::Anchor { p: *p, color, filled: true, size: 6.0 }); + } + o + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { + Cursor::Crosshair + } + + fn options(&self) -> Value { + json!({ "direction": self.direction }) + } + + fn set_option(&mut self, key: &str, value: &Value) { + if key == "direction" + && let Some(on) = value.as_bool() + { + self.direction = on; + } + } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "direction" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/tools/src/three_point_arc/tests.rs b/crates/tools/src/three_point_arc/tests.rs new file mode 100644 index 0000000000..eaf269e974 --- /dev/null +++ b/crates/tools/src/three_point_arc/tests.rs @@ -0,0 +1,388 @@ +use super::*; +use crate::testutil::*; +use vectorcraft_doc::Selection; +use vectorcraft_geom::Rect; + +fn ev(kind: PointerKind, (x, y): (f64, f64), mods: Mods) -> PointerEvent { + PointerEvent::new(kind, x, y).with_mods(mods) +} + +fn click_with(t: &mut ThreePointArcTool, cx: &ToolContext, p: (f64, f64), mods: Mods) -> Vec { + let mut acts = t.pointer(cx, &ev(PointerKind::Down, p, mods)); + acts.extend(t.pointer(cx, &ev(PointerKind::Up, p, mods))); + acts +} + +fn click(t: &mut ThreePointArcTool, cx: &ToolContext, p: (f64, f64)) -> Vec { + click_with(t, cx, p, Mods::default()) +} + +fn hover(t: &mut ThreePointArcTool, cx: &ToolContext, p: (f64, f64), mods: Mods) { + assert!(t.pointer(cx, &ev(PointerKind::Move, p, mods)).is_empty()); +} + +/// A press at `from`, dragged through `path` and let go at its last point. +fn drag(t: &mut ThreePointArcTool, cx: &ToolContext, from: (f64, f64), path: &[(f64, f64)], mods: Mods) -> Vec { + let mut acts = t.pointer(cx, &ev(PointerKind::Down, from, mods)); + for p in path { + acts.extend(t.pointer(cx, &ev(PointerKind::Drag, *p, mods))); + } + let end = path.last().copied().unwrap_or(from); + acts.extend(t.pointer(cx, &ev(PointerKind::Up, end, mods))); + acts +} + +fn through(start: (f64, f64), end: (f64, f64), via: (f64, f64)) -> Vec { + let pair = |(x, y): (f64, f64)| json!([x, y]); + vec![Action::Exec("shape.threePointArc".into(), json!({ "start": pair(start), "end": pair(end), "through": pair(via) }))] +} + +fn toward(start: (f64, f64), end: (f64, f64), to: (f64, f64), at: &str) -> Vec { + let pair = |(x, y): (f64, f64)| json!([x, y]); + vec![Action::Exec("shape.threePointArc".into(), json!({ "start": pair(start), "end": pair(end), "toward": pair(to), "at": at }))] +} + +/// The dashed arc the tool shows: its bounding box. +fn preview(o: &[Overlay]) -> Option { + o.iter().find_map(|o| match o { + Overlay::Path { path, dashed: true, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + _ => None, + }) +} + +fn too_large(o: &[Overlay]) -> bool { + o.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == TOO_LARGE)) +} + +/// A drag places the two ends; a click on a third point then draws the arc through it. Until +/// then, nothing is drawn. +#[test] +fn a_drag_and_a_click_draw_the_arc_through_the_third_point() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + assert!(drag(&mut t, &cx, (300.0, 300.0), &[(340.0, 300.0), (380.0, 300.0)], Mods::default()).is_empty()); + assert!(t.busy() && t.ends_on_escape(&cx)); + assert_eq!(click(&mut t, &cx, (340.0, 260.0)), through((300.0, 300.0), (380.0, 300.0), (340.0, 260.0))); + assert!(!t.busy() && t.overlays(&cx).is_empty(), "the tool starts afresh"); +} + +/// Two clicks place the ends. Between the second click and the third, the tool shows the arc +/// through the pointer (a half circle here, bulging up the page), its center cross and its +/// radius; the third click draws it. +#[test] +fn three_clicks_draw_the_arc_and_the_tool_shows_it_on_the_way() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + assert!(click(&mut t, &cx, (300.0, 300.0)).is_empty()); + hover(&mut t, &cx, (380.0, 300.0), Mods::default()); + assert!(t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Line { dashed: true, .. })), "the chord so far"); + assert!(click(&mut t, &cx, (380.0, 300.0)).is_empty()); + hover(&mut t, &cx, (340.0, 260.0), Mods::default()); + let o = t.overlays(&cx); + let b = preview(&o).expect("the arc"); + assert!((b.x0 - 300.0).abs() < 0.1 && (b.x1 - 380.0).abs() < 0.1 && (b.y0 - 260.0).abs() < 0.1 && (b.y1 - 300.0).abs() < 1e-9, "{b:?}"); + let radius = format!("R: {}", cx.len(40.0)); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if *text == radius)), "{o:?}"); + // The center cross at (340, 300). + assert!(o.iter().any(|o| matches!(o, Overlay::Line { a, b, dashed: false, .. } if a.midpoint(*b).distance(Point::new(340.0, 300.0)) < 1e-9))); + let quiet = ToolContext { measurement_labels: false, ..cx }; + assert!(!t.overlays(&quiet).iter().any(|o| matches!(o, Overlay::Measure { .. }))); + assert_eq!(click(&mut t, &cx, (340.0, 260.0)), through((300.0, 300.0), (380.0, 300.0), (340.0, 260.0))); +} + +/// A third point on the line through the ends, an arc reaching past the canvas, or a third point +/// on an end gives no arc: a click draws nothing and keeps the ends, and a click on a point that +/// fits then draws the arc. The tool shows "Arc too large" by the pointer, except on an end. +#[test] +fn a_third_point_in_line_with_the_ends_draws_nothing() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + // Nearly in line beyond the end: the circle's center is about 1.2·10⁷ pt away. + for (bad, label) in [((420.0, 300.0), true), ((250.0, 300.0), true), ((340.0, 300.0), true), ((500.0, 300.001), true), ((380.0, 300.0), false)] { + hover(&mut t, &cx, bad, Mods::default()); + let o = t.overlays(&cx); + assert!(too_large(&o) == label && preview(&o).is_none(), "{bad:?}: {o:?}"); + assert!(click(&mut t, &cx, bad).is_empty(), "{bad:?}"); + assert!(t.busy()); + } + assert_eq!(click(&mut t, &cx, (340.0, 340.0)), through((300.0, 300.0), (380.0, 300.0), (340.0, 340.0))); +} + +/// An arc near the canvas edge fits while its curve stays inside, even where a handle reaches past +/// the edge, and gives no arc once the curve reaches past it. +#[test] +fn an_arc_near_the_canvas_edge_is_measured_by_its_curve() { + // A 60° arc of radius 1000 whose rightmost point is `edge`: the handles at its ends reach about + // 45 pt further right. + let arc = |edge: f64| { + let (r, c) = (1000.0, edge - 1000.0); + let (dx, dy) = (r * 30f64.to_radians().cos(), r * 30f64.to_radians().sin()); + let start = Point::new(c + dx, -dy); + let end = Point::new(c + dx, dy); + arc_of(start, end, start + Vec2::new(0.5, 3f64.sqrt() / 2.0) * 100.0, true, false) + }; + let Some((_, path)) = arc(MAX_COORD - 1.0) else { panic!("an arc inside the canvas fits") }; + assert!(path.control_bounds().is_some_and(|r| r.x1 > MAX_COORD), "a handle reaches past the edge"); + assert!(path.bounds().is_some_and(|r| r.x1 <= MAX_COORD && (r.x1 - (MAX_COORD - 1.0)).abs() < 1e-6)); + assert!(arc(MAX_COORD + 1.0).is_none(), "an arc reaching past the canvas does not fit"); +} + +/// In direction mode, Shift keeps the direction line at 45° steps from the end it starts at. +#[test] +fn shift_keeps_the_direction_at_45_degree_steps() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + t.set_option("direction", &json!(true)); + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + let shift = Mods { shift: true, ..Mods::default() }; + let acts = click_with(&mut t, &cx, (303.0, 250.0), shift); + let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") }; + assert!(params["toward"][0].as_f64().is_some_and(|x| (x - 300.0).abs() < 1e-9), "{params}"); + // With Alt, from the second end. + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + let both = Mods { shift: true, alt: true, ..Mods::default() }; + let acts = click_with(&mut t, &cx, (383.0, 250.0), both); + let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") }; + assert!(params["toward"][0].as_f64().is_some_and(|x| (x - 380.0).abs() < 1e-9) && params["at"] == "end", "{params}"); +} + +/// With the `direction` option, the third point gives the direction the arc leaves its first +/// end in, and the tool shows the line from that end to the pointer. Alt moves the direction to +/// the second end. `]` switches the option while the ends are placed, and only then. +#[test] +fn in_direction_mode_the_third_point_sets_the_tangent_at_an_end() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + assert!(!t.claims_key(&cx, ToolKey::BracketRight), "no ends: ] is left to the app"); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + assert_eq!(t.options(), json!({ "direction": false })); + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + assert!(t.claims_key(&cx, ToolKey::BracketRight)); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + assert_eq!(t.options(), json!({ "direction": true })); + // Straight up the page from (300, 300): the upper half circle about (340, 300). + hover(&mut t, &cx, (300.0, 250.0), Mods::default()); + let o = t.overlays(&cx); + let b = preview(&o).expect("the arc"); + assert!((b.y0 - 260.0).abs() < 0.1 && (b.y1 - 300.0).abs() < 1e-9, "{b:?}"); + // The direction line: solid, from the end it starts at. + let line = |o: &[Overlay], from: Point| o.iter().any(|o| matches!(o, Overlay::Line { a, dashed: false, .. } if *a == from)); + assert!(line(&o, Point::new(300.0, 300.0)), "{o:?}"); + assert_eq!(click(&mut t, &cx, (300.0, 250.0)), toward((300.0, 300.0), (380.0, 300.0), (300.0, 250.0), "start")); + // Alt: the direction line starts at the second end. + t.set_option("direction", &json!(true)); + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + let alt = Mods { alt: true, ..Mods::default() }; + hover(&mut t, &cx, (380.0, 250.0), alt); + assert!(line(&t.overlays(&cx), Point::new(380.0, 300.0))); + assert!(preview(&t.overlays(&cx)).is_some()); + assert_eq!(click_with(&mut t, &cx, (380.0, 250.0), alt), toward((300.0, 300.0), (380.0, 300.0), (380.0, 250.0), "end")); + // ] switches back to passing through the third point. + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + assert_eq!(click(&mut t, &cx, (340.0, 260.0)), through((300.0, 300.0), (380.0, 300.0), (340.0, 260.0))); +} + +/// The `direction` option takes a bool; anything else leaves it as it was. +#[test] +fn the_direction_option_takes_a_bool() { + let mut t = ThreePointArcTool::default(); + t.set_option("direction", &json!(true)); + for v in [json!("false"), json!(0), json!(null)] { + t.set_option("direction", &v); + assert_eq!(t.options(), json!({ "direction": true }), "{v}"); + } + t.set_option("direction", &json!(false)); + assert_eq!(t.options(), json!({ "direction": false })); +} + +/// `]` pressed while the third point is held down places the point as the new mode keeps it: the +/// point Shift kept on the direction line goes back to where the pointer is, and the other way. +#[test] +fn bracket_during_a_press_places_the_third_point_in_the_new_mode() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + let shift = Mods { shift: true, ..Mods::default() }; + t.set_option("direction", &json!(true)); + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + t.pointer(&cx, &ev(PointerKind::Down, (303.0, 250.0), shift)); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (303.0, 250.0), shift)), through((300.0, 300.0), (380.0, 300.0), (303.0, 250.0))); + // Through mode first, switched to direction mode during the press: Shift keeps the line upright. + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + t.pointer(&cx, &ev(PointerKind::Down, (303.0, 250.0), shift)); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + let acts = t.pointer(&cx, &ev(PointerKind::Up, (303.0, 250.0), shift)); + let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") }; + assert!(params["toward"][0].as_f64().is_some_and(|x| (x - 300.0).abs() < 1e-9) && params["at"] == "start", "{params}"); +} + +/// `]` pressed while the pointer hovers moves the third point the tool shows to where the new mode +/// keeps it, so the arc shown is the arc a click there draws. +#[test] +fn bracket_while_hovering_shows_the_third_point_in_the_new_mode() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + let shift = Mods { shift: true, ..Mods::default() }; + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + hover(&mut t, &cx, (303.0, 250.0), shift); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + // The direction line from the first end: Shift keeps it upright. + let start = Point::new(300.0, 300.0); + let line = t.overlays(&cx).into_iter().find_map(|o| match o { + Overlay::Line { a, b, dashed: false, .. } if a == start => Some(b), + _ => None, + }); + assert!(line.is_some_and(|b| (b.x - 300.0).abs() < 1e-9), "{line:?}"); + let acts = click_with(&mut t, &cx, (303.0, 250.0), shift); + let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") }; + assert!(params["toward"][0].as_f64().is_some_and(|x| (x - 300.0).abs() < 1e-9), "{params}"); + // Back to through mode while hovering: the point goes back to the pointer. + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + hover(&mut t, &cx, (303.0, 250.0), shift); + assert!(t.pointer.is_some_and(|q| (q.x - 300.0).abs() < 1e-9), "{:?}", t.pointer); + t.key(&cx, ToolKey::BracketRight, Mods::default()); + assert_eq!(t.pointer, Some(Point::new(303.0, 250.0))); + assert_eq!(click_with(&mut t, &cx, (303.0, 250.0), shift), through((300.0, 300.0), (380.0, 300.0), (303.0, 250.0))); +} + +/// With Snap to Point, a first press that snaps to the rectangle's corner, 1.5 pt from the +/// pointer, and moves 1.9 pt before it is let go is a click: the drag is measured from the press, +/// not from the corner, so only the first end is placed. +#[test] +fn a_short_move_from_a_snapped_press_is_not_a_drag() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, snap_to_point: true, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, (201.5, 200.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (203.4, 200.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Up, (203.4, 200.0), Mods::default())); + assert_eq!((t.start, t.end), (Some(Point::new(200.0, 200.0)), None)); +} + +/// A release away from the last drag event places the point where the pointer is let go, for +/// the second end and for the third point. +#[test] +fn a_point_is_placed_where_the_press_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 mut t = ThreePointArcTool::default(); + let none = Mods::default(); + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), none)); + t.pointer(&cx, &ev(PointerKind::Drag, (340.0, 300.0), none)); + t.pointer(&cx, &ev(PointerKind::Up, (380.0, 300.0), none)); + assert_eq!(t.end, Some(Point::new(380.0, 300.0))); + t.pointer(&cx, &ev(PointerKind::Down, (340.0, 250.0), none)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (340.0, 260.0), none)), through((300.0, 300.0), (380.0, 300.0), (340.0, 260.0))); + // A press that only moves when it is let go still counts as a drag for the ends. + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), none)); + t.pointer(&cx, &ev(PointerKind::Up, (380.0, 300.0), none)); + assert_eq!(t.end, Some(Point::new(380.0, 300.0))); +} + +/// A release with Shift or Alt changed since the press places the point as the keys at the +/// release keep it, even where the pointer did not move. +#[test] +fn a_release_places_the_point_with_the_keys_held_then() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + let (none, shift) = (Mods::default(), Mods { shift: true, ..Mods::default() }); + // The second end: pressed without Shift, let go with it. + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (380.0, 306.0), none)); + t.pointer(&cx, &ev(PointerKind::Up, (380.0, 306.0), shift)); + assert_eq!(t.end.map(|e| e.y), Some(300.0), "{:?}", t.end); + // The third point in direction mode: pressed with Shift, let go with Shift and Alt, so the + // direction line keeps to 45° steps from the second end. + t.set_option("direction", &json!(true)); + let both = Mods { alt: true, ..shift }; + t.pointer(&cx, &ev(PointerKind::Down, (303.0, 250.0), shift)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, (303.0, 250.0), both)); + let [Action::Exec(_, params)] = acts.as_slice() else { panic!("{acts:?}") }; + let at = |key: &str, i: usize| params[key][i].as_f64().unwrap_or(f64::NAN); + let (dx, dy) = (at("toward", 0) - at("end", 0), at("toward", 1) - at("end", 1)); + assert!(params["at"] == "end" && (dx.abs() - dy.abs()).abs() < 1e-9, "{params}"); +} + +/// A first click that snaps to the rectangle's corner, 3 pt from the pointer, and is let go with +/// Shift changed places only the first end: a change of keys alone is not a drag. +#[test] +fn a_click_let_go_with_shift_changed_is_not_a_drag() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let g = Point::new(200.0, 200.0); + let off = (203.0, 201.0); + let mut t = ThreePointArcTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, off, Mods::default())); + t.pointer(&cx, &ev(PointerKind::Up, off, Mods { shift: true, ..Mods::default() })); + assert_eq!((t.start, t.end), (Some(g), None)); +} + +/// Shift keeps the second end at 45° steps from the first. +#[test] +fn shift_keeps_the_second_end_at_45_degree_steps() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + let shift = Mods { shift: true, ..Mods::default() }; + drag(&mut t, &cx, (300.0, 300.0), &[(340.0, 303.0), (380.0, 306.0)], shift); + assert_eq!(t.end.map(|e| e.y), Some(300.0), "{:?}", t.end); +} + +/// Escape, an edit made outside the tool and a dropped press drop the ends; a second click on +/// the first end (a double-click) places nothing. +#[test] +fn escape_history_and_a_double_click_drop_or_keep_the_ends() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = ThreePointArcTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + assert!(t.claims_key(&cx, ToolKey::Escape)); + t.key(&cx, ToolKey::Escape, Mods::default()); + assert!(!t.busy() && !t.claims_key(&cx, ToolKey::Escape)); + click(&mut t, &cx, (300.0, 300.0)); + assert!(click(&mut t, &cx, (300.5, 300.0)).is_empty()); + assert_eq!((t.start, t.end), (Some(Point::new(300.0, 300.0)), None), "the double-click's second click places nothing"); + click(&mut t, &cx, (380.0, 300.0)); + t.history_moved(); + assert!(!t.busy()); + drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 300.0)], Mods::default()); + t.drop_press(&cx); + assert!(!t.busy() && t.overlays(&cx).is_empty()); +} + +/// The catalog lists the tool in the Line Segment tool's group, after the Arc tool, with no +/// default shortcut, and `create` makes it. +#[test] +fn the_tool_is_in_the_line_segment_group_after_the_arc_tool() { + let group = crate::TOOL_GROUPS.iter().find(|g| g.iter().any(|t| t.id == ID)).expect("in a toolbar group"); + let ids: Vec<_> = group.iter().map(|t| t.id).collect(); + let arc = ids.iter().position(|id| *id == "arc").expect("the Arc tool's group"); + assert_eq!(ids.first(), Some(&"lineSegment")); + assert_eq!(ids.get(arc + 1), Some(&ID)); + let info = crate::tool_info(ID).expect("catalogued"); + assert_eq!((info.label, info.shortcut), ("Three-Point Arc Tool", None)); + assert_eq!(crate::create(ID).id(), ID); +} diff --git a/crates/tools/src/xform/artboard.rs b/crates/tools/src/xform/artboard.rs index fae20e6d4e..cfadb80fa3 100644 --- a/crates/tools/src/xform/artboard.rs +++ b/crates/tools/src/xform/artboard.rs @@ -9,7 +9,8 @@ //! all of them (#1139). Shift-drag inside an artboard draws a new artboard there, and Shift-drag on //! the pasteboard is a marquee: the artboards it touches leave the selection or join it. Drag inside //! moves it (with its artwork when the `moveArt` option is on; Alt moves a copy and -//! leaves the artboard where it was), drag a handle resizes it +//! leaves the artboard where it was; Shift held once the drag is under way keeps the move or copy +//! to the level, upright or 45° line, counted from General › Constrain Angle), drag a handle resizes it //! (Shift proportional, Alt from centre; with the `scaleArt` option on, Scale Artwork with Artboard, //! always proportional, and the art fully inside scales with it), drag on the pasteboard draws a new artboard, Delete removes //! the active one (Copy, Cut and Paste take it with its art: `artboard.copy`), the arrow keys move the @@ -36,7 +37,7 @@ use vectorcraft_doc::ArtboardSide; use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use super::{BLUE, polygon, rect_corners}; -use crate::bbox::{Handle, hit_handle, scale_for_drag}; +use crate::bbox::{Handle, hit_handle, move_delta, scale_for_drag, slide_along}; use crate::guides::{DrawSnap, Leave, Targets}; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -247,6 +248,36 @@ impl ArtboardTool { d + adj } + /// [`Self::snap_move`] for a move Shift keeps to its line (through the press, along `d`): + /// every snap slides the move along that line. Whole pixels and the grid slide it by the + /// shorter of the ways that put its top-left on a whole pixel or a gridline on either axis + /// ([`slide_along`]); Smart Guides slide it until an edge or the centre lines up + /// ([`Targets::snap_rects_along`]). A move of zero length does not snap. + fn snap_move_along(&mut self, cx: &ToolContext, rect: Rect, d: Vec2, copy: bool) -> Vec2 { + self.guides.clear(); + let len = d.hypot(); + if !len.is_finite() || len <= 1e-9 { + return d; + } + let u = d / len; + let tl = Point::new(rect.x0, rect.y0) + d; + if cx.snaps_to_pixel(PixelOp::Moving) { + return d + u * slide_along(Vec2::new(tl.x.round() - tl.x, tl.y.round() - tl.y), u); + } + if cx.snap_to_grid { + return d + u * slide_along(vectorcraft_geom::snap::snap_point_to_grid(tl, cx.grid_step()) - tl, u); + } + let Some(t) = (if copy { &self.copy_targets } else { &self.targets }) else { return d }; + let moved = rect + d; + let (adj, ov) = if cx.doc.setup.has_bleed() { + t.snap_rects_along(&[moved, cx.doc.setup.bleed_rect(moved)], u, cx.snap_tol()) + } else { + t.snap_rects_along(&[moved], u, cx.snap_tol()) + }; + self.guides = ov; + d + adj + } + fn end_drag(&mut self) { self.drag = None; self.click_art = None; @@ -433,7 +464,11 @@ impl Tool for ArtboardTool { out.push(Action::Begin(label(m.alt).into())); } self.drag = Some(Drag::Move { index, many, start, rect, began: true, copy: m.alt }); - let d = self.snap_move(cx, rect, p - start, m.alt); + // Shift held once the drag is under way keeps the move (or copy) to the level, + // upright or 45° line, as a Selection tool move does (#8580); a Shift-press draws + // or selects instead. + let d = move_delta(start, p, m.shift, cx.constrain_angle); + let d = if m.shift { self.snap_move_along(cx, rect, d, m.alt) } else { self.snap_move(cx, rect, d, m.alt) }; self.preview = Some(rect + d); let mut v = json!({ "index": index, "dx": d.x, "dy": d.y, "moveArt": self.move_art, "copy": m.alt }); if many { @@ -679,6 +714,11 @@ impl Tool for ArtboardTool { } fn cursor(&self, cx: &ToolContext, p: Point, m: Mods) -> Cursor { + // A move under way keeps the move cursor wherever the pointer is: Shift may keep the + // artboard to a line the pointer leaves, and the document shows the moved artboard. + if matches!(self.drag, Some(Drag::Move { began: true, .. })) { + return Cursor::Move; + } if self.edge_button_at(cx, p).is_some() { return Cursor::Arrow; } diff --git a/crates/tools/src/xform/artboard/tests.rs b/crates/tools/src/xform/artboard/tests.rs index 20c3128176..379f494d33 100644 --- a/crates/tools/src/xform/artboard/tests.rs +++ b/crates/tools/src/xform/artboard/tests.rs @@ -367,10 +367,20 @@ fn a_shift_drag_on_the_pasteboard_selects_the_artboards_it_touches() { assert_eq!(t.options()["selected"], json!([1, 2])); } -/// A drag begun without Shift still moves the artboard, and on the pasteboard still draws one; -/// Shift pressed during either no longer keeps the move at 45° or the new artboard square. +/// The `(dx, dy)` of an `artboard.move` preview. +fn moved_by(v: &Value) -> (f64, f64) { + (v["dx"].as_f64().unwrap(), v["dy"].as_f64().unwrap()) +} + +fn near(a: (f64, f64), b: (f64, f64)) -> bool { + (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9 +} + +/// Shift held once a move is under way keeps it to the level, upright or 45° line, at the length +/// dragged (#8580); without Shift it follows the pointer again. (A Shift-press draws or +/// selects rather than moving: `a_shift_drag_inside_an_artboard_draws_a_new_one`.) #[test] -fn a_plain_drag_still_moves_and_shift_no_longer_constrains_it() { +fn shift_held_during_a_move_keeps_it_to_its_line() { let d = two_boards(); let (s, p) = (Selection::default(), paint()); let mut c = cx(&d, &s, &p); @@ -378,15 +388,99 @@ fn a_plain_drag_still_moves_and_shift_no_longer_constrains_it() { let shift = Mods { shift: true, ..Default::default() }; let mut t = ArtboardTool::default(); t.pointer(&c, &ev(PointerKind::Down, 700.0, 100.0)); - let v = preview_params(&t.pointer(&c, &ev(PointerKind::Drag, 730.0, 110.0).with_mods(shift))); - assert_eq!((v["index"].as_u64(), v["dx"].as_f64(), v["dy"].as_f64()), (Some(1), Some(30.0), Some(10.0))); - assert_eq!(t.pointer(&c, &ev(PointerKind::Up, 730.0, 110.0).with_mods(shift)), vec![Action::Commit]); + let mut drag = |dx: f64, dy: f64, m: Mods| moved_by(&preview_params(&t.pointer(&c, &ev(PointerKind::Drag, 700.0 + dx, 100.0 + dy).with_mods(m)))); + assert!(near(drag(30.0, 10.0, shift), (1000f64.sqrt(), 0.0)), "level"); + assert!(near(drag(12.0, 40.0, shift), (0.0, 1744f64.sqrt())), "upright"); + let (dx, dy) = drag(30.0, 28.0, shift); + assert!(dx > 0.0 && (dx - dy).abs() < 1e-9, "45°: {dx} {dy}"); + // Shift released: the move follows the pointer. + assert_eq!(drag(30.0, 10.0, Mods::default()), (30.0, 10.0)); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, 730.0, 110.0)), vec![Action::Commit]); + // A new artboard drawn on the pasteboard isn't kept square by Shift held during the drag. t.pointer(&c, &ev(PointerKind::Down, 1000.0, 1000.0)); t.pointer(&c, &ev(PointerKind::Drag, 1100.0, 1050.0).with_mods(shift)); let a = t.pointer(&c, &ev(PointerKind::Up, 1100.0, 1050.0).with_mods(shift)); assert_eq!(a, create_artboard(Rect::new(1000.0, 1000.0, 1100.0, 1050.0))); } +/// An Alt-drag copy keeps to its line with Shift too, and the line turns with General › Constrain +/// Angle. +#[test] +fn shift_keeps_an_alt_drag_copy_to_its_line_from_the_constrain_angle() { + let d = two_boards(); + let (s, p) = (Selection::default(), paint()); + let mut c = cx(&d, &s, &p); + c.smart_guides = false; + let alt = Mods { alt: true, ..Default::default() }; + let both = Mods { alt: true, shift: true, ..Default::default() }; + let mut t = ArtboardTool::default(); + t.pointer(&c, &ev(PointerKind::Down, 700.0, 100.0).with_mods(alt)); + let v = preview_params(&t.pointer(&c, &ev(PointerKind::Drag, 730.0, 110.0).with_mods(both))); + assert!(near(moved_by(&v), (1000f64.sqrt(), 0.0)) && v["copy"] == true, "{v}"); + // Alt released and pressed again mid-drag: a constrained move, then a constrained copy again. + let a = t.pointer(&c, &ev(PointerKind::Drag, 730.0, 110.0).with_mods(Mods { shift: true, ..Default::default() })); + assert_eq!(a[..2], [Action::Cancel, Action::Begin("Move Artboard".into())]); + let v = preview_params(&a); + assert!(near(moved_by(&v), (1000f64.sqrt(), 0.0)) && v["copy"] == false, "{v}"); + let a = t.pointer(&c, &ev(PointerKind::Drag, 730.0, 110.0).with_mods(both)); + assert_eq!(a[..2], [Action::Cancel, Action::Begin("Duplicate Artboard".into())]); + assert!(near(moved_by(&preview_params(&a)), (1000f64.sqrt(), 0.0))); + t.pointer(&c, &ev(PointerKind::Up, 730.0, 110.0).with_mods(both)); + // Constrain Angle 30°: the lines run in 45° steps from 30° up the page (30° up, 15° down, …), + // and a drag 18.4° below level keeps to the one 15° below level (down the page is positive y). + c.constrain_angle = 30.0; + t.pointer(&c, &ev(PointerKind::Down, 700.0, 100.0)); + let (dx, dy) = + moved_by(&preview_params(&t.pointer(&c, &ev(PointerKind::Drag, 730.0, 110.0).with_mods(Mods { shift: true, ..Default::default() })))); + assert!((dy.atan2(dx).to_degrees() - 15.0).abs() < 1e-9, "{dx} {dy}"); +} + +/// Snaps slide a move Shift keeps to its line along that line: Smart Guides, the grid and whole +/// pixels never take it off the line. +#[test] +fn snaps_keep_a_shift_move_on_its_line() { + let d = two_boards(); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let mut c = cx(&d, &s, &p); + let mut t = ArtboardTool::default(); + let mut drag = |c: &ToolContext, dx: f64, dy: f64| { + t.pointer(c, &ev(PointerKind::Down, 700.0, 100.0)); + let v = moved_by(&preview_params(&t.pointer(c, &ev(PointerKind::Drag, 700.0 + dx, 100.0 + dy).with_mods(shift)))); + t.pointer(c, &ev(PointerKind::Up, 700.0 + dx, 100.0 + dy).with_mods(shift)); + v + }; + // Level, 101.5 pt left: the left edge, 1.5 pt past artboard 1's right edge (500), slides back + // onto it, and the move stays level. + assert!(near(drag(&c, -97.0, 30.0), (-100.0, 0.0))); + c.smart_guides = false; + c.snap_to_grid = true; + // Grid step 72 / 8 = 9: x 620.9 → 621, y stays 0 (not 9, where it would snap off the line). + assert!(near(drag(&c, 20.0, 6.0), (21.0, 0.0))); + c.snap_to_grid = false; + c.snap_to_pixel = true; + assert!(near(drag(&c, 10.0, 3.0), (10.0, 0.0))); +} + +/// While Shift keeps a move to its line the cursor stays the move cursor, also where the pointer +/// has left the moved artboard; before a press, Shift shows the crosshair of a drag that draws or +/// selects. +#[test] +fn shift_during_a_move_keeps_the_move_cursor() { + let mut d = two_boards(); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let mut t = ArtboardTool::default(); + let over = Point::new(1100.0, 250.0); + assert_eq!(t.cursor(&cx(&d, &s, &p), Point::new(700.0, 100.0), shift), Cursor::Crosshair); + t.pointer(&cx(&d, &s, &p), &ev(PointerKind::Down, 700.0, 100.0)); + let (dx, dy) = moved_by(&preview_params(&t.pointer(&cx(&d, &s, &p), &ev(PointerKind::Drag, over.x, over.y).with_mods(shift)))); + // The engine shows the preview: the level move leaves the pointer 50 pt below the artboard. + d.artboards[1].rect = d.artboards[1].rect + Vec2::new(dx, dy); + assert!(!d.artboards[1].rect.contains(over)); + assert_eq!(t.cursor(&cx(&d, &s, &p), over, shift), Cursor::Move); +} + /// Escape during a marquee or while a new artboard is being drawn ends the gesture without /// selecting or drawing anything and keeps the tool; the next Escape leaves it. #[test] diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index 7b91731691..b2d0fdadba 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -27,8 +27,12 @@ //! Brush Options' Key Color eyedropper sets `brushKeyColor` and `stop`: the next click samples into //! the open dialog (`brushKeyColor` UI request) and switches back. //! -//! Escape ends either pick without sampling and switches back to that tool. With neither pick +//! Escape ends an armed pick without sampling and switches back to that tool. With no pick //! armed, Escape is left to the application. +//! +//! Image Trace's Ignore Color eyedropper passes its bound document point to the panel, which +//! samples the original image pixels and ends the pick only when a color is accepted. A miss +//! stays armed; this tool changes neither paint nor selection. use std::collections::HashSet; @@ -51,6 +55,8 @@ pub struct EyedropperTool { text_selection: crate::text::TypeTool, /// Brush Options › Key Color (Hue Shift): sample into the dialog, then [`Self::stop`]. brush_key_color: bool, + /// Image Trace > Ignore Color: the panel's opaque document/object/revision binding. + image_trace_ignore_color: Option, /// The gradient mesh points the tool switched from had picked, each a mesh and a point index. mesh_points: Vec<(NodeId, usize)>, } @@ -512,6 +518,11 @@ impl Tool for EyedropperTool { if ev.kind != PointerKind::Down { return vec![]; } + if let Some(binding) = &self.image_trace_ignore_color { + // The panel knows whether this hits an opaque source pixel. It clears the binding + // and restores the previous tool only after accepting a color, not on a miss. + return vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "point": [ev.pos.x, ev.pos.y] }))]; + } let opts = sample_options(cx); if self.brush_key_color { let Some(c) = sample_color_at(cx, ev.pos) else { return vec![] }; @@ -573,6 +584,9 @@ impl Tool for EyedropperTool { if let Some(o) = options.as_object_mut() { o.insert("stop".into(), json!(self.stop)); o.insert("brushKeyColor".into(), json!(self.brush_key_color)); + if let Some(binding) = &self.image_trace_ignore_color { + o.insert("imageTraceIgnoreColor".into(), binding.clone()); + } if !self.mesh_points.is_empty() { let points: Vec = self.mesh_points.iter().map(|(id, index)| json!({"id": id.0, "index": index})).collect(); o.insert("meshPoints".into(), Value::Array(points)); @@ -587,6 +601,7 @@ impl Tool for EyedropperTool { match key { "stop" => self.stop = value.as_str().map(str::to_string), "brushKeyColor" => self.brush_key_color = value.as_bool().unwrap_or(false), + "imageTraceIgnoreColor" => self.image_trace_ignore_color = (!value.is_null()).then(|| value.clone()), "meshPoints" => self.mesh_points = crate::meshedit::points_of(value), "textSelection" => self.text_selection.set_option(key, value), _ => {} @@ -621,12 +636,15 @@ impl Tool for EyedropperTool { Cursor::Eyedropper } - /// Escape ends a gradient stop's or Key Color's pick without sampling and switches back to the - /// tool that armed it. + /// Escape ends the armed pick without sampling; Image Trace receives its cancellation reply. fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { if key != ToolKey::Escape || !self.picking() { return vec![]; } + if let Some(binding) = self.image_trace_ignore_color.take() { + let back = self.stop.take().unwrap_or_else(|| "selection".to_string()); + return vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({ "binding": binding, "cancel": true })), Action::SwitchTool(back)]; + } let back = self.stop.take().unwrap_or_else(|| "selection".to_string()); self.brush_key_color = false; vec![Action::SwitchTool(back)] @@ -648,9 +666,9 @@ impl Tool for EyedropperTool { } impl EyedropperTool { - /// Is a one-shot pick armed (a gradient stop's or Brush Options' Key Color)? + /// Is a gradient stop, Brush Key Color or Image Trace Ignore Color pick armed? fn picking(&self) -> bool { - self.stop.is_some() || self.brush_key_color + self.stop.is_some() || self.brush_key_color || self.image_trace_ignore_color.is_some() } } @@ -869,6 +887,96 @@ mod tests { assert_eq!(t.options(), json!({ "stop": null, "brushKeyColor": false })); } + #[test] + fn image_trace_sampling_keeps_forwarding_its_binding_until_the_panel_accepts_a_color() { + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let binding = json!({"doc": 7, "target": id.0, "revision": 11}); + for mods in [Mods::default(), Mods { alt: true, ..Default::default() }, Mods { alt: true, shift: true, ..Default::default() }] { + let mut t = EyedropperTool::default(); + t.set_option("stop", &json!("gradient")); + t.set_option("imageTraceIgnoreColor", &binding); + assert_eq!(t.options()["imageTraceIgnoreColor"], binding); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Move, -25.5, 400.25)).is_empty()); + assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, -25.5, 400.25)).is_empty()); + assert_eq!( + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, -25.5, 400.25).with_mods(mods)), + vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "point": [-25.5, 400.25]}))] + ); + assert_eq!(t.options()["imageTraceIgnoreColor"], binding, "a point is only a request until the panel accepts its source color"); + assert_eq!(t.options()["stop"], "gradient"); + assert!(t.claims_key(&cx, ToolKey::Escape)); + assert!(t.ends_on_escape(&cx)); + let next = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 20.0)); + assert_eq!(next, vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "point": [10.0, 20.0]}))]); + t.set_option("imageTraceIgnoreColor", &Value::Null); + t.set_option("stop", &Value::Null); + assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false})); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); + } + } + + #[test] + fn image_trace_escape_cancels_its_binding_and_restores_the_tool_once() { + let (d, id) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let binding = json!({"doc": 7, "target": id.0, "revision": 11}); + let mut t = EyedropperTool::default(); + assert!(!t.claims_key(&cx, ToolKey::Escape)); + assert!(!t.ends_on_escape(&cx)); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); + t.set_option("stop", &json!("selection")); + t.set_option("imageTraceIgnoreColor", &binding); + assert!(t.claims_key(&cx, ToolKey::Escape)); + assert!(t.ends_on_escape(&cx)); + assert!(!t.claims_key(&cx, ToolKey::Enter)); + assert!(t.key(&cx, ToolKey::Enter, Mods::default()).is_empty()); + assert_eq!(t.options()["imageTraceIgnoreColor"], binding); + assert!(t.drop_press(&cx).is_empty(), "a dropped press leaves this pick waiting too"); + assert_eq!(t.options()["imageTraceIgnoreColor"], binding); + assert_eq!( + t.key(&cx, ToolKey::Escape, Mods::default()), + vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "cancel": true})), Action::SwitchTool("selection".into())] + ); + assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false})); + assert!(!t.claims_key(&cx, ToolKey::Escape)); + assert!(!t.ends_on_escape(&cx)); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); + // A binding without a saved tool still claims its one Escape and returns to Selection. + t.set_option("imageTraceIgnoreColor", &binding); + assert!(t.claims_key(&cx, ToolKey::Escape) && t.ends_on_escape(&cx)); + assert_eq!( + t.key(&cx, ToolKey::Escape, Mods::default()), + vec![Action::Dialog("imageTraceIgnoreColor".into(), json!({"binding": binding, "cancel": true})), Action::SwitchTool("selection".into())] + ); + assert!(!t.claims_key(&cx, ToolKey::Escape) && !t.ends_on_escape(&cx)); + } + + #[test] + fn clearing_image_trace_sampling_preserves_existing_brush_and_stop_options() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = EyedropperTool::default(); + t.set_option("brushKeyColor", &json!(true)); + t.set_option("stop", &json!("selection")); + let original = t.options(); + t.set_option("imageTraceIgnoreColor", &json!({"doc": 7, "target": 8, "revision": 11})); + t.set_option("imageTraceIgnoreColor", &Value::Null); + assert_eq!(t.options(), original); + // Clearing Trace leaves the ordinary Brush pick armed, including its upstream Escape. + assert!(t.claims_key(&cx, ToolKey::Escape)); + assert!(t.ends_on_escape(&cx)); + assert!(t.key(&cx, ToolKey::Enter, Mods::default()).is_empty()); + assert_eq!(t.options(), original); + assert_eq!( + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 150.0, 150.0)), + vec![Action::Dialog("brushKeyColor".into(), json!({"color": color_json(&Color::WHITE)})), Action::SwitchTool("selection".into())] + ); + } + /// The hex of the colour a `paint.sampleColor` action samples. fn sampled_hex(a: &[Action]) -> String { let [Action::Exec(c, p)] = a else { panic!("one action: {a:?}") }; diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 0fc0d136b0..bba6a5d83d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -367,6 +367,7 @@ impl VectorcraftApp { // A panel's, a dialog's or the text input's commit journaled in the frame before. crate::panels::actions::after_journaled_edit(self); crate::scripts_menu::poll(self, ctx); + crate::dialogs::proof_setup::poll(self, ctx); if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 75a4f05164..fc04c051fc 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -519,6 +519,7 @@ impl VectorcraftApp { } self.ui.flyout = None; switched?; + crate::panels::image_trace::cancel_ignore_sampler(self, false); if let Some(g) = vectorcraft_tools::catalog::group_of(id) && let Some(slot) = self.ui.group_tool.get_mut(g) { diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index b6c7eaae97..70f5b4e81c 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -181,6 +181,7 @@ impl VectorcraftApp { /// injected until the batch was actually applied, so a burst of hidden ticks cannot queue /// several steps of a drag or replay them together later. pub fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + crate::canvas::capture_pointer_before_input(ctx, raw.viewport_id); self.fill_raw_input(ctx, raw); crate::font_menu::sync_wheel_target(self, ctx, raw.viewport_id); crate::font_menu::take_raw_wheel(ctx, raw); diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index be5ff73c54..6e1d229023 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -25,8 +25,8 @@ pub struct CanvasCache { /// last render took more than 8 ms, the canvas draws the frame shown reprojected and renders /// once the view has been still for [`canvas::STILL_SECS`]. pub waits_for_still: bool, - /// The cache key the canvas last asked for and when it first asked for it (seconds, egui's - /// input time), kept while [`Self::waits_for_still`] is set. + /// The cache key the canvas last asked for and when it first asked for its view (seconds, + /// egui's input time), kept while [`Self::waits_for_still`] is set. pub still: Option<(CacheKey, f64)>, /// The low-resolution frame that covers the parts of the canvas the frame shown leaves /// uncovered while it is drawn for a view it was not rendered for ([`canvas::Fill`]). diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 921bb23c4e..b4a8eee2a0 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -72,8 +72,9 @@ 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; use task_bar::task_bar; +pub(crate) use task_bar::{TASK_BAR_ACTIONS, TASK_BAR_CHIPS, is_task_bar_action, read_hidden_task_bar_actions}; #[cfg(test)] -pub(crate) use task_bar::{chip_paints, images_with_other_art}; +pub(crate) use task_bar::{bar_action_name, chip_paints, images_with_other_art, task_bar_offered}; pub(crate) use task_bar::{has_colors, task_bar_rect, task_bar_shows_fonts, task_bar_shows_type}; #[cfg(test)] use tool_overlays::{DIAL_RADIUS, HiddenMarks}; @@ -251,6 +252,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The meshes of the tools' shared paths. Likewise, a frame that does not draw the tools' // overlays drops them. let mut shared_paths = std::mem::take(&mut app.canvas.shared_paths); + let sampler_cancelled = crate::panels::image_trace::refresh_ignore_sampler(app); // A release ends the Image Trace panel's eye-button hold, also when the panel is no longer // drawn, so a later press elsewhere does not show the source image. if app.ui.trace_hold_source.is_some() && !ui.input(|i| i.pointer.any_down()) { @@ -263,7 +265,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if app.ui.home.is_some_and(|k| k != crate::menus::home_key(app)) { app.ui.home = None; } - if crate::menus::home_showing(app) { + let home_showing = crate::menus::home_showing(app); + observe_hidden_ignore_sampler_pointer(app, ui, home_showing); + if home_showing { // No IME owner this pass (`ime_caret_rect` stays None): the end-of-pass observation marks // the context absent and keeps any marked text as typed. home(app, ui, full); @@ -298,7 +302,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { scroll_bars(app, ui, rect, outer, &t); } let resp = ui.interact(rect, egui::Id::unique("canvas"), Sense::click_and_drag()); - canvas_input(app, ui, &resp, rect); + input_after_sampler_refresh(app, ui, &resp, rect, sampler_cancelled); let v = *app.view().unwrap_or(&View::default()); let xf = Xf::at(rect, &v, app.canvas_ui_zoom); // While the view pans, zooms or turns under the pointer, the art under it isn't hit-tested. @@ -355,8 +359,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { poll_worker(app, ui, key.doc); // With `waits_for_still` set (the web build, which has no render worker), a heavy document is // not rendered while only the view changes: the frame shown is drawn reprojected below, and the - // first frame after the view has been still for STILL_SECS renders. + // first frame after the view has been still for STILL_SECS renders. An edit meanwhile is drawn + // into the frame shown ([`edit_in_frame_shown`]). let wait = if app.canvas.waits_for_still { + edit_in_frame_shown(app, &key, &doc, &effects, &drawn, (mask_view, smooth_images)); let slow = app.canvas.last_ms > 8.0 && app.canvas.texture.is_some(); still_wait(&mut app.canvas.still, app.canvas.key.as_ref(), &key, slow, ui.input(|i| i.time)) } else { @@ -470,6 +476,272 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } +#[derive(Clone, Copy, Default)] +struct CanvasClick { + count: u8, + at: Option, +} + +fn pointer_before_input_id(viewport: egui::ViewportId) -> egui::Id { + egui::Id::unique("canvas-pointer-before-input").with(viewport) +} + +/// The existing host hook calls this before egui updates the pointer for this batch. +pub(crate) fn capture_pointer_before_input(ctx: &egui::Context, viewport: egui::ViewportId) { + let pointer = ctx.input_for(viewport, |i| i.pointer.clone()); + ctx.data_mut(|data| data.insert_temp(pointer_before_input_id(viewport), pointer)); +} + +/// Each release keeps egui's own qualification, including earlier releases in this batch. +fn canvas_pointer_releases(ui: &Ui) -> Vec { + let previous = ui.data(|data| data.get_temp::(pointer_before_input_id(ui.ctx().viewport_id()))).unwrap_or_default(); + let options = ui.ctx().options(|o| o.input_options); + let pixels_per_point = ui.ctx().pixels_per_point(); + ui.input(|i| { + let mut counts = [0usize; egui::NUM_POINTER_BUTTONS]; + for event in &i.events { + if let egui::Event::PointerButton { button, pressed: false, .. } = event { + counts[*button as usize] += 1; + } + } + i.events + .iter() + .enumerate() + .filter_map(|(index, event)| { + let egui::Event::PointerButton { pos, button, pressed: false, .. } = event else { return None }; + let clicked = if counts[*button as usize] == 1 { + i.pointer.button_clicked(*button) + } else { + // Aggregated flags cannot identify a later non-click release. Replay only + // an ambiguous button's prefix, before its Up, through egui's public API. + let mut before = i.clone(); + before.pointer = previous.clone(); + let raw = egui::RawInput { time: Some(i.time), events: i.events[..index].to_vec(), ..i.raw.clone() }; + before.begin_pass(raw, false, pixels_per_point, options).pointer.could_any_button_be_click() + }; + Some(IgnoreSamplerRelease { button: *button, at: *pos, clicked }) + }) + .collect() + }) +} + +/// Two non-sampler clicks replace egui's last two click times after a consumed pick. +#[derive(Clone, Copy, Default)] +struct IgnoreSamplerClicks { + last: Option<(f64, Pos2)>, + remaining: u8, +} + +fn ignore_sampler_primary_id(id: egui::Id) -> egui::Id { + id.with("image-trace-consumed-primary") +} + +fn ignore_sampler_owns_primary(ui: &Ui, id: egui::Id) -> bool { + ui.data(|data| data.get_temp::(ignore_sampler_primary_id(id)).unwrap_or(false)) +} + +fn reset_ignore_sampler_clicks(ui: &Ui, id: egui::Id) { + ui.data_mut(|data| data.insert_temp(id.with("image-trace-clicks"), IgnoreSamplerClicks { last: None, remaining: 2 })); +} + +/// Reclassify only the two clicks whose raw history can still contain a consumed pick. +/// Other widgets' clicks count too, as they do in egui; its pointer state stays untouched. +fn ignore_sampler_clicks(ui: &Ui, id: egui::Id, consumed: bool, releases: &[IgnoreSamplerRelease]) { + ui.data_mut(|data| data.remove::(id.with("image-trace-click-count"))); + if !releases.iter().any(|release| release.clicked) { + return; + } + if consumed { + reset_ignore_sampler_clicks(ui, id); + return; + } + let time = ui.input(|i| i.time); + for release in releases.iter().filter(|release| release.clicked) { + record_ignore_sampler_click(ui, id, release.at, time, release.button == egui::PointerButton::Primary); + } +} + +fn record_ignore_sampler_click(ui: &Ui, id: egui::Id, at: Pos2, time: f64, primary: bool) { + let (delay, distance) = ui.ctx().options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_dist)); + ui.data_mut(|data| { + let history_id = id.with("image-trace-clicks"); + let Some(mut clicks) = data.remove_temp::(history_id) else { + if primary { + data.remove::(id.with("image-trace-click-count")); + } + return; + }; + let double = clicks.last.is_some_and(|(last, pos)| time - last < delay && pos.distance_sq(at) < distance * distance); + if primary { + data.insert_temp(id.with("image-trace-click-count"), CanvasClick { count: if double { 2 } else { 1 }, at: Some(at) }); + } + clicks.last = Some((time, at)); + clicks.remaining -= 1; + if clicks.remaining != 0 { + data.insert_temp(history_id, clicks); + } + }); +} + +fn primary_click(ui: &Ui, resp: &egui::Response) -> CanvasClick { + if !resp.clicked_by(egui::PointerButton::Primary) { + return CanvasClick::default(); + } + ui.data(|data| data.get_temp::(resp.id.with("image-trace-click-count"))).unwrap_or_else(|| { + let count = if resp.triple_clicked() { + 3 + } else if resp.double_clicked() { + 2 + } else { + 1 + }; + let at = ui.data(|data| data.get_temp::(resp.id.with("canvas-qualified-primary-release"))); + CanvasClick { count, at } + }) +} + +fn primary_click_count(ui: &Ui, resp: &egui::Response) -> u8 { + primary_click(ui, resp).count +} + +/// Remove only the pointer sequence acquired by this sampler, never a view or tool drag. +fn clear_ignore_sampler_gesture(ui: &Ui, id: egui::Id) { + ui.data_mut(|data| { + data.remove::(ignore_sampler_primary_id(id)); + if matches!(data.get_temp::(drag::drag_id()), Some(Drag::Gesture)) { + data.remove::(drag::drag_id()); + data.remove::(drag::drag_pos_id()); + data.remove::(drag::tool_drag_doc_id()); + data.remove::(drag::tool_press_doc_id()); + } + }); +} + +#[derive(Clone, Copy)] +struct IgnoreSamplerRelease { + button: egui::PointerButton, + at: Pos2, + clicked: bool, +} + +#[derive(Default)] +struct IgnoreSamplerPointer { + owned: bool, + replaced: bool, + ordinary_pressed: bool, + consumed_release: bool, + releases: Vec, +} + +/// Attribute a fresh press after an owned release before egui's per-frame flags lose their order. +fn ignore_sampler_pointer_frame(ui: &Ui, id: egui::Id, cancelled: bool, releases: &[IgnoreSamplerRelease]) -> IgnoreSamplerPointer { + let owned = ignore_sampler_owns_primary(ui, id); + if !owned && !cancelled { + return IgnoreSamplerPointer::default(); + } + ui.input(|i| { + let mut frame = IgnoreSamplerPointer { owned, ..Default::default() }; + let mut first_press_owned = cancelled; + let mut releases = releases.iter(); + for event in &i.events { + if let egui::Event::PointerButton { pos, button, pressed, .. } = event { + if *pressed { + if *button == egui::PointerButton::Primary { + frame.replaced |= frame.owned; + // An observed old Up ends that cancelled sequence; without it, + // a fresh invalid press keeps the existing cancellation gate. + frame.owned = first_press_owned && !frame.consumed_release; + first_press_owned = false; + frame.ordinary_pressed |= !frame.owned; + } + } else { + let clicked = releases.next().is_some_and(|release| release.clicked); + ignore_sampler_release(&mut frame, *button, *pos, clicked); + } + } + } + frame + }) +} + +fn ignore_sampler_release(frame: &mut IgnoreSamplerPointer, button: egui::PointerButton, at: Pos2, clicked: bool) { + if button == egui::PointerButton::Primary && frame.owned { + frame.consumed_release = true; + frame.releases.clear(); + } else if frame.consumed_release { + frame.releases.push(IgnoreSamplerRelease { button, at, clicked }); + } +} + +fn ignore_sampler_frame_clicks(ui: &Ui, id: egui::Id, frame: &IgnoreSamplerPointer, consumed: bool, releases: &[IgnoreSamplerRelease]) { + if !frame.consumed_release || !frame.ordinary_pressed { + ignore_sampler_clicks(ui, id, consumed, releases); + return; + } + // Consume the old sequence, then classify only subsequent ordinary releases. A new Down + // still reaches the tool when the last release belongs to the consumed sequence. + reset_ignore_sampler_clicks(ui, id); + ui.data_mut(|data| data.insert_temp(id.with("image-trace-click-count"), CanvasClick::default())); + let time = ui.input(|i| i.time); + for release in &frame.releases { + let primary = release.button == egui::PointerButton::Primary; + if release.clicked { + record_ignore_sampler_click(ui, id, release.at, time, primary); + } + } +} + +fn begin_ignore_sampler_pointer(ui: &Ui, id: egui::Id, cancelled: bool) -> (bool, bool) { + let releases = canvas_pointer_releases(ui); + ui.data_mut(|data| { + let position_id = id.with("canvas-qualified-primary-release"); + data.remove::(position_id); + if let Some(release) = releases.iter().rev().find(|release| release.clicked && release.button == egui::PointerButton::Primary) { + data.insert_temp(position_id, release.at); + } + }); + let frame = ignore_sampler_pointer_frame(ui, id, cancelled, &releases); + if frame.replaced { + // This also replaces an abandoned sampler Down whose release was not observed. + clear_ignore_sampler_gesture(ui, id); + } + if frame.owned { + ui.data_mut(|data| data.insert_temp(ignore_sampler_primary_id(id), true)); + } + let consumed = frame.owned && ui.input(|i| i.pointer.primary_pressed() || i.pointer.primary_released() || i.pointer.primary_down()); + ignore_sampler_frame_clicks(ui, id, &frame, consumed, &releases); + (consumed, frame.ordinary_pressed) +} + +fn end_ignore_sampler_pointer(ui: &Ui, id: egui::Id) { + // A valid Down can acquire ownership and complete in the same frame. + if ignore_sampler_owns_primary(ui, id) && !ui.input(|i| i.pointer.primary_down()) { + if ui.input(|i| i.pointer.button_clicked(egui::PointerButton::Primary)) { + reset_ignore_sampler_clicks(ui, id); + } + clear_ignore_sampler_gesture(ui, id); + } +} + +fn observe_hidden_ignore_sampler_pointer(app: &VectorcraftApp, ui: &Ui, home_showing: bool) { + if home_showing || app.session.active().is_none() { + // Home and the empty window still advance egui's click history. Observe the same + // correction there so it retires after the two ordinary clicks that replace a pick. + let id = egui::Id::unique("canvas"); + begin_ignore_sampler_pointer(ui, id, false); + end_ignore_sampler_pointer(ui, id); + } +} + +/// A sampler press keeps its release, even if its Down completes or its binding expires held. +fn input_after_sampler_refresh(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect, cancelled: bool) { + let (consumed, ordinary_pressed) = begin_ignore_sampler_pointer(ui, resp.id, cancelled); + if !consumed && (ordinary_pressed || !cancelled || !ui.input(|i| i.pointer.any_pressed())) { + canvas_input(app, ui, resp, rect); + } + end_ignore_sampler_pointer(ui, resp.id); +} + /// The pointer on the canvas: the tool's input, unless the context menu or the 3D gizmo has the press. pub(crate) fn canvas_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect: egui::Rect) { if app.ui.dialog.as_ref().is_some_and(crate::dialogs::revolve_gizmo::active) { @@ -643,7 +915,6 @@ fn cache_key( rich_black: app.session.prefs.black_on_screen == "rich", // A tool's drag on the canvas, during an interaction (not a dialog's preview). dragging: app.session.in_interaction() && ui.data(|d| d.get_temp::(drag_id())) == Some(Drag::Tool), - // The Image Trace panel's eye button, while it is held. trace_source: app.ui.trace_hold_source.clone(), // Preferences › Performance › Use Monitor Profile for Canvas. display: app.display_profile.key(app.session.prefs.monitor_profile_display), @@ -881,6 +1152,72 @@ struct Frame<'a> { /// shows the document's paper without the art: about a frame at 60 Hz. pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::from_millis(16); +/// Draw `region` of `frame` again, into the texture of the frame shown, which then shows `frame`'s +/// key: only the document changed since the frame shown, in that part of it +/// ([`changed_pixels`]). `None`: nothing in view changed. `last_ms` stays the whole frame's. +fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]>) { + let Frame { key, doc, effects, view, opts, pixel, .. } = frame; + let t0 = now_ms(); + if region.is_none() { + // Nothing in view to draw again: what was made to measure the edit isn't drawn. + app.canvas.renderer.let_go_of_measured(); + } + let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); + if let (Some([x0, y0, x1, y1]), Some(tex)) = (region, &mut app.canvas.texture) { + let renderer = &mut app.canvas.renderer; + let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * *view; + let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, opts)); + let width = part.width; + crate::display_profile::convert_over(display.as_deref(), &mut part.pixels, width, part_view, key.over()); + let color = color_image(&part); + let options = if pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR }; + tex.set_partial([x0 as usize, y0 as usize], color, options); + app.canvas.moved |= app.canvas.renderer.stats.moved > 0; + } + app.canvas.key = Some((*key).clone()); + app.canvas.shown = Some(((*doc).clone(), opts.clone())); + app.perf.render_ms = now_ms() - t0; +} + +/// With `waits_for_still` set (the web build) and the last render slow, an edit while the view +/// moves (a tool's drag that scrolls the view at an edge of the canvas, or a wheel scroll during a +/// drag) is drawn into the frame shown, at the view it was rendered for: the part the edit changed +/// only ([`changed_pixels`]). The frame shown then stays drawn reprojected with the view, and the +/// canvas renders whole once the view has been still for [`STILL_SECS`], as for a view change +/// without an edit (#8688). When more than the view and the document differ from the frame shown, +/// or the edit changed more than half of it, nothing is drawn here: the frame renders whole. +fn edit_in_frame_shown( + app: &mut VectorcraftApp, + key: &CacheKey, + doc: &std::sync::Arc, + effects: &vectorcraft_plugins::deferred::Deferrals, + drawn: &View, + (mask_view, smooth_images): (Option, bool), +) { + let slow = app.canvas.last_ms > 8.0 && app.canvas.texture.is_some(); + let Some(shown) = app.canvas.key.clone().filter(|_| slow) else { return }; + let at_shown = CacheKey { + zoom: shown.zoom, + cx: shown.cx, + cy: shown.cy, + w: shown.w, + h: shown.h, + ppp: shown.ppp, + rot: shown.rot, + pixel: shown.pixel, + ..key.clone() + }; + if at_shown == shown || at_shown == *key || shown.pixel.is_some() != key.pixel.is_some() { + return; + } + let v = View { center: Point::new(shown.cx, shown.cy), zoom: shown.zoom, rotation: shown.rot, ..*drawn }; + let (w, h, view) = frame_view(at_shown.pixel, (at_shown.w, at_shown.h), &v, at_shown.ppp); + let opts = frame_options(app, &at_shown, mask_view, smooth_images); + if let Some(region) = changed_pixels(app, &at_shown, doc, &opts, view, w, h) { + draw_changed(app, &Frame { key: &at_shown, doc, effects, size: (w, h), view, opts, pixel: at_shown.pixel }, region); + } +} + fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { let Frame { key, doc, effects, size: (w, h), view, opts, pixel } = frame; // Frames that would be slow on this thread (the last one took over 8 ms) go @@ -904,27 +1241,7 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { match (&mut app.canvas.worker, heavy, changed) { // Only the document changed since the frame shown, in a part of it: that part is // rendered again, here, into the texture. `last_ms` stays the whole frame's. - (_, _, Some(region)) => { - let t0 = now_ms(); - if region.is_none() { - // Nothing in view to draw again: what was made to measure the edit isn't drawn. - app.canvas.renderer.let_go_of_measured(); - } - if let (Some([x0, y0, x1, y1]), Some(tex)) = (region, &mut app.canvas.texture) { - let renderer = &mut app.canvas.renderer; - let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * view; - let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, &opts)); - let width = part.width; - crate::display_profile::convert_over(display.as_deref(), &mut part.pixels, width, part_view, key.over()); - let color = color_image(&part); - let options = if pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR }; - tex.set_partial([x0 as usize, y0 as usize], color, options); - app.canvas.moved |= app.canvas.renderer.stats.moved > 0; - } - app.canvas.key = Some(key.clone()); - app.canvas.shown = Some((doc.clone(), opts.clone())); - app.perf.render_ms = now_ms() - t0; - } + (_, _, Some(region)) => draw_changed(app, &Frame { key, doc, effects, size: (w, h), view, opts, pixel }, region), (Some(worker), true, None) => { // The worker draws the frame: what this thread's renderer made to measure the edit // isn't drawn here. diff --git a/crates/ui-egui/src/canvas/cursor.rs b/crates/ui-egui/src/canvas/cursor.rs index 864a708e34..d9e589c246 100644 --- a/crates/ui-egui/src/canvas/cursor.rs +++ b/crates/ui-egui/src/canvas/cursor.rs @@ -51,11 +51,13 @@ pub(super) fn hover_wait(moved: &mut Option<(ViewKey, f64)>, key: ViewKey, now: /// Note that the canvas asks for `key` at time `now` (seconds, egui's input time) → how many more /// seconds it draws the frame `shown` reprojected instead of rendering `key`: while the last -/// render was `slow`, only the view differs between the two, and the canvas has asked for `key` -/// for less than [`STILL_SECS`]. `still` holds the key last asked for and when the canvas first -/// asked for it. None: the canvas renders `key` now, unless it is the frame shown. +/// render was `slow`, only the view differs between the two, and the canvas has asked for the view +/// of `key` for less than [`STILL_SECS`]. `still` holds the key last asked for and when the canvas first +/// asked for its view. An edit leaves that time as it is: with the view still and edits drawn into +/// the frame shown at each step of a drag, the canvas still renders whole once the view has been +/// still for [`STILL_SECS`]. None: the canvas renders `key` now, unless it is the frame shown. pub(super) fn still_wait(still: &mut Option<(CacheKey, f64)>, shown: Option<&CacheKey>, key: &CacheKey, slow: bool, now: f64) -> Option { - if still.as_ref().is_none_or(|(k, _)| k != key) { + if still.as_ref().is_none_or(|(k, _)| !same_view(k, key)) { *still = Some((key.clone(), now)); } let waited = still.as_ref().map_or(0.0, |(_, at)| now - at); @@ -64,6 +66,12 @@ pub(super) fn still_wait(still: &mut Option<(CacheKey, f64)>, shown: Option<&Cac (slow && waiting && shown.is_some_and(|s| s != key && only_view_differs(s, key))).then_some(STILL_SECS - waited) } +/// Whether two cache keys are of the same document at the same view (zoom, center, rotation, +/// canvas size, pixel density and Pixel Preview's document pixels), whatever else differs. +fn same_view(a: &CacheKey, b: &CacheKey) -> bool { + (a.doc, a.zoom, a.cx, a.cy, a.w, a.h, a.ppp, a.rot, a.pixel) == (b.doc, b.zoom, b.cx, b.cy, b.w, b.h, b.ppp, b.rot, b.pixel) +} + /// Whether two cache keys differ only in the view (zoom, center, rotation, canvas size, pixel /// density and Pixel Preview's document pixels), with Pixel Preview on in both or off in both. pub(super) fn only_view_differs(a: &CacheKey, b: &CacheKey) -> bool { diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index 36188617ac..512df6e9a9 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -380,6 +380,9 @@ pub(crate) fn end_art_move(app: &mut VectorcraftApp, ctx: &egui::Context) { /// Send a pointer event to the active tool and act on UI requests (dialogs, tool switches). pub fn dispatch(app: &mut VectorcraftApp, ev: &PointerEvent, view: vectorcraft_engine::ViewInfo) { + if ev.kind == PointerKind::Down && crate::panels::image_trace::discard_stale_ignore_click(app) { + return; + } // A press lent to a selection tool (Cmd/Ctrl held) does not use the tool of a held key. if ev.kind == PointerKind::Down && app.session.lent_tool_id(&ev.mods).is_none() { crate::shortcuts::note_tool_use(app); @@ -422,11 +425,27 @@ fn pressed_with(app: &mut VectorcraftApp, index: Option, pos: Point, tool pub fn apply_requests(app: &mut VectorcraftApp, r: vectorcraft_engine::Result>) { match r { Ok(reqs) => { + let mut sampler_return = None; for r in reqs { match r { - vectorcraft_engine::UiRequest::Dialog(kind, p) => crate::dialogs::open_tool_dialog(app, &kind, p), + vectorcraft_engine::UiRequest::Dialog(kind, p) => { + let back = if kind == "imageTraceIgnoreColor" && p["cancel"] == true { + app.ui.trace_ignore_sampler.as_ref().map(|sampler| sampler.back.clone()) + } else { + None + }; + crate::dialogs::open_tool_dialog(app, &kind, p); + // A matching callback must actually consume the active sampler. + sampler_return = back.filter(|_| app.ui.trace_ignore_sampler.is_none()); + } vectorcraft_engine::UiRequest::Panel(panel) => activate_panel(app, &panel), - vectorcraft_engine::UiRequest::SwitchTool(t) => app.select_tool(&t), + vectorcraft_engine::UiRequest::SwitchTool(t) => { + if sampler_return.take().is_some_and(|back| back == t) { + app.return_to_tool(&t); + } else { + app.select_tool(&t); + } + } vectorcraft_engine::UiRequest::Status(msg) => app.status(msg), vectorcraft_engine::UiRequest::Place(p) => crate::place::place_from_cursor(app, &p), // In the document the press was made in, which may no longer be the active one. diff --git a/crates/ui-egui/src/canvas/input.rs b/crates/ui-egui/src/canvas/input.rs index 36f3cb2a5f..a6a0509de5 100644 --- a/crates/ui-egui/src/canvas/input.rs +++ b/crates/ui-egui/src/canvas/input.rs @@ -140,7 +140,7 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo drag_held(app, ui, &f, d, p); } else { // The drag ends where its button went up: the moves after the release in this frame are hover. - drag_released(app, ui, &f, d, release_pos(ui, button).unwrap_or(p)); + drag_released(app, ui, &f, d, release_pos(ui, button, false).unwrap_or(p)); } } else if let Some(p) = hover_tool // A press on an artboard's name starts no drag: the moves while it is held are not hover. @@ -190,15 +190,18 @@ pub(super) fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respo .unwrap_or(m.shift); select_named_artboard(app, i, shift || release_shift); } - if resp.double_clicked() + let click = super::primary_click(ui, resp); + if !super::ignore_sampler_owns_primary(ui, resp.id) + && click.count == 2 && !f.modal - && let Some(p) = at + && let Some(p) = click.at.or(at) { double_click(app, ui, &f, p); } - if resp.triple_clicked() + if !super::ignore_sampler_owns_primary(ui, resp.id) + && click.count == 3 && !f.modal - && let Some(p) = at + && let Some(p) = click.at.or(at) { triple_click(app, ui, &f, p); } @@ -339,7 +342,7 @@ fn begin_drag(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { Drag::RotateView { start_angle: (p.y - c.y).atan2(p.x - c.x) as f64, start_rot: v.rotation, snaps: !space } } else { // Cmd with another tool drags with the selection tool used last (the session lends it). - let ev = PointerEvent { + let mut ev = PointerEvent { kind: PointerKind::Down, pos: xf.to_doc(p), mods: mods(m, space), @@ -347,9 +350,25 @@ fn begin_drag(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { pressure: pen_pressure(ui, app, true), pen: pen_pose(app, &xf), }; + // Only a Down actually sent to this sampler owns the gesture. Cmd/Ctrl's borrowed + // selection press keeps the ordinary tool path. + let sampler = app.ui.trace_ignore_sampler.is_some() && tool == "eyedropper" && app.session.lent_tool_id(&ev.mods).is_none(); + if sampler { + // A later hover move is not the source pixel that was pressed. + let pressed = ui.input(|i| { + i.events.iter().find_map(|event| match event { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => Some(*pos), + _ => None, + }) + }); + if let Some(pressed) = pressed { + ev.pos = xf.to_doc(pressed); + } + ui.data_mut(|data| data.insert_temp(super::ignore_sampler_primary_id(resp.id), true)); + } dispatch(app, &ev, view); crate::document_drag::begin(app, ui.ctx(), ev.pos); - Drag::Tool + if sampler { Drag::Gesture } else { Drag::Tool } }; // A drag of the Zoom, Hand or Rotate View tool uses the tool of a held shortcut; held Space's // view tools are not that tool. @@ -611,7 +630,7 @@ fn drag_released(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, d: Drag, p: Po // The second click of a double-click: don't fit another artboard on this release. // A double-click on an object does not open Artboard Options. Empty artboard // space still does. - if resp.double_clicked() && app.session.tool_id() == "artboard" { + if super::primary_click_count(ui, resp) == 2 && app.session.tool_id() == "artboard" { app.session.set_tool_option("suppressFitClick", &json!(true)); } // A move that came in the release's own frame shapes the preview first: the @@ -714,13 +733,14 @@ fn triple_click(app: &mut VectorcraftApp, ui: &Ui, f: &Pointing, p: Pos2) { dispatch(app, &ev, view); } -/// Where `button` went up in this frame, if it did. -fn release_pos(ui: &Ui, button: egui::PointerButton) -> Option { +/// Where `button` went up: the first release ends a drag, the last classifies this frame's click. +fn release_pos(ui: &Ui, button: egui::PointerButton, last: bool) -> Option { ui.input(|i| { - i.events.iter().find_map(|e| match e { + let mut releases = i.events.iter().filter_map(|e| match e { egui::Event::PointerButton { pos, button: b, pressed: false, .. } if *b == button => Some(*pos), _ => None, - }) + }); + if last { releases.next_back() } else { releases.next() } }) } diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index c133c003f8..03ced4f7c6 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -19,6 +19,14 @@ pub(crate) fn task_bar_shows_fonts(ctx: &egui::Context) -> bool { task_bar_rect(ctx).is_some() && ctx.data(|d| d.get_temp::(task_bar_id().with("fonts")).unwrap_or(false)) } +/// The actions and chips the Contextual Task Bar offered where it was last drawn, before Bar +/// Actions left any out, as More Options › Bar Actions lists them: each one's name, its id in +/// [`TASK_BAR_ACTIONS`] or [`TASK_BAR_CHIPS`] (none: Bar Actions cannot turn it off) and whether it +/// shows. +pub(crate) fn task_bar_offered(ctx: &egui::Context) -> Vec<(&'static str, Option<&'static str>, bool)> { + ctx.data(|d| d.get_temp(task_bar_id().with("offered")).unwrap_or_default()) +} + /// Whether the objects `ids` (or anything inside them) are painted with a colour: a solid colour, /// a gradient's stops or a mesh's points, which Recolor Artwork can change. pub(crate) fn has_colors(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> bool { @@ -182,7 +190,10 @@ pub(crate) fn task_bar_shows_type(app: &VectorcraftApp) -> bool { /// On a blank canvas, a document with no artwork and a selection tool in use, it sits under the /// active artboard and offers Draw (Pencil) and Place Image. /// Its handle drags it anywhere on the canvas; unpinned it keeps that offset as it follows the -/// selection, pinned it stays put ([`crate::state::TaskBarPlace`]). +/// selection, pinned it stays put ([`crate::state::TaskBarPlace`]). More Options › Bar Actions +/// turns each action and chip the bar offers on or off ([`TASK_BAR_ACTIONS`], [`TASK_BAR_CHIPS`]); +/// the bar leaves out the ones that are off, and Reset Bar Actions shows them all again. With every +/// one of them off, the bar still shows its handle and More Options, where they turn back on. pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { let t = Tokens::get(ui.ctx()); let on_artboards = app.session.tool_id() == "artboard"; @@ -351,6 +362,13 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { let paints = chip_paints(app, ui.ctx()); let colored = has_colors(&st.doc, &st.selection.objects); let doc = st.uid; + // Every action and chip the bar offers here, with its name and its id in TASK_BAR_ACTIONS or + // TASK_BAR_CHIPS (none: Bar Actions cannot turn it off), for More Options › Bar Actions; the + // ones that are off there are left out of the bar. + let hidden = &app.ui.task_bar_hidden_actions; + let mut offered: Vec<(&'static str, Option<&'static str>)> = + items.iter().map(|(label, _, cmd, params)| (*label, action_id(cmd, params))).collect(); + items.retain(|(_, _, cmd, params)| action_id(cmd, params).is_none_or(|a| !hidden.contains(a))); let bounds = xf.rect.shrink(8.0); // The canvas's width less the frame's margins and stroke. let room = bounds.width() - BAR_FRAME; @@ -371,6 +389,13 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { .into_iter() .filter_map(|(shown, chip)| shown.then_some(chip)) .collect(); + offered.extend(chips.iter().map(|c| (c.label(shape.is_some()), Some(c.id(shape.is_some()))))); + let chips: Vec = chips.into_iter().filter(|c| !hidden.contains(c.id(shape.is_some()))).collect(); + // Bar Actions reads this list through task_bar_offered while its menu is open. + let offered: Vec<(&'static str, Option<&'static str>, bool)> = + offered.into_iter().map(|(label, action)| (label, action, action.is_none_or(|a| !hidden.contains(a)))).collect(); + ui.ctx().data_mut(|d| d.insert_temp(task_bar_id().with("offered"), offered)); + let any_hidden = !hidden.is_empty(); let widths: Vec = items.iter().map(|(label, _, cmd, _)| item_width(ui, label, cmd)).collect(); let fidelity = app.session.tool_options()["fidelity"].as_f64(); let font_w = fonts.then(|| { @@ -498,6 +523,21 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { run = Some((cmd, json!({}))); } } + // The actions and chips the bar offers for this selection or tool, each + // checked while it shows, which turns it on or off; then Reset Bar + // Actions, which shows every action again. + ui.menu_button(format!(" {}", tl!("Bar Actions")), |ui| { + ui.set_min_width(170.0); + for (label, action, shown) in task_bar_offered(ui.ctx()) { + let Some(action) = action else { continue }; + if widgets::menu_item_name(ui, bar_action_name(label), true, shown) { + run = Some(("window.taskBar.actions", json!({ "action": action }))); + } + } + }); + if widgets::menu_item(ui, tl!("Reset Bar Actions"), any_hidden, false) { + run = Some(("window.taskBar.resetActions", json!({}))); + } ui.separator(); if widgets::menu_item(ui, tl!("Show Properties Panel"), true, false) { run = Some(("window.panel", json!({"panel": "properties"}))); @@ -579,6 +619,112 @@ impl Chip { Chip::Recolor | Chip::Lock => 30.0, } } + + /// The chip's id in [`TASK_BAR_CHIPS`]; Lock is `shapeProperties` while it shows a basic + /// `shape`'s properties. + fn id(self, shape: bool) -> &'static str { + match self { + Chip::Fill => "fill", + Chip::Stroke => "stroke", + Chip::Recolor => "recolor", + Chip::Lock if shape => "shapeProperties", + Chip::Lock => "lock", + } + } + + /// The chip's name in More Options › Bar Actions, translated. + fn label(self, shape: bool) -> &'static str { + match self { + Chip::Fill => tl!("Fill"), + Chip::Stroke => tl!("Stroke"), + Chip::Recolor => tl!("Recolor Artwork"), + Chip::Lock if shape => tl!("Shape Properties"), + Chip::Lock => tl!("Lock"), + } + } +} + +/// The Contextual Task Bar's actions that More Options › Bar Actions turns on or off +/// (`window.taskBar.actions {action, visible?}`): each action's id, the command its button runs and +/// the `tool` that command names, if any. An action that is off stays out of the bar, and More +/// Options does not list it either; turning one off changes only the bar. Every action starts on. +pub(crate) const TASK_BAR_ACTIONS: [(&str, &str, Option<&str>); 37] = [ + ("imageTrace", TASK_BAR_IMAGE_TRACE, None), + ("cropImage", "ui.cropImage", None), + ("removeBackground", crate::addons::image::REMOVE_BACKGROUND, None), + ("removeAnchorPoints", "path.removeAnchors", None), + ("join", "path.join", None), + ("cutPath", "path.cutAtAnchors", None), + ("convertToCorner", TASK_BAR_TO_CORNER, None), + ("convertToSmooth", TASK_BAR_TO_SMOOTH, None), + ("group", "object.group", None), + ("makeClippingMask", "object.clippingMask.make", None), + ("unite", "object.pathfinder.unite", None), + ("expand", "imageTrace.expand", None), + ("editClippingPath", "object.clippingMask.editMask", None), + ("releaseClippingMask", "object.clippingMask.release", None), + ("ungroup", "object.ungroup", None), + ("isolate", "object.isolate", None), + ("editPath", "tool.select", Some("directSelection")), + ("releaseCompoundPath", "object.compoundPath.release", None), + ("createOutlines", "type.createOutlines", None), + ("convertToPointType", "type.convertToPointType", None), + ("convertToAreaType", "type.convertToAreaType", None), + ("typeOnPathOptions", "type.pathOptions", None), + ("centerOnTop", "type.pathCenter.top", None), + ("centerOnBottom", "type.pathCenter.bottom", None), + ("dynamicText", "type.dynamicText", None), + ("offsetPath", "object.path.offsetPath", None), + ("simplify", "object.path.simplify", None), + ("smooth", "object.path.smooth", None), + ("duplicate", "edit.duplicate", None), + ("drawPencil", "tool.select", Some("pencil")), + ("placeImage", "file.place", None), + ("fidelity", TASK_BAR_FIDELITY, None), + ("smoothToolOptions", "tool.options", Some("smooth")), + ("resizeArtboard", TASK_BAR_ARTBOARD_OPTIONS, None), + ("duplicateArtboards", TASK_BAR_DUPLICATE_ARTBOARDS, None), + ("rearrangeArtboards", TASK_BAR_REARRANGE_ARTBOARDS, None), + ("exportArtboards", "file.exportForScreens", None), +]; + +/// The ids of the Contextual Task Bar's chips that More Options › Bar Actions turns on or off, +/// as [`TASK_BAR_ACTIONS`] are. +pub(crate) const TASK_BAR_CHIPS: [&str; 5] = ["fill", "stroke", "recolor", "lock", "shapeProperties"]; + +/// Whether `id` names one of the Contextual Task Bar's actions or chips. +pub(crate) fn is_task_bar_action(id: &str) -> bool { + TASK_BAR_ACTIONS.iter().any(|a| a.0 == id) || TASK_BAR_CHIPS.contains(&id) +} + +/// The id in [`TASK_BAR_ACTIONS`] of the bar's item that runs `cmd` with `params`. +fn action_id(cmd: &str, params: &serde_json::Value) -> Option<&'static str> { + let tool = params.get("tool").and_then(serde_json::Value::as_str); + TASK_BAR_ACTIONS.iter().find(|(_, c, t)| *c == cmd && *t == tool).map(|a| a.0) +} + +/// The name More Options › Bar Actions lists for the bar's item `label`: without a field's colon +/// (a full-width one too), the space some languages put before it, or a final ellipsis (`…` or +/// `...`), in whichever order they come. +pub(crate) fn bar_action_name(label: &str) -> &str { + let mut name = label.trim_end(); + loop { + let rest = name.trim_end_matches([':', ':', '…']); + let rest = rest.strip_suffix("...").unwrap_or(rest).trim_end(); + if rest == name { + return name; + } + name = rest; + } +} + +/// Reads the Contextual Task Bar's actions and chips that are off, as kept in the preferences. Ids +/// the bar does not have are dropped, and a value that is not a list of strings reads as none off, +/// so the bar shows every action. +pub(crate) fn read_hidden_task_bar_actions<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + let value = ::deserialize(d)?; + let ids = value.as_array().into_iter().flatten().filter_map(serde_json::Value::as_str); + Ok(ids.filter(|id| is_task_bar_action(id)).map(str::to_string).collect()) } /// What a click on one of the bar's [`Chip`]s does: make the Fill (`true`) or the Stroke active and diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 35c9fd3737..5f5741fc9c 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -4357,7 +4357,8 @@ fn a_pan_fills_the_area() { /// With the web build's setting (`waits_for_still`, no render worker), a heavy document's canvas /// is not rendered while the view moves: each frame draws the frame shown moved and scaled with /// the view and asks for a frame within STILL_SECS. The canvas renders once the view has been -/// still for STILL_SECS, and at once after an edit. With a worker's build settings the same frames render at once, as +/// still for STILL_SECS. An edit while the view moves draws the part it changed into the frame +/// shown, and one that changes most of the frame renders it whole at once. With a worker's build settings the same frames render at once, as /// before. #[test] fn without_a_worker_a_heavy_canvas_is_reprojected_until_the_view_is_still() { @@ -4421,15 +4422,39 @@ fn without_a_worker_a_heavy_canvas() { let now = app.canvas.key.clone().unwrap(); assert_eq!((now.cx, now.zoom), (app.view().unwrap().center.x, app.view().unwrap().zoom), "rendered for the view"); assert!((b.min - rect.min).length() < 0.01 && (b.max - rect.max).length() < 0.01, "{b:?} over {rect:?}"); - // An edit renders at once, even while the view moves. + // An edit while the view moves shows at once: the part it changed is drawn into the frame + // shown, at the view that frame was rendered for, and the frame stays drawn reprojected until + // the view is still (#8688). app.canvas.last_ms = 50.0; app.view_mut().unwrap().center.y += 10.0; frame(&mut app); assert_eq!(app.canvas.key.as_ref(), Some(&now), "waiting"); - app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 110, "y": 60, "width": 20, "height": 20})).unwrap(); + let render_ms = app.canvas.last_ms; + let (b, delay) = frame(&mut app); + let k = app.canvas.key.clone().unwrap(); + assert_eq!(k.revision, app.session.active().unwrap().revision, "the edit is drawn"); + assert_eq!((k.cx, k.cy, k.zoom), (now.cx, now.cy, now.zoom), "at the view of the frame shown"); + assert_eq!(app.canvas.last_ms, render_ms, "the frame was not rendered whole"); + let (old, new) = (Xf::new(rect, &View { center: Point::new(now.cx, now.cy), ..*app.view().unwrap() }), Xf::new(rect, app.view().unwrap())); + let (a, z) = (new.to_screen(old.to_doc(rect.min)), new.to_screen(old.to_doc(rect.max))); + assert!((b.min - a).length() < 0.01 && (b.max - z).length() < 0.01, "{b:?}: the frame shown at {a:?} to {z:?}"); + assert!(delay <= std::time::Duration::from_secs_f64(STILL_SECS), "a frame within STILL_SECS: {delay:?}"); + let mut frames = 0; + while app.canvas.key.as_ref() == Some(&k) && frames < 60 { + frames += 1; + frame(&mut app); + } + let k = app.canvas.key.clone().unwrap(); + assert_eq!((k.revision, k.cy), (app.session.active().unwrap().revision, app.view().unwrap().center.y), "rendered once still"); + // An edit that changes more than half of the frame renders whole at once, view and all. + app.canvas.last_ms = 50.0; + app.view_mut().unwrap().center.y += 10.0; + frame(&mut app); + app.session.execute("shape.rectangle", &json!({"x": -1000, "y": -1000, "width": 3000, "height": 3000})).unwrap(); frame(&mut app); let k = app.canvas.key.clone().unwrap(); - assert_eq!((k.revision, k.cy), (app.session.active().unwrap().revision, app.view().unwrap().center.y), "rendered after the edit"); + assert_eq!((k.revision, k.cy), (app.session.active().unwrap().revision, app.view().unwrap().center.y), "rendered whole after the edit"); // With a worker's build settings and no worker (VECTORCRAFT_SYNC_RENDER), a heavy document // renders every change of view at once. app.canvas.waits_for_still = false; @@ -4439,6 +4464,48 @@ fn without_a_worker_a_heavy_canvas() { assert_eq!(app.canvas.key.as_ref().map(|k| k.cx), Some(app.view().unwrap().center.x), "rendered at once"); } +/// With the web build's setting (`waits_for_still`, no render worker), a heavy document's view +/// that stops moving while a drag goes on editing the document renders whole once the view has +/// been still for STILL_SECS: each edit is drawn into the frame shown and does not start the wait +/// again. +#[test] +fn without_a_worker_edits_while_the_view_is_still_do_not_hold_off_the_render() { + keeping_color_settings(edits_while_the_view_is_still); +} + +fn edits_while_the_view_is_still() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap(); + app.canvas.worker_started = true; // no worker, as in the web build + app.canvas.waits_for_still = true; + let ctx = egui::Context::default(); + let frame = |app: &mut VectorcraftApp| { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + frame(&mut app); // the first frame fits the view to the artboard + frame(&mut app); + app.canvas.last_ms = 50.0; + // The view moves once (a drag at an edge of the canvas scrolls it) and then stays still. + app.view_mut().unwrap().center.y += 10.0; + frame(&mut app); + let shown = app.canvas.key.clone().unwrap(); + assert_ne!(shown.cy, app.view().unwrap().center.y, "waiting"); + // The drag edits the document on every frame, at 60 fps (egui's input time without a clock). + let mut frames = 0; + while app.canvas.key.as_ref().is_none_or(|k| k.cy != app.view().unwrap().center.y) && frames < 60 { + frames += 1; + let x = 110 + (frames % 10) * 5; + app.session.execute("shape.rectangle", &json!({"x": x, "y": 60, "width": 4, "height": 4})).unwrap(); + frame(&mut app); + let k = app.canvas.key.as_ref().unwrap(); + assert_eq!(k.revision, app.session.active().unwrap().revision, "each edit is drawn"); + } + assert!((11..=13).contains(&frames), "rendered whole about STILL_SECS after the view stopped: {frames} frames"); +} + /// [`still_wait`] waits while only the view changes on a slow canvas: each change starts /// STILL_SECS again. It does not wait for a light document, a still view, a clock that went /// back, an edit, a switch into Pixel Preview or a canvas with no frame shown. diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index ab5c9b121c..ce7f95808d 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -1011,6 +1011,19 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// The Control bar's object label, `label`, while the bar has room for it. For one selected image +/// (`image`: Linked File or Embedded) it is an underlined link, and a click opens the Links panel on +/// the image with its Link Info. +fn object_label(app: &mut VectorcraftApp, ui: &mut Ui, label: egui::RichText, image: bool) { + if ui.available_width() < widgets::text_width(ui, label.clone()) { + left_out(ui); + } else if !image { + ui.label(label); + } else if ui.link(label.underline()).clicked() { + crate::panels::links::show_selected_image(app, ui.ctx()); + } +} + /// The Control bar's gripper, controls and panel menu, in the bar `bar`. A `floating` bar clips its /// controls to the room left of the panel menu button, and always shows the button. fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, dock_room: egui::Rect, floating: bool) { @@ -1043,30 +1056,22 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, let units = app.session.general_unit(); let first = st.selection.objects.first().and_then(|id| st.doc.node(*id)); let anchors = anchor_controls(app); - let label = match first { - _ if app.session.tool_id() == "artboard" => tl!("Artboard"), - Some(_) if count == 1 && anchors != AnchorControls::None => { - tl!("Anchor Point") - } + // The label, and whether it names one selected image. + let (label, image) = match first { + _ if app.session.tool_id() == "artboard" => (tl!("Artboard"), false), + Some(_) if count == 1 && anchors != AnchorControls::None => (tl!("Anchor Point"), false), Some(vectorcraft_doc::Node { kind: NodeKind::Image(im), .. }) if count == 1 => { if im.link.is_some() { - tl!("Linked File") + (tl!("Linked File"), true) } else { - tl!("Embedded") + (tl!("Embedded"), true) } } - Some(n) if count == 1 && crate::panels::image_trace::is_trace(n) => { - tl!("Image Tracing") - } - _ => tl!(crate::panels::appearance::summary(app, ui.ctx()).map_or("No Selection", |s| s.label)), + Some(n) if count == 1 && crate::panels::image_trace::is_trace(n) => (tl!("Image Tracing"), false), + _ => (tl!(crate::panels::appearance::summary(app, ui.ctx()).map_or("No Selection", |s| s.label)), false), }; let has_first = first.is_some(); - let label = egui::RichText::new(label).font(theme::semibold(12.0)).color(t.text); - if ui.available_width() >= widgets::text_width(ui, label.clone()) { - ui.label(label); - } else { - left_out(ui); - } + object_label(app, ui, egui::RichText::new(label).font(theme::semibold(12.0)).color(t.text), image); // With the Artboard tool in use, the bar shows the active artboard's controls in place // of the object controls. let (artboard_options, transform) = (group_on(app, "artboardOptions"), group_on(app, "transform")); diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 20828b0287..5a4d92ab6d 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -4304,6 +4304,58 @@ fn select_similar_stays_out_while_an_image_control_is_left_out() { assert!(seen, "a wide bar shows the button after the image's controls"); } +/// A click on the Control bar's Linked File or Embedded label shows the Links panel, in an expanded +/// dock and in one collapsed to icons; the label of any other object stays plain text. +#[test] +fn the_linked_file_and_embedded_labels_open_the_links_panel() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let img = image::RgbaImage::from_pixel(20, 20, image::Rgba([0, 0, 0, 255])); + let mut png = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let dir = vectorcraft_testkit::temp_dir("control-bar-image-label"); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("square.png"); + std::fs::write(&path, &png).unwrap(); + use crate::tests_removeanchors::{at, click_control, control_frame}; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let links = crate::panels::links::ID; + // Closes the Links panel, clicks `name` on the bar and answers whether the panel shows. + let click = |app: &mut crate::VectorcraftApp, name: &str| { + app.run("window.panel.close", json!({"panel": links})).ok(); + app.ui.open_panel = None; + assert!(!crate::panel_docking::visible(&app.ui, links), "{name}: the panel is closed first"); + let pos = at(&control_frame(app, &ctx, vec![]), name); + click_control(app, &ctx, pos); + crate::panel_docking::visible(&app.ui, links) + }; + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].clone(); + let linked = app.run("file.place", json!({"path": path, "link": true})).unwrap()["ids"].clone(); + let embedded = app.run("file.place", json!({"path": path, "link": false})).unwrap()["ids"].clone(); + // The default layout floats Links: dock it beside Layers so that both passes reach a docked panel. + app.run("window.panel", json!({"panel": links})).unwrap(); + app.run("window.panel.dock", json!({"panel": links, "onto": "layers"})).unwrap(); + // Whether Links floats, and whether its dock column is collapsed to icons. + let placed = |app: &crate::VectorcraftApp| { + let layout = crate::panel_docking::layout_of(&app.ui); + (layout.floating.iter().any(|w| w.panels().any(|p| p == links)), crate::panel_docking::in_iconic_column(&layout, links)) + }; + for collapsed in [false, true] { + app.run("window.collapseDock", json!({ "collapsed": collapsed })).unwrap(); + app.run("select.set", json!({ "ids": linked })).unwrap(); + assert!(click(&mut app, "Linked File"), "collapsed {collapsed}, status: {}", app.ui.status); + assert_eq!(placed(&app), (false, collapsed), "Links opened in its dock, collapsed {collapsed}"); + app.run("select.set", json!({ "ids": embedded })).unwrap(); + assert!(click(&mut app, "Embedded"), "collapsed {collapsed}, status: {}", app.ui.status); + assert_eq!(placed(&app), (false, collapsed), "Links opened in its dock, collapsed {collapsed}"); + app.run("select.set", json!({ "ids": [id] })).unwrap(); + let name = crate::panels::appearance::object_label(&app); + assert!(!click(&mut app, name), "collapsed {collapsed}: a rectangle's label opens nothing"); + } +} + /// The Anchor Points group holds Convert and Anchors for direct-selected anchors; off, the bar keeps /// its Anchor Point label. #[test] diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index b5b829ebbf..6d2417a0fd 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1146,9 +1146,9 @@ fn leave_out_unreadable_values(v: &mut Value, place: ParamsPlace) { /// Takes out of `ui.inspect`'s copy of the UI state the paths the request may not read: recent files, /// a library panel's file, folder preferences (saved, and in an open Preferences dialog) and the paths -/// in recorded actions' steps outside the read root. The file selected in an open JavaScript Files -/// dialog is named as `svgInteractivity.info` names the active document's linked files. The UI state -/// itself is not changed. +/// in recorded actions' steps and in the item an open Insert Menu Item dialog picked, outside the +/// read root. The file selected in an open JavaScript Files dialog is named as `svgInteractivity.info` +/// names the active document's linked files. The UI state itself is not changed. fn leave_out_unreadable_paths(app: &VectorcraftApp, ui: &mut serde_json::Map) { if let Some(Value::Array(files)) = ui.get_mut("recent_files") { files.retain(|f| f.as_str().is_some_and(readable)); @@ -1172,6 +1172,16 @@ fn leave_out_unreadable_paths(app: &VectorcraftApp, ui: &mut serde_json::Map color_guide_options::SPEC, ColorBalance: [color_balance::KIND] => color_balance::SPEC, Saturate: [saturate::KIND] => saturate::SPEC, + ProofSetup: [proof_setup::KIND] => proof_setup::SPEC, IndexedColor: [indexed_color::KIND] => indexed_color::SPEC, SaveSwatchLibrary: [save_swatch_library::KIND] => save_swatch_library::SPEC, TileEdgeColor: [tile_edge_color::KIND] => tile_edge_color::SPEC, @@ -469,6 +472,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, + 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, DeleteSymbol: [symbol_delete::KIND] => symbol_delete::SPEC, @@ -623,7 +627,8 @@ pub fn accepts_field(d: &Dialog, field: &str) -> bool { /// A Graph Data Column Width set this way sets every column, as Cell Style's does. A Width Point /// Edit side width set this way for several points sets it on every point, as typing it does. An /// Import PDF `allPages` set this way to the other pick sets Import PDF pages as links back to its -/// default. +/// default. A Dimension Tool Options `arrowStyle` set this way clears `arrowHead`, and a built-in +/// `arrowHead` set this way sets both values of its Arrow Style entry, as that menu does. pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == brush_options::KIND { brush_art_options::note_set(d, &field); @@ -637,6 +642,9 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == import_pdf::KIND { import_pdf::note_set(d, &field, &value); } + if d.kind == dimension::KIND && dimension::note_set(d, &field, &value) { + return; + } if d.kind == "preferences" { crate::prefs_dialog::note_set(d, &field, &value); } @@ -784,6 +792,9 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == script_run::NOTICE_KIND { script_run::notice_cancel(app, &d); } + if d.kind == proof_setup::KIND { + proof_setup::cancel(app, &d); + } if d.kind == script_run::PICKER_KIND { script_run::picker_cancel(app, &d); } @@ -839,13 +850,15 @@ pub fn confirm(app: &mut VectorcraftApp) -> DialogResult { } /// After a dialog closes, and each frame: a Missing Fonts dialog that another dialog replaced waits -/// for its turn again, the search a Missing Fonts or Find Linked Files dialog started stops once -/// that dialog is gone, and with no dialog open the choice about a stopped plug-in that another +/// for its turn again, a Proof Setup preview that another dialog replaced is undone, the search a +/// Missing Fonts or Find Linked Files dialog started stops once that dialog is gone, and with no +/// dialog open the choice about a stopped plug-in that another /// dialog replaced opens again, else the questions about the next restored document's linked files /// ([`crate::recovery::ask_next`]), else the next document's Missing Fonts dialog (one dialog at a /// time). pub(crate) fn settle(app: &mut VectorcraftApp) { crate::placing::settle_swatch_paste(app); + proof_setup::restore_replaced(app); profile_mismatch::settle(app); missing_fonts::requeue_replaced(app); missing_fonts::stop_when_closed(app); diff --git a/crates/ui-egui/src/dialogs/action_insert_menu_item.rs b/crates/ui-egui/src/dialogs/action_insert_menu_item.rs index 0b4bd8dc7d..2423999694 100644 --- a/crates/ui-egui/src/dialogs/action_insert_menu_item.rs +++ b/crates/ui-egui/src/dialogs/action_insert_menu_item.rs @@ -66,23 +66,27 @@ fn build(lang: crate::i18n::Lang, english_names: bool) -> Vec { .map(|item| { let parts = || item.path.iter().chain(std::iter::once(&item.label)).copied(); let english = parts().collect::>().join(" › "); - let shown = parts().map(|s| crate::i18n::tr(lang, s)).collect::>().join(" › "); + // A saved proof setup keeps its file's name. + let own_name = item.command == crate::dialogs::proof_setup::LOAD; + let path = item.path.iter().map(|s| crate::i18n::tr(lang, s)); + let label = if own_name { item.label } else { crate::i18n::tr(lang, item.label) }; + let shown = path.chain(std::iter::once(label)).collect::>().join(" › "); let haystack = format!("{}\n{}\n{}", english.to_lowercase(), shown.to_lowercase(), item.command.to_lowercase()); Row { command: item.command, params: item.params, shown, haystack } }) .collect() } -/// The rows, built again only when the language, the installed plug-ins, the font name setting or -/// the loaded fonts change, not on every frame. +/// The rows, built again only when the language, the installed plug-ins, the font name setting, +/// the loaded fonts or the saved proof setups change, not on every frame. fn rows(app: &VectorcraftApp, ctx: &egui::Context) -> Arc> { - type Key = (&'static str, u64, bool, u64, bool); + type Key = (&'static str, u64, bool, u64, bool, u64); let lang = crate::i18n::current(); let english_names = app.session.prefs.font_names_in_english; let db = vectorcraft_text::FontDb::global(); // Read before building, as the Font menu does: fonts that load meanwhile build the rows again. let (cataloged, generation) = (db.installed_fonts_ready(), db.generation()); - let key: Key = (lang.code(), menus::plugin_revision(), english_names, generation, cataloged); + let key: Key = (lang.code(), menus::plugin_revision(), english_names, generation, cataloged, crate::dialogs::proof_setup::saved_revision()); let id = egui::Id::unique("action-insert-menu-item-rows"); if let Some((k, v)) = ctx.data(|d| d.get_temp::<(Key, Arc>)>(id)) && k == key @@ -301,4 +305,33 @@ mod tests { let shared = rows.iter().any(|r| rows.iter().any(|o| o.command == r.command && o.params != r.params)); assert!(shared, "items that share a command are listed apart, by their params"); } + + /// A proof setup saved while the dialog is open is listed at once, by its file's name in every + /// UI language. + #[test] + fn a_proof_setup_saved_meanwhile_is_listed_by_its_name() { + use crate::dialogs::proof_setup; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + let dir = vectorcraft_testkit::TempDir::new("insert-menu-item-proof-setups"); + app.session.attach_proof_setups(dir.join("Proof Setups")); + proof_setup::refresh_saved(&app, None); + proof_setup::wait(); + let de = Lang::from_code("de").unwrap(); + crate::i18n::set_current(de); + let listed = + |app: &VectorcraftApp| rows(app, &ctx).iter().filter(|r| r.command == proof_setup::LOAD).map(|r| r.shown.clone()).collect::>(); + // The installed fonts' scan, which builds the rows again when it ends, is over first. + vectorcraft_text::FontDb::global().menu_family_list(); + let before = listed(&app); + app.run("view.proofSetup.save", json!({"name": "Group", "target": "workingCmyk"})).unwrap(); + proof_setup::refresh_saved(&app, None); + proof_setup::wait(); + let after = listed(&app); + crate::i18n::set_current(Lang::EN); + assert!(before.is_empty(), "{before:?}"); + let view = crate::i18n::tr(de, "View"); + let menu = crate::i18n::tr(de, "Proof Setup"); + assert_eq!(after, [format!("{view} › {menu} › Group")]); + } } diff --git a/crates/ui-egui/src/dialogs/dimension.rs b/crates/ui-egui/src/dialogs/dimension.rs index 950e8bfabd..9095c74fcb 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -4,6 +4,7 @@ use super::DialogSpec; use crate::{VectorcraftApp, state::Dialog, theme::Tokens, widgets}; use egui::{RichText, Ui}; use serde_json::{Value, json}; +use vectorcraft_doc::Arrowhead; use vectorcraft_doc::dimension::{ArrowStyle, DimensionOptions}; pub const KIND: &str = "dimensionOptions"; @@ -14,6 +15,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec { ok: Some("Save"), min_width: 520.0, max_width: Some(560.0), + // The saved options leave `arrowHead` out when it is null. + inputs: |_| &["arrowHead"], ..DialogSpec::FORM }; @@ -31,11 +34,33 @@ const UNITS: Choices = &[ ("yd", "Yards"), ]; const LINE_TYPES: Choices = &[("solid", "Solid"), ("dashed", "Dashed"), ("dotted", "Dotted")]; -const ARROWS: Choices = &[("filled", "Filled"), ("open", "Open"), ("tick", "Tick"), ("none", "None")]; -/// The style of each `ARROWS` entry, in the same order. -const ARROW_STYLES: [ArrowStyle; 4] = [ArrowStyle::Filled, ArrowStyle::Open, ArrowStyle::Tick, ArrowStyle::None]; -/// The size of an Arrow Style preview: a line with the head at its right end. -const ARROW_PREVIEW: egui::Vec2 = egui::vec2(40.0, 16.0); +/// The size of an Arrow Style preview: a line with the head at its right end. Line Arrow, the widest +/// head, spreads 20 pt across at the preview's head weight. +const ARROW_PREVIEW: egui::Vec2 = egui::vec2(40.0, 22.0); +/// One Arrow Style entry: the `arrowStyle` and `arrowHead` values it sets, and its name. +struct ArrowChoice { + style: ArrowStyle, + head: Option, + name: &'static str, +} +impl ArrowChoice { + /// The arrowhead the dimension line draws with this entry. + fn drawn(&self) -> Option { + self.head.clone().or_else(|| self.style.arrowhead()) + } +} +/// The Arrow Style entries: Filled, Open, Tick and None, then the other built-in stroke arrowheads +/// in the Stroke panel's order. A stroke arrowhead keeps `filled` as its `arrowStyle`, the head that +/// versions which do not read `arrowHead` draw when they draw the dimension again. +fn arrow_choices() -> Vec { + let named = [(ArrowStyle::Filled, "Filled"), (ArrowStyle::Open, "Open"), (ArrowStyle::Tick, "Tick"), (ArrowStyle::None, "None")]; + let heads = Arrowhead::ALL.into_iter().filter(|h| !named.iter().any(|(s, _)| s.arrowhead().as_ref() == Some(h))); + named + .into_iter() + .map(|(style, name)| ArrowChoice { style, head: None, name }) + .chain(heads.map(|h| ArrowChoice { style: ArrowStyle::Filled, name: h.label(), head: Some(h) })) + .collect() +} const POSITIONS: Choices = &[("away", "Away from the Line"), ("between", "Between Line and Object")]; const ALIGNMENTS: Choices = &[("left", "Left"), ("center", "Center"), ("right", "Right")]; @@ -51,6 +76,37 @@ pub fn open(app: &mut VectorcraftApp) -> Result { Ok(json!({"dialog":KIND})) } +/// For `ui.dialog.set`, as the Arrow Style menu sets them: an `arrowStyle` set alone draws that +/// style's own head, and a built-in head set as `arrowHead` sets both values of its Arrow Style +/// entry (`tick` with no `arrowHead` for `Slash`, `filled` with `Barbed` for `Barbed`). Returns +/// whether it set the field itself. +pub(super) fn note_set(d: &mut Dialog, field: &str, value: &Value) -> bool { + match field { + "arrowStyle" => { + d.fields.insert("arrowHead".into(), Value::Null); + false + } + "arrowHead" => { + let head = built_in_head(value); + if let Some(ch) = arrow_choices().into_iter().find(|ch| head.is_some() && ch.drawn() == head) + && let (Ok(style), Ok(head)) = (serde_json::to_value(ch.style), serde_json::to_value(&ch.head)) + { + d.fields.insert("arrowStyle".into(), style); + d.fields.insert("arrowHead".into(), head); + return true; + } + false + } + _ => false, + } +} + +/// The built-in stroke arrowhead `value` names. Only a short name is read: a draft may hold anything. +fn built_in_head(value: &Value) -> Option { + let name = value.as_str().filter(|name| name.len() <= 64)?; + serde_json::from_value::(Value::String(name.into())).ok().filter(|h| !matches!(h, Arrowhead::Custom(_))) +} + fn read(fields: &serde_json::Map) -> Result { let o: DimensionOptions = serde_json::from_value(Value::Object(fields.clone())).map_err(|e| e.to_string())?; o.validate()?; @@ -73,24 +129,34 @@ fn choose(ui: &mut Ui, fields: &mut serde_json::Map, key: &str, l }); changed } -/// The Arrow Style dropdown: each style shows a drawn preview of its arrowhead before its name, in -/// the open list and in the closed field. +/// The Arrow Style dropdown: Filled, Open, Tick and None, then the other built-in stroke +/// arrowheads. Each style shows a drawn preview of its arrowhead before its name, in the open list +/// and in the closed field. fn arrow_style(ui: &mut Ui, fields: &mut serde_json::Map, id: &str) -> bool { - const KEY: &str = "arrowStyle"; + const STYLE: &str = "arrowStyle"; + const HEAD: &str = "arrowHead"; let mut changed = false; widgets::label_row(ui, tl!("Arrow Style:"), 96.0, |ui| { - let current = fields.get(KEY).and_then(Value::as_str).unwrap_or_default(); - let shown = ARROWS.iter().position(|(v, _)| *v == current); - let names: Vec<&str> = ARROWS.iter().map(|(_, s)| tl!(*s)).collect(); + let choices = arrow_choices(); + let style = fields.get(STYLE).cloned().and_then(|v| serde_json::from_value::(v).ok()); + let head = fields.get(HEAD).and_then(built_in_head); + let current = style.map(|s| head.or_else(|| s.arrowhead())); + let shown = current.and_then(|c| choices.iter().position(|ch| ch.drawn() == c)); + let names: Vec<&str> = choices.iter().map(|ch| crate::panels::stroke::builtin_arrow_name(ch.name)).collect(); let icon = |ui: &Ui, rect: egui::Rect, i: usize, ink: egui::Color32, _: bool| { - if let Some(style) = ARROW_STYLES.get(i) { - crate::panels::stroke::paint_arrow(ui, rect, style.arrowhead().as_ref(), false, ink); + // Only the rows in view render their previews. + if ui.is_rect_visible(rect) + && let Some(ch) = choices.get(i) + { + crate::panels::stroke::paint_arrow(ui, rect, ch.drawn().as_ref(), false, ink); } }; - if let Some((value, _)) = - widgets::dropdown_icon_names_sized(ui, ("dimension", id), shown, &names, 150.0, ARROW_PREVIEW, icon).and_then(|i| ARROWS.get(i)) + if let Some(ch) = + widgets::dropdown_icon_names_sized(ui, ("dimension", id), shown, &names, 150.0, ARROW_PREVIEW, icon).and_then(|i| choices.get(i)) + && let (Ok(style), Ok(head)) = (serde_json::to_value(ch.style), serde_json::to_value(&ch.head)) { - fields.insert(KEY.into(), json!(value)); + fields.insert(STYLE.into(), style); + fields.insert(HEAD.into(), head); changed = true; } }); @@ -387,9 +453,13 @@ mod tests { assert!(text.contains(label), "{label}: {text}"); } let d = app.ui.dialog.as_mut().unwrap(); + // The default style has no `arrowHead`, and the dialog still takes one. + assert!(!d.fields.contains_key("arrowHead") && super::super::accepts_field(d, "arrowHead")); d.fields.insert("scale".into(), json!("1:10")); d.fields.insert("units".into(), json!("pc")); + d.fields.insert("arrowHead".into(), json!("Barbed")); super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.tool_options_of("dimension")["style"]["arrowHead"], "Barbed"); assert_eq!(app.session.tool_options_of("dimension")["style"]["scale"], "1:10"); assert_eq!(app.session.tool_options_of("dimension")["style"]["units"], "pc"); open(&mut app).unwrap(); @@ -397,6 +467,28 @@ mod tests { assert!(super::super::confirm(&mut app).is_err()); app.ui.dialog = None; assert_eq!(app.session.tool_options_of("dimension")["style"]["scale"], "1:10"); + // An arrow style set by `ui.dialog.set` replaces the Barbed head, as the menu does. + open(&mut app).unwrap(); + super::super::set_field(app.ui.dialog.as_mut().unwrap(), "arrowStyle".into(), json!("none")); + super::super::confirm(&mut app).unwrap(); + let style = serde_json::from_value::(app.session.tool_options_of("dimension")["style"].clone()).unwrap(); + assert_eq!((style.arrow_style, style.arrowhead()), (ArrowStyle::None, None)); + // A stroke head set by `ui.dialog.set` keeps Filled as the arrow style, as the menu does; an + // unknown name leaves the arrow style as it was. + open(&mut app).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + super::super::set_field(d, "arrowStyle".into(), json!("tick")); + super::super::set_field(d, "arrowHead".into(), json!("Nope")); + assert_eq!(d.fields["arrowStyle"], "tick"); + super::super::set_field(d, "arrowHead".into(), json!("Barbed")); + super::super::confirm(&mut app).unwrap(); + let style = serde_json::from_value::(app.session.tool_options_of("dimension")["style"].clone()).unwrap(); + assert_eq!((style.arrow_style, style.arrowhead()), (ArrowStyle::Filled, Some(Arrowhead::Barbed))); + // The head of an older style sets that style and no `arrowHead`, as its menu entry does. + open(&mut app).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + super::super::set_field(d, "arrowHead".into(), json!("Slash")); + assert_eq!((&d.fields["arrowStyle"], &d.fields["arrowHead"]), (&json!("tick"), &Value::Null)); } /// A selected dimension shows its style in Properties, with Apply to All and Set as Default. @@ -436,7 +528,10 @@ mod tests { let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui)).textures_delta.clear(); - ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui)) + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui)); + // Previews of rows that come into view in this frame load now. + out.textures_delta.clear(); + out } /// The Arrow Style field of the Tool Options and of Properties shows the style's arrowhead, @@ -454,12 +549,30 @@ mod tests { assert!(picture_before(&out, "Tick"), "Properties"); } - /// Each Arrow Style entry previews the style its value names. + /// A dimension drawn with a stroke arrowhead shows that head's name and preview in its Arrow + /// Style field (#3222). #[test] - fn arrow_previews_follow_the_listed_styles() { - assert_eq!(ARROWS.len(), ARROW_STYLES.len()); - for ((value, _), style) in ARROWS.iter().zip(ARROW_STYLES) { - assert_eq!(serde_json::to_value(style).unwrap(), json!(value)); + fn arrow_style_shows_a_stroke_arrowhead() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("dimension.create", json!({"a":[10,10],"b":[110,10],"options":{"arrowHead":"HalfArrowLeft"}})).unwrap(); + let out = frame(&mut app, properties_section); + assert!(picture_before(&out, "Half Arrow (left)"), "Properties"); + } + + /// The Arrow Style list names each arrowhead once, with the four older styles first, and each + /// stroke arrowhead keeps Filled as its `arrowStyle`. + #[test] + fn arrow_style_list_names_each_style_once() { + let choices = arrow_choices(); + let names: Vec<&str> = choices.iter().map(|c| c.name).collect(); + assert_eq!(names[..4], ["Filled", "Open", "Tick", "None"]); + for name in ["Triangle", "Triangle (open)", "Slash"] { + assert!(!names.contains(&name), "{name} is listed as Filled, Open or Tick"); } + assert_eq!(names.len(), Arrowhead::ALL.len() + 1, "None and each built-in head: {names:?}"); + let drawn: Vec<_> = choices.iter().map(|c| format!("{:?}", c.drawn())).collect(); + assert_eq!(drawn.iter().collect::>().len(), drawn.len(), "{drawn:?}"); + assert!(choices[4..].iter().all(|c| c.style == ArrowStyle::Filled && c.head.is_some())); } } diff --git a/crates/ui-egui/src/dialogs/proof_setup.rs b/crates/ui-egui/src/dialogs/proof_setup.rs new file mode 100644 index 0000000000..44350ac659 --- /dev/null +++ b/crates/ui-egui/src/dialogs/proof_setup.rs @@ -0,0 +1,1022 @@ +//! View → Proof Setup → Customize…: the device to simulate (the working CMYK space, or any CMYK or +//! RGB profile), Preserve CMYK Numbers or Preserve RGB Numbers, the rendering intent (used while +//! the numbers are not preserved), Simulate Paper Color and Simulate Black Ink (CMYK devices only). +//! Preview shows the proof on the canvas while the dialog is open; OK sets the proof setup and +//! turns Proof Colors on (`view.proofSetup`), and Cancel puts the earlier proof view back. Save… +//! writes the dialog's settings to a proof setup file (`view.proofSetup.save`) and Load… reads one +//! into the dialog (`view.proofSetup.read`). Both are desktop only. Their pickers start in the +//! Proof Setups folder next to the preferences, whose setups View → Proof Setup lists below +//! Customize… ([`saved_items`]): Save… makes the folder when it may be written, and Load…'s picker +//! starts in its own default folder until the folder exists. +//! +//! Fields: `device` (`workingCmyk`, `cmyk:` or `rgb:`), `preserveNumbers`, +//! `intent`, `simulatePaper`, `simulateBlack` and `preview`. + +use std::sync::mpsc::{Receiver, TryRecvError}; +use std::sync::{Mutex, MutexGuard}; + +use serde_json::{Value, json}; +use vectorcraft_color::cms::{self, Intent, ProfileKind, ProofTarget}; +use vectorcraft_engine::cmd::colormgmt::proof_file::{self, EXT}; +use vectorcraft_render::proof; + +use super::{DialogSpec, form}; +use crate::menus::Item; +use crate::state::Dialog; +use crate::widgets; +use crate::{FilePick, VectorcraftApp}; + +/// The dialog kind of Proof Setup › Customize. +pub const KIND: &str = "proofSetup"; + +const CMD: &str = "view.proofSetup"; + +/// The proof view as the dialog found it, which Cancel puts back after a preview. +const BEFORE: &str = "__before"; +/// The settings the canvas shows while Preview is on, as last sent. +const PREVIEWED: &str = "__previewed"; + +/// The device a proof target that is not a device (an RGB display or a color blindness type) +/// starts the dialog on. +const WORKING: &str = "workingCmyk"; + +const LABEL_W: f32 = 140.0; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Proof Setup").into(), body, confirm, min_width: 420.0, ..DialogSpec::FORM }; + +/// Open the dialog on the current proof setup. While it is open, it stays as it is, so Cancel +/// still puts back the view it found first. +pub fn open(app: &mut VectorcraftApp) { + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND) { + return; + } + // A preview whose dialog another one replaced is undone before this dialog takes the view. + restore_replaced(app); + let v = proof::view(); + let s = &v.setup; + let device = match &s.target { + ProofTarget::WorkingCmyk | ProofTarget::Cmyk(_) | ProofTarget::Rgb(_) => s.target.id(), + _ => WORKING.to_string(), + }; + let before = snapshot(&v); + app.ui.dialog = Some(Dialog::new( + KIND, + json!({ + "device": device, + "preserveNumbers": s.preserve_numbers, + "intent": s.intent.id(), + "simulatePaper": s.simulate_paper, + "simulateBlack": s.simulate_black, + "preview": true, + BEFORE: before, + }), + )); +} + +/// The parts of the proof view `v` that Cancel puts back, as the dialog keeps them in `BEFORE`. +fn snapshot(v: &proof::ProofView) -> Value { + let s = &v.setup; + json!({ + "target": s.target.id(), + "intent": s.intent.id(), + "simulatePaper": s.simulate_paper, + "preserveNumbers": s.preserve_numbers, + "simulateBlack": s.simulate_black, + "proof": v.proof_colors, + }) +} + +/// The devices to simulate, as (`device` value, name shown): the working CMYK space, then every +/// CMYK profile and every RGB profile. +fn devices() -> Vec<(String, String)> { + let profiles = cms::profiles(); + let of = |kind: ProfileKind, prefix: &str| { + profiles.iter().filter(move |p| p.kind == kind).map(move |p| (format!("{prefix}{}", p.name), p.name.clone())).collect::>() + }; + std::iter::once((WORKING.to_string(), tl!("Working CMYK").to_string())) + .chain(of(ProfileKind::Cmyk, "cmyk:")) + .chain(of(ProfileKind::Rgb, "rgb:")) + .collect() +} + +/// Whether `device` is an RGB profile. +fn rgb_device(device: &str) -> bool { + device.starts_with("rgb:") +} + +/// What OK sends to `view.proofSetup`. +fn params(d: &Dialog) -> Value { + json!({ + "target": d.str("device"), + "preserveNumbers": d.bool("preserveNumbers"), + "intent": d.str("intent"), + "simulatePaper": d.bool("simulatePaper"), + "simulateBlack": d.bool("simulateBlack"), + "proof": true, + }) +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let devices = devices(); + let device = d.str("device"); + // A profile that is no longer loaded shows its name as it is. + let shown = + devices.iter().find(|(id, _)| *id == device).map_or_else(|| device.split_once(':').map_or(device.as_str(), |(_, n)| n), |(_, n)| n.as_str()); + let names: Vec<&str> = devices.iter().map(|(_, n)| n.as_str()).collect(); + widgets::label_row(ui, tl!("Device to Simulate:"), LABEL_W, |ui| { + if let Some((id, _)) = widgets::dropdown_names(ui, "proof-setup-device", shown, &names, 260.0).and_then(|i| devices.get(i)) { + d.fields.insert("device".into(), json!(id)); + } + }); + ui.add_space(4.0); + let rgb = rgb_device(&d.str("device")); + let preserve = if rgb { tl!("Preserve RGB Numbers") } else { tl!("Preserve CMYK Numbers") }; + form::check(ui, d, "preserveNumbers", preserve); + let intents: Vec<(&str, &str)> = Intent::ALL.iter().map(|i| (i.id(), i.label())).collect(); + ui.add_enabled_ui(!d.bool("preserveNumbers"), |ui| form::choice(ui, d, "intent", tl!("Rendering intent:"), (LABEL_W, 200.0), &intents)); + ui.add_space(4.0); + // Paper and black ink are a printing press's: an RGB device has neither. + let paper = d.bool("simulatePaper"); + if widgets::check(ui, tl!("Simulate Paper Color"), paper && !rgb, !rgb) { + d.fields.insert("simulatePaper".into(), json!(!paper)); + } + // Simulate Paper Color shows the press black too, so the box shows checked while it is on. + let black = d.bool("simulateBlack"); + if widgets::check(ui, tl!("Simulate Black Ink"), (black || paper) && !rgb, !rgb && !paper) { + d.fields.insert("simulateBlack".into(), json!(!black)); + } + // The web has no folder to keep setups in. + if !cfg!(target_arch = "wasm32") { + ui.add_space(6.0); + let (mut save_clicked, mut load_clicked) = (false, false); + ui.horizontal(|ui| { + save_clicked = widgets::flat_button(ui, tl!("Save…"), 64.0).clicked(); + load_clicked = widgets::flat_button(ui, tl!("Load…"), 64.0).clicked(); + }); + // Their file dialogs, shown off the UI thread, save from or load into the dialog as it is + // then. + let r = if save_clicked { + crate::picks::in_app_dialog(app, d, save) + } else if load_clicked { + crate::picks::in_app_dialog(app, d, load) + } else { + Ok(()) + }; + if let Err(e) = r { + app.status(e); + } + } + ui.add_space(8.0); + form::preview_check(ui, d); + preview(app, d); + false +} + +/// While Preview is on, the canvas shows the dialog's settings, sent again whenever they change; +/// turned off, the earlier proof view comes back. +fn preview(app: &mut VectorcraftApp, d: &mut Dialog) { + // Back from under another dialog that undid its preview, the dialog starts from the view the + // canvas shows now and previews again. + if d.fields.contains_key(PREVIEWED) && app.ui.proof_preview.is_none() { + d.fields.remove(PREVIEWED); + } + if d.bool("preview") { + let p = params(d); + if d.fields.get(PREVIEWED) != Some(&p) { + // A preview that starts while the canvas shows no preview of this dialog (none yet, or a + // proof setup a command set since) takes the view the canvas shows now as the one to + // put back. + let v = proof::view(); + let start = match &app.ui.proof_preview { + Some((_, previewed)) if dialog_part(&v) == dialog_part(previewed) => None, + _ => Some(snapshot(&v)), + }; + match app.run(CMD, p.clone()) { + Ok(_) => { + if let Some(before) = start { + d.fields.insert(BEFORE.into(), before); + } + d.fields.insert(PREVIEWED.into(), p); + app.ui.proof_preview = d.fields.get(BEFORE).map(|b| (b.clone(), proof::view())); + } + Err(e) => app.ui.status = e, + } + } + } else if d.fields.remove(PREVIEWED).is_some() { + restore(app); + } +} + +/// Put back the proof view the dialog found before its preview. A proof setup set since the +/// preview (by `view.proofSetup`, for example) stays. +fn restore(app: &mut VectorcraftApp) { + if let Some((before, previewed)) = app.ui.proof_preview.take() + && dialog_part(&proof::view()) == dialog_part(&previewed) + { + set_view(app, &before); + } +} + +/// When another dialog has taken the place of a previewing Proof Setup dialog, put back the proof +/// view that dialog found. +pub(super) fn restore_replaced(app: &mut VectorcraftApp) { + if !app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND) { + restore(app); + } +} + +/// The parts of a proof view the dialog sets: the device, the intent, the three options and Proof +/// Colors. +fn dialog_part(v: &proof::ProofView) -> (&ProofTarget, Intent, bool, bool, bool, bool) { + let s = &v.setup; + (&s.target, s.intent, s.simulate_paper, s.preserve_numbers, s.simulate_black, v.proof_colors) +} + +/// Set the proof view `before` holds and redraw the documents. The view is set directly, not +/// through `view.proofSetup`, which refuses a device profile removed since it was set. +fn set_view(app: &mut VectorcraftApp, before: &Value) { + let text = |k: &str| before.get(k).and_then(Value::as_str).unwrap_or_default(); + let on = |k: &str| before.get(k).and_then(Value::as_bool).unwrap_or_default(); + let (Some(target), Some(intent)) = (ProofTarget::parse(text("target")), Intent::parse(text("intent"))) else { return }; + let mut v = proof::view(); + let was = v.clone(); + v.setup.target = target; + v.setup.intent = intent; + v.setup.simulate_paper = on("simulatePaper"); + v.setup.preserve_numbers = on("preserveNumbers"); + v.setup.simulate_black = on("simulateBlack"); + v.proof_colors = on("proof"); + if v == was { + return; + } + proof::set_view(v); + let uids: Vec = app.session.documents().iter().map(|d| d.uid).collect(); + for uid in uids { + if let Some(d) = app.session.document_mut(uid) { + d.revision += 1; + } + } +} + +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let r = app.run(CMD, params(d))?; + app.ui.proof_preview = None; + app.ui.dialog = None; + Ok(r) +} + +/// Cancel: after a preview, the earlier proof view comes back. +pub(super) fn cancel(app: &mut VectorcraftApp, d: &Dialog) { + if d.fields.contains_key(PREVIEWED) { + restore(app); + } +} + +/// A file dialog for proof setup files, starting in the Proof Setups folder. +fn pick(app: &VectorcraftApp, name: String) -> FilePick { + let folder = app.session.proof_setup_dir().map(|f| f.to_string_lossy().into_owned()); + FilePick { name, folder, filters: vec![FilePick::filter("Proof setups", &[EXT])] } +} + +/// Save…: the dialog's settings go to the picked file, and the menu lists the saved setups again. +fn save(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + // The picker opens in the folder, made for it when it may be written. When the picker is + // canceled, the folder it made is removed again while it is still empty: here for a picker + // shown in line, and by [`poll`] once a picker shown off the UI thread has closed. + let made = app + .session + .proof_setup_dir() + .filter(|dir| !dir.is_dir() && vectorcraft_engine::file_access::check_write(&dir.to_string_lossy()).is_ok()) + .map(std::path::Path::to_path_buf) + .filter(|dir| std::fs::create_dir_all(dir).is_ok()); + let pick = pick(app, format!("{}.{EXT}", tl!("Proof Setup"))); + let Some((picked, file_type)) = crate::picks::save_with_type(app, &pick) else { + if let Some(dir) = made { + if app.picks.is_waiting() { + saved().made = Some(dir); + } else { + let _ = std::fs::remove_dir(dir); + } + } + return Ok(()); + }; + let path = if std::path::Path::new(&picked).extension().is_none() { format!("{picked}.{EXT}") } else { picked.clone() }; + // The picker asked only about the name as typed: a file at the name with the extension added + // is replaced after a question, whose OK runs Save… again. + if path != picked && crate::picks::ask_to_replace(app, crate::picks::PickRequest::Save(pick.clone()), &picked, file_type.as_deref(), &path) { + return Ok(()); + } + let mut p = params(d); + if let Some(o) = p.as_object_mut() { + o.remove("proof"); + o.insert("path".into(), json!(path)); + } + app.run("view.proofSetup.save", p)?; + // The read asks for a frame when it ends, so an idle window lists the setup. + refresh_saved(app, app.ui_ctx.as_ref()); + app.status(format!("Saved {path}")); + Ok(()) +} + +/// Load…: the picked file's settings fill the dialog (Preview then shows them). +fn load(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + let mut pick = pick(app, String::new()); + // Before a setup is saved there is no folder, and the picker starts in its own default folder. + if pick.folder.as_deref().is_some_and(|f| !std::path::Path::new(f).is_dir()) { + pick.folder = None; + } + // A canceled picker leaves the dialog as it is. + let Some(path) = crate::picks::open(app, &pick) else { return Ok(()) }; + let r = app.run("view.proofSetup.read", json!({ "path": path }))?; + let fields = [ + ("device", "target"), + ("intent", "intent"), + ("preserveNumbers", "preserveNumbers"), + ("simulatePaper", "simulatePaper"), + ("simulateBlack", "simulateBlack"), + ]; + for (field, key) in fields { + d.fields.insert(field.into(), r[key].clone()); + } + Ok(()) +} + +// ---------- the saved setups in View › Proof Setup ---------- + +/// The command a saved setup's menu item runs. +pub const LOAD: &str = "view.proofSetup.load"; + +#[derive(Default)] +struct Saved { + /// (name, path) of each setup, as `view.proofSetup.list` last gave them. + setups: Vec<(&'static str, String)>, + /// How many listings differed from the one before (the macOS menu bar follows it). + revision: u64, + /// A first listing was read. + started: bool, + /// The window was the active one at the last [`poll`]. + focused: bool, + /// The session's count of saved setups at the last [`poll`] (`Session::proof_setup_saves`). + saves: u64, + /// The Proof Setups folder that Save… made for a picker shown off the UI thread, removed by + /// [`poll`] once the picker has closed if it is still empty. + made: Option, + /// The listing being read on another thread, as (name, path) of each setup. + reading: Option>>, + /// Another read was asked for while one was under way; [`poll`] starts it when that one ends. + pending: bool, +} + +/// The listing the menus show. One per process in the app; one per thread in unit tests, which run +/// in parallel threads, each with its own folder. +fn saved() -> MutexGuard<'static, Saved> { + #[cfg(not(test))] + let saved: &'static Mutex = { + static S: std::sync::OnceLock> = std::sync::OnceLock::new(); + S.get_or_init(Default::default) + }; + #[cfg(test)] + let saved: &'static Mutex = { + thread_local!(static S: &'static Mutex = Box::leak(Box::default())); + S.with(|s| *s) + }; + saved.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Read the Proof Setups folder's listing again on another thread (`view.proofSetup.list`'s +/// listing: file names only, at most 100), unless the session has no folder. While a read is under +/// way, another read starts when it ends ([`poll`]). `ctx` is asked to draw when the read ends. +pub fn refresh_saved(app: &VectorcraftApp, ctx: Option<&egui::Context>) { + let Some(dir) = app.session.proof_setup_dir().map(std::path::Path::to_path_buf) else { return }; + let mut saved = saved(); + if saved.reading.is_some() { + saved.pending = true; + return; + } + let (tx, rx) = std::sync::mpsc::channel(); + let ctx = ctx.cloned(); + let spawned = std::thread::Builder::new().name("vectorcraft-proof-setups".into()).spawn(move || { + // The app's own folder, read for the person at the keyboard. + let listed = vectorcraft_engine::file_access::unconfined(|| proof_file::listed(&dir)); + let setups = listed + .ok() + .flatten() + .and_then(|r| r["setups"].as_array().cloned()) + .unwrap_or_default() + .iter() + .filter_map(|e| Some((e["name"].as_str()?.to_string(), e["path"].as_str()?.to_string()))) + .collect(); + if tx.send(setups).is_ok() + && let Some(ctx) = ctx + { + ctx.request_repaint(); + } + }); + if spawned.is_ok() { + saved.reading = Some(rx); + } +} + +/// Take in the read under way: when it has ended, or with `wait` once it ends. A name past the +/// menu's name limit is left out. +fn take(wait: bool) { + let mut saved = saved(); + let Some(reading) = &saved.reading else { return }; + let listed = if wait { reading.recv().map_err(|_| TryRecvError::Disconnected) } else { reading.try_recv() }; + match listed { + Ok(listed) => { + let setups: Vec<(&'static str, String)> = + listed.into_iter().filter_map(|(name, path)| Some((crate::scripts_menu::intern(&name)?, path))).collect(); + if saved.setups != setups { + saved.setups = setups; + saved.revision += 1; + } + saved.reading = None; + } + Err(TryRecvError::Empty) => {} + Err(TryRecvError::Disconnected) => saved.reading = None, + } +} + +/// Wait for the read under way and take it in. +#[cfg(test)] +pub(crate) fn wait() { + take(true); +} + +/// Once per iteration: list the folder on the first one, after `view.proofSetup.save` wrote a +/// setup (from the dialog, a control client or the command palette), and when the window becomes +/// the active one, so a setup copied into the folder is listed without a restart; take in a read +/// that ended, and then start a read asked for while it was under way. Once Save…'s picker shown +/// off the UI thread has closed, the folder it made is removed if it is still empty. +pub fn poll(app: &mut VectorcraftApp, ctx: &egui::Context) { + let focused = ctx.input(|i| i.focused); + let saves = app.session.proof_setup_saves(); + let start = { + let mut saved = saved(); + if !app.picks.is_waiting() + && let Some(dir) = saved.made.take() + { + // A folder that a setup was saved in is not empty, and stays. + let _ = std::fs::remove_dir(dir); + } + let start = !saved.started || (focused && !saved.focused) || saves != saved.saves; + (saved.started, saved.focused, saved.saves) = (true, focused, saves); + start + }; + if start { + refresh_saved(app, Some(ctx)); + } + take(false); + let again = { + let mut saved = saved(); + let again = saved.pending && saved.reading.is_none(); + if again { + saved.pending = false; + } + again + }; + if again { + refresh_saved(app, Some(ctx)); + } +} + +/// Changes whenever the menus' listing changes. +pub fn saved_revision() -> u64 { + saved().revision +} + +/// View › Proof Setup's saved setups, each by its file's name, loading it with Proof Colors on. +pub fn saved_items() -> Vec { + saved().setups.iter().map(|&(name, ref path)| Item::Cmd(name, LOAD, json!({ "path": path }))).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + /// Proof views are process-wide: these tests take turns, and each leaves the default view. + static VIEW: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + struct DefaultView<'a>(#[allow(dead_code)] std::sync::MutexGuard<'a, ()>); + + impl DefaultView<'_> { + fn new() -> Self { + let g = VIEW.lock().unwrap_or_else(|e| e.into_inner()); + proof::set_view(Default::default()); + DefaultView(g) + } + } + + impl Drop for DefaultView<'_> { + fn drop(&mut self) { + proof::set_view(Default::default()); + } + } + + fn frame(app: &mut VectorcraftApp, ctx: &egui::Context) { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + } + + fn app() -> (VectorcraftApp, egui::Context) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + (app, ctx) + } + + /// View › Proof Setup › Customize… opens the dialog on the current proof setup; OK sets the + /// device, Preserve Numbers, the intent and Simulate Black Ink, and turns Proof Colors on. + #[test] + fn customize_sets_the_proof_setup_and_turns_proof_colors_on() { + let _v = DefaultView::new(); + let (mut app, ctx) = app(); + let item = crate::menus::menu_entries(&app).into_iter().find(|e| e.path == ["View", "Proof Setup"] && e.label == "Customize…").unwrap(); + app.run(item.command.as_deref().unwrap(), item.params.clone()).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.kind, KIND); + assert_eq!((d.str("device"), d.str("intent"), d.bool("preserveNumbers")), (WORKING.to_string(), "relative".to_string(), false)); + frame(&mut app, &ctx); + let device = format!("cmyk:{}", cms::DEVICE_CMYK); + let d = app.ui.dialog.as_mut().unwrap(); + for (k, v) in [("device", json!(device)), ("intent", json!("perceptual")), ("simulateBlack", json!(true)), ("preview", json!(false))] { + d.fields.insert(k.into(), v); + } + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let v = proof::view(); + assert!(v.proof_colors); + assert_eq!(v.setup.target, ProofTarget::Cmyk(cms::DEVICE_CMYK.into())); + assert_eq!(v.setup.intent, Intent::Perceptual); + assert!(v.setup.simulate_black && !v.setup.preserve_numbers && !v.setup.simulate_paper); + // Opened again, it shows those settings, and the menu checks Customize…. + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("device"), d.str("intent"), d.bool("simulateBlack")), (device, "perceptual".to_string(), true)); + assert_eq!(crate::menus::checked(&app, "ui.proofSetupDialog", &json!({})), Some(true)); + super::super::cancel(&mut app); + } + + /// Preview shows the dialog's settings on the canvas at once, follows their changes, and + /// Cancel (or turning Preview off) puts the earlier proof view back. + #[test] + fn preview_shows_the_settings_and_cancel_puts_the_view_back() { + let _v = DefaultView::new(); + let (mut app, ctx) = app(); + app.run("view.proofSetup", json!({"target": "protanopia"})).unwrap(); + let before = proof::view(); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("device"), WORKING, "a color blindness proof starts on the working CMYK"); + let rgb = format!("rgb:{}", cms::DISPLAY_P3); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("device".into(), json!(rgb)); + d.fields.insert("preserveNumbers".into(), json!(true)); + frame(&mut app, &ctx); + let v = proof::view(); + assert!(v.proof_colors, "the preview turns Proof Colors on"); + assert_eq!(v.setup.target, ProofTarget::Rgb(cms::DISPLAY_P3.into())); + assert!(v.setup.preserve_numbers); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(false)); + frame(&mut app, &ctx); + assert_eq!(proof::view(), before, "Preview off puts the view back"); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true)); + frame(&mut app, &ctx); + assert_eq!(proof::view().setup.target, ProofTarget::Rgb(cms::DISPLAY_P3.into())); + super::super::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(proof::view(), before, "Cancel puts the view back"); + } + + /// Cancel and Preview off put back a proof view whose device profile was removed after it was + /// set, and redraw the documents. + #[test] + fn cancel_puts_back_a_view_whose_profile_was_removed() { + let _v = DefaultView::new(); + let (mut app, ctx) = app(); + let name = "Proof Setup Removed RGB"; + cms::register_icc(&cms::icc_bytes(cms::DISPLAY_P3).unwrap(), Some(name.into())).unwrap(); + app.run("view.proofSetup", json!({"target": format!("rgb:{name}"), "proof": true})).unwrap(); + app.run("color.removeProfile", json!({"name": name})).unwrap(); + let before = proof::view(); + assert_eq!(before.setup.target, ProofTarget::Rgb(name.into()), "removing the profile leaves it the device"); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("device".into(), json!(WORKING)); + frame(&mut app, &ctx); + assert_eq!(proof::view().setup.target, ProofTarget::WorkingCmyk, "the preview shows the working CMYK"); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(false)); + frame(&mut app, &ctx); + assert_eq!(proof::view(), before, "Preview off puts the view back"); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true)); + frame(&mut app, &ctx); + let revision = app.session.doc().unwrap().revision; + super::super::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(proof::view(), before, "Cancel puts the view back"); + assert!(app.session.doc().unwrap().revision > revision, "the document redraws"); + } + + /// Run again while the dialog is open, Proof Setup keeps the dialog as it is, so Cancel still + /// puts back the view it found the first time. + #[test] + fn running_proof_setup_again_keeps_the_open_dialog() { + let _v = DefaultView::new(); + let (mut app, ctx) = app(); + let before = proof::view(); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let rgb = format!("rgb:{}", cms::DISPLAY_P3); + app.ui.dialog.as_mut().unwrap().fields.insert("device".into(), json!(rgb)); + frame(&mut app, &ctx); + assert_eq!(proof::view().setup.target, ProofTarget::Rgb(cms::DISPLAY_P3.into())); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("device"), rgb, "the open dialog stays as it is"); + super::super::cancel(&mut app); + assert_eq!(proof::view(), before, "Cancel puts back the view the first run found"); + } + + /// When another dialog (Saturate) takes the place of a previewing Proof Setup dialog, the proof + /// view the dialog found comes back, and a later Proof Setup starts from that view. + #[test] + fn another_dialog_in_its_place_puts_the_view_back() { + let _v = DefaultView::new(); + let (mut app, ctx) = app(); + let before = proof::view(); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let rgb = format!("rgb:{}", cms::DISPLAY_P3); + app.ui.dialog.as_mut().unwrap().fields.insert("device".into(), json!(rgb)); + frame(&mut app, &ctx); + assert_eq!(proof::view().setup.target, ProofTarget::Rgb(cms::DISPLAY_P3.into()), "the preview shows"); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap(); + app.run("ui.saturateDialog", json!({})).unwrap(); + frame(&mut app, &ctx); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, super::super::saturate::KIND); + assert_eq!(proof::view(), before, "the preview is undone"); + super::super::cancel(&mut app); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("device"), WORKING, "the next Proof Setup starts from the view it found"); + super::super::cancel(&mut app); + assert_eq!(proof::view(), before); + } + + /// Opened again before a frame has drawn the dialog that replaced a previewing Proof Setup + /// dialog, Proof Setup starts from the view the first dialog found, and Cancel keeps it. + #[test] + fn reopened_before_a_frame_starts_from_the_view_it_found() { + let _v = DefaultView::new(); + let (mut app, ctx) = app(); + let before = proof::view(); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let rgb = format!("rgb:{}", cms::DISPLAY_P3); + app.ui.dialog.as_mut().unwrap().fields.insert("device".into(), json!(rgb)); + frame(&mut app, &ctx); + assert_eq!(proof::view().setup.target, ProofTarget::Rgb(cms::DISPLAY_P3.into()), "the preview shows"); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap(); + app.run("ui.saturateDialog", json!({})).unwrap(); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + assert_eq!(proof::view(), before, "the preview is undone"); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("device"), WORKING); + super::super::cancel(&mut app); + assert_eq!(proof::view(), before, "Cancel keeps the view the first dialog found"); + } + + /// A proof view set after another dialog replaced a previewing Proof Setup dialog, before a + /// frame, stays: the preview is not put back over it. + #[test] + fn a_view_set_after_the_replacement_stays() { + let _v = DefaultView::new(); + let (mut app, ctx) = app(); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let rgb = format!("rgb:{}", cms::DISPLAY_P3); + app.ui.dialog.as_mut().unwrap().fields.insert("device".into(), json!(rgb)); + frame(&mut app, &ctx); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap(); + app.run("ui.saturateDialog", json!({})).unwrap(); + app.run("view.proofSetup", json!({"target": "protanopia", "proof": true})).unwrap(); + let set = proof::view(); + frame(&mut app, &ctx); + assert_eq!(proof::view(), set, "the view set after the replacement stays"); + super::super::cancel(&mut app); + assert_eq!(proof::view(), set); + } + + /// Overprint Preview turned on during the preview stays on when another dialog replaces the + /// dialog, and the proof setup the dialog found comes back. + #[test] + fn overprint_set_during_the_preview_stays_after_the_replacement() { + let _v = DefaultView::new(); + let (mut app, ctx) = app(); + let before = proof::view(); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let rgb = format!("rgb:{}", cms::DISPLAY_P3); + app.ui.dialog.as_mut().unwrap().fields.insert("device".into(), json!(rgb)); + frame(&mut app, &ctx); + app.run("view.overprintPreview", json!({"on": true})).unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap(); + app.run("ui.saturateDialog", json!({})).unwrap(); + frame(&mut app, &ctx); + let v = proof::view(); + assert!(v.overprint, "Overprint Preview stays on"); + assert_eq!((v.setup, v.proof_colors), (before.setup, before.proof_colors), "the proof setup comes back"); + super::super::cancel(&mut app); + } + + /// Back from under a dialog opened over it (here Saturate, as a file-replacement question is), + /// which undid the preview, the dialog previews its settings again, and Cancel puts back the + /// view it found. + #[test] + fn back_from_under_another_dialog_it_previews_again() { + let _v = DefaultView::new(); + let (mut app, ctx) = app(); + let before = proof::view(); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let rgb = format!("rgb:{}", cms::DISPLAY_P3); + app.ui.dialog.as_mut().unwrap().fields.insert("device".into(), json!(rgb)); + frame(&mut app, &ctx); + let under = app.ui.dialog.clone().unwrap(); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap(); + app.run("ui.saturateDialog", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert(super::super::PARENT.into(), serde_json::to_value(under).unwrap()); + frame(&mut app, &ctx); + assert_eq!(proof::view(), before, "the preview is undone while the other dialog shows"); + super::super::cancel(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, KIND, "Proof Setup comes back"); + frame(&mut app, &ctx); + assert_eq!(proof::view().setup.target, ProofTarget::Rgb(cms::DISPLAY_P3.into()), "the preview shows again"); + super::super::cancel(&mut app); + assert_eq!(proof::view(), before, "Cancel puts back the view it found"); + } + + /// A proof setup set by a command while the dialog previews stays when Preview is turned off + /// and when the dialog is canceled. + #[test] + fn a_view_set_while_the_dialog_previews_stays() { + let _v = DefaultView::new(); + let (mut app, ctx) = app(); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let rgb = format!("rgb:{}", cms::DISPLAY_P3); + app.ui.dialog.as_mut().unwrap().fields.insert("device".into(), json!(rgb)); + frame(&mut app, &ctx); + app.run("view.proofSetup", json!({"target": "protanopia", "proof": true})).unwrap(); + let set = proof::view(); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(false)); + frame(&mut app, &ctx); + assert_eq!(proof::view(), set, "Preview off keeps the view the command set"); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true)); + frame(&mut app, &ctx); + assert_eq!(proof::view().setup.target, ProofTarget::Rgb(cms::DISPLAY_P3.into()), "the preview shows again"); + super::super::cancel(&mut app); + assert_eq!(proof::view(), set, "Cancel puts back the view the command set"); + } + + /// After a command sets a proof setup while the dialog previews, a changed setting previews + /// again, and Cancel puts back the proof setup the command set. + #[test] + fn a_changed_setting_after_a_command_keeps_the_commands_view_for_cancel() { + let _v = DefaultView::new(); + let (mut app, ctx) = app(); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let rgb = format!("rgb:{}", cms::DISPLAY_P3); + app.ui.dialog.as_mut().unwrap().fields.insert("device".into(), json!(rgb)); + frame(&mut app, &ctx); + app.run("view.proofSetup", json!({"target": "protanopia", "proof": true})).unwrap(); + let set = proof::view(); + app.ui.dialog.as_mut().unwrap().fields.insert("intent".into(), json!("perceptual")); + frame(&mut app, &ctx); + assert_eq!(proof::view().setup.intent, Intent::Perceptual, "the changed setting previews"); + super::super::cancel(&mut app); + assert_eq!(proof::view(), set, "Cancel puts back the view the command set"); + } + + /// A device the dialog can't use (a profile that is not loaded) is refused, and the dialog + /// stays open with the proof view as it was. + #[test] + fn ok_with_an_unknown_device_keeps_the_dialog_open() { + let _v = DefaultView::new(); + let (mut app, _) = app(); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("device".into(), json!("cmyk:Nope")); + d.fields.insert("preview".into(), json!(false)); + assert!(super::super::confirm(&mut app).unwrap_err().contains("unknown CMYK profile")); + assert!(app.ui.dialog.is_some()); + assert_eq!(proof::view(), Default::default()); + } + + /// Save… writes the dialog's settings to the picked file in the Proof Setups folder, which View › + /// Proof Setup then lists; Load… puts a file's settings back in the dialog, and the menu item + /// applies the setup with Proof Colors on. + #[test] + fn save_and_load_keep_a_custom_proof_setup() { + let _v = DefaultView::new(); + let (mut app, ctx) = app(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-dialog"); + let folder = dir.join("Proof Setups"); + app.session.attach_proof_setups(folder.clone()); + refresh_saved(&app, None); + wait(); + assert!(saved_items().is_empty()); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let rgb = format!("rgb:{}", cms::DISPLAY_P3); + let d = app.ui.dialog.as_mut().unwrap(); + for (k, v) in [("device", json!(rgb)), ("intent", json!("saturation")), ("preserveNumbers", json!(true)), ("preview", json!(false))] { + d.fields.insert(k.into(), v); + } + let picked = std::rc::Rc::new(std::cell::RefCell::new(None::)); + let seen = picked.clone(); + let path = folder.join("Screen").to_string_lossy().to_string(); + let answer = path.clone(); + app.services.pick_save = Some(Box::new(move |p: &FilePick| { + *seen.borrow_mut() = Some(p.clone()); + Some(answer.clone()) + })); + let mut d = app.ui.dialog.take().unwrap(); + save(&mut app, &mut d).unwrap(); + let pick = picked.borrow().clone().unwrap(); + assert_eq!(pick.folder.as_deref(), Some(folder.to_string_lossy().as_ref()), "the picker starts in the Proof Setups folder"); + let file = format!("{path}.{EXT}"); + assert!(std::path::Path::new(&file).is_file(), "the extension is added"); + assert_eq!(proof::view(), Default::default(), "saving leaves the proof view alone"); + wait(); + let items = crate::menus::menu_entries(&app).into_iter().filter(|e| e.path == ["View", "Proof Setup"] && e.command.as_deref() == Some(LOAD)); + let items: Vec<_> = items.map(|e| (e.label.to_string(), e.params.clone())).collect(); + assert_eq!(items, [("Screen".to_string(), json!({ "path": file }))]); + // A control client that may not read the folder is not shown the saved setup. + std::fs::create_dir_all(dir.join("out")).unwrap(); + let write_only = vectorcraft_engine::file_access::AutomationRoots::new(&[], &[&dir.join("out")]).unwrap(); + let listed = vectorcraft_engine::file_access::confine(write_only.as_ref(), || crate::menus::menu_entries(&app)); + assert!(!listed.iter().any(|e| e.command.as_deref() == Some(LOAD)), "a setup outside the read roots is left out"); + // A setup the command saves, outside the dialog, is listed at the next iteration. + poll(&mut app, &ctx); + wait(); + app.run("view.proofSetup.save", json!({ "name": "Direct" })).unwrap(); + poll(&mut app, &ctx); + wait(); + assert_eq!(saved_items().len(), 2, "the menu lists the new setup"); + std::fs::remove_file(folder.join(format!("Direct.{EXT}"))).unwrap(); + refresh_saved(&app, None); + wait(); + // Load… puts the file's settings back in the dialog. + for (k, v) in [("device", json!(WORKING)), ("intent", json!("perceptual")), ("preserveNumbers", json!(false))] { + d.fields.insert(k.into(), v); + } + let answer = file.clone(); + app.services.pick_open = Some(Box::new(move |_: &FilePick| Some(answer.clone()))); + load(&mut app, &mut d).unwrap(); + assert_eq!((d.str("device"), d.str("intent"), d.bool("preserveNumbers")), (rgb.clone(), "saturation".to_string(), true)); + assert_eq!(proof::view(), Default::default(), "loading into the dialog leaves the proof view alone"); + app.ui.dialog = Some(d); + frame(&mut app, &ctx); + super::super::cancel(&mut app); + // The menu item applies the saved setup and turns Proof Colors on. + app.run(LOAD, json!({ "path": file })).unwrap(); + let v = proof::view(); + assert!(v.proof_colors && v.setup.preserve_numbers); + assert_eq!((v.setup.target, v.setup.intent), (ProofTarget::Rgb(cms::DISPLAY_P3.into()), Intent::Saturation)); + } + + /// Save… whose picker is canceled saves nothing and leaves no Proof Setups folder behind. + #[test] + fn a_canceled_save_leaves_no_folder() { + let _v = DefaultView::new(); + let (mut app, ctx) = app(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-dialog-cancel"); + let folder = dir.join("Proof Setups"); + app.session.attach_proof_setups(folder.clone()); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + let opened = std::rc::Rc::new(std::cell::Cell::new(false)); + let seen = opened.clone(); + let f = folder.clone(); + app.services.pick_save = Some(Box::new(move |_: &FilePick| { + seen.set(f.is_dir()); + None + })); + save(&mut app, &mut d).unwrap(); + assert!(opened.get(), "the picker opens in the folder"); + assert!(!folder.exists(), "the canceled save removes the folder it made"); + // A picker shown off the UI thread is still open when Save… returns: its folder stays. + let (shown, _) = crate::tests::picks::off_the_ui_thread(&mut app.services); + app.ui.dialog = Some(d.clone()); + crate::picks::in_app_dialog(&mut app, &mut d, save).unwrap(); + assert_eq!(shown.requests().len(), 1, "the picker is shown off the UI thread"); + poll(&mut app, &ctx); + assert!(folder.is_dir(), "the open picker's folder stays"); + // Canceled, the picker leaves no folder once the next iteration runs. + shown.answer(&[]); + crate::picks::poll(&mut app, &ctx); + poll(&mut app, &ctx); + assert!(!folder.exists(), "the canceled picker's folder is removed"); + // A picker that answers a file there saves it, and the folder stays. + crate::picks::in_app_dialog(&mut app, &mut d, save).unwrap(); + let file = folder.join(format!("Kept.{EXT}")); + shown.answer(&[&file.to_string_lossy()]); + crate::picks::poll(&mut app, &ctx); + poll(&mut app, &ctx); + assert!(file.is_file(), "the picked file is saved"); + } + + /// The listing Save… starts asks for a frame when it ends, so an idle window takes it in. + #[test] + fn the_listing_after_a_save_asks_for_a_frame() { + let _v = DefaultView::new(); + let (mut app, _) = app(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-dialog-frame"); + let folder = dir.join("Proof Setups"); + app.session.attach_proof_setups(folder.clone()); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + d.fields.insert("preview".into(), json!(false)); + let path = folder.join("Screen").to_string_lossy().to_string(); + app.services.pick_save = Some(Box::new(move |_: &FilePick| Some(path.clone()))); + let ctx = egui::Context::default(); + let (tx, frames) = std::sync::mpsc::channel(); + ctx.set_request_repaint_callback(move |_| { + let _ = tx.send(()); + }); + app.ui_ctx = Some(ctx); + save(&mut app, &mut d).unwrap(); + // With the app's copy of the context dropped, only the listing's thread can still ask for + // a frame; the channel closes without one when that thread ends without asking. + app.ui_ctx = None; + assert_eq!(frames.recv(), Ok(()), "the finished listing asks for a frame"); + wait(); + assert_eq!(saved_items().len(), 1); + } + + /// A saved setup whose name ends in an ellipsis still loads when its menu item is chosen. + #[test] + fn a_saved_setup_named_with_an_ellipsis_loads() { + let p = json!({ "path": "Press….vcproof" }); + assert_eq!(crate::menus::click_target("Press…", LOAD, &p), (LOAD.to_string(), p.clone())); + } + + /// A saved setup keeps its file's name in every UI language, also a name the catalogs translate. + #[test] + fn a_saved_setup_keeps_its_name_in_other_languages() { + let (app, _) = app(); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").expect("de registered")); + let shown = crate::menus::display_label(&app, LOAD, "Save…"); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(shown, "Save…"); + } + + /// Load…'s picker starts in the Proof Setups folder once it exists, and in its own default + /// folder before; Load… does not make the folder. + #[test] + fn load_starts_in_the_folder_once_it_exists() { + let _v = DefaultView::new(); + let (mut app, _) = app(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-dialog-load-folder"); + let folder = dir.join("Proof Setups"); + app.session.attach_proof_setups(folder.clone()); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + let picked = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let seen = picked.clone(); + app.services.pick_open = Some(Box::new(move |p: &FilePick| { + seen.borrow_mut().push(p.folder.clone()); + None + })); + load(&mut app, &mut d).unwrap(); + assert!(!folder.exists(), "Load… does not make the folder"); + std::fs::create_dir_all(&folder).unwrap(); + load(&mut app, &mut d).unwrap(); + assert_eq!(*picked.borrow(), [None, Some(folder.to_string_lossy().into_owned())]); + } + + /// Load… of a file whose device is not loaded leaves the dialog's settings as they were. + #[test] + fn load_of_an_unusable_file_keeps_the_dialog() { + let _v = DefaultView::new(); + let (mut app, _) = app(); + let dir = vectorcraft_testkit::TempDir::new("proof-setup-dialog-bad"); + let file = dir.join("gone.vcproof").to_string_lossy().to_string(); + let text = r#"{"format": "vectorcraft-proof-setup", "version": 1, "target": "cmyk:Not Loaded", "intent": "relative"}"#; + std::fs::write(&file, text).unwrap(); + app.run("ui.proofSetupDialog", json!({})).unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + let before = d.fields.clone(); + app.services.pick_open = Some(Box::new(move |_: &FilePick| Some(file.clone()))); + let e = load(&mut app, &mut d).unwrap_err(); + assert!(e.contains("`Not Loaded`, which is not loaded"), "{e}"); + assert_eq!(d.fields, before); + } + + /// The device list holds the working CMYK space and every CMYK and RGB profile, each a target + /// `view.proofSetup` accepts. + #[test] + fn devices_list_every_cmyk_and_rgb_profile() { + let list = devices(); + assert_eq!(list[0].0, WORKING); + for p in cms::profiles().iter().filter(|p| p.kind != ProfileKind::Gray) { + assert!(list.iter().any(|(_, n)| *n == p.name), "{} is listed", p.name); + } + for (id, _) in &list { + let t = ProofTarget::parse(id).unwrap(); + assert_eq!(&t.id(), id); + assert!(rgb_device(id) == matches!(t, ProofTarget::Rgb(_))); + } + } +} diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 267b2ac0c8..1b80ce5e35 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -31,10 +31,17 @@ //! Color too. The base color can't be removed. A removed color's row goes, unless it has current //! colors and art or a group is open: it then keeps them, with no new color, so that art keeps its //! colors and the group's swatch at that place goes. Under the tools, a button switches both wheels -//! to hue and brightness (black at the center, full brightness at the edge, at the base color's +//! to hue and brightness (black at the center, full brightness at the edge, at the selected color's //! saturation; a marker drag sets hue and brightness, Add Color adds the hue and brightness clicked -//! at the base color's saturation, and the slider under the wheel is a Saturation slider) and back; -//! switching changes no color, and the dialog opens on hue and saturation. With art, the Prominent Colors bar under the wheel shows the new +//! at the selected color's saturation, and the slider under the wheel is a Saturation slider) and +//! back; switching changes no color, and the dialog opens on hue and saturation. The base color is the one the harmony rules +//! build from, drawn with the larger marker; it stays the base when another color is selected for +//! the sliders. A right-click on a marker or a color bar offers Set As Base Color, Select Shade (a +//! grid of the color's hue at 7 saturations by 7 brightnesses; a click moves the marker there as a +//! drag would), Color Picker and Remove Color; a right-click elsewhere on the wheel offers Add New +//! Color, which adds the hue and saturation there as the Add Color tool does, and a color added on +//! the line from the center to a marker moves with that marker when the colors are unlinked. Set +//! Current Color As Base Color, before the color chips, makes the selected color the base. With art, the Prominent Colors bar under the wheel shows the new //! colors, each part as wide as its row's share of the art's uses, the largest first; dragging the //! edge between two parts moves width between them, and when the drag ends the rows' current //! colors move toward those widths (`recolor.weigh`), and the art previews them. The New Color @@ -78,7 +85,10 @@ //! //! Fields (`ui.dialog.set`): `rows` ([{from: [keys], to: key, exclude?, tint?: percent of a spot //! color, added?}]; a row with no current colors, `from: []`, recolors no art, and with `added: true` -//! (a color the Add Color tool added) adds its new color to the color group; `to: null`, no new color), `colors` (null: Auto, or a count), `method`, `preserveWhite`, `preserveBlack`, +//! (a color the Add Color tool added) adds its new color to the color group; `to: null`, no new color; +//! `base: true`, the base color, else the first color the Edit tab shows; `tie: n` on a marker and +//! `follows: n` on a color added on its line, which moves with it; the dialog sends `recolor.apply` +//! the rows without these three), `colors` (null: Auto, or a count), `method`, `preserveWhite`, `preserveBlack`, //! `preserveGrays`, `limitTo` (library id, "document" for the document's swatches, "" for none), //! `group`, `groupName`, `tab` (`assign` or `edit`), `rule` (harmony id), `linked`, `preview`, //! `sliderMode` (`hsb`, `rgb`, `cmyk`, `lab` or `tint`; unset: the row color's own model, HSB for @@ -213,7 +223,8 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { None => String::new(), }; // Without art the rows are the group's colours, as they are. - let start: Vec = if art { vec![] } else { assign.iter().map(|k| json!({"from": [k], "to": k})).collect() }; + let mut start: Vec = if art { vec![] } else { assign.iter().map(|k| json!({"from": [k], "to": k})).collect() }; + number_slots(&mut start); // The Preserve checkboxes as they were last confirmed (#2960). let kept = |k: &str, default: bool| app.ui.recolor_preserve.get(k).and_then(Value::as_bool).unwrap_or(default); let fields = json!({ @@ -276,6 +287,7 @@ fn sync(app: &mut VectorcraftApp, d: &mut Dialog) { for (row, to) in rows.iter_mut().zip(assign) { row["to"] = to; } + number_slots(&mut rows); snap(app, d, &mut rows); d.fields.insert("rows".into(), Value::Array(rows)); // Find dims the preserved colors with the rows that aren't selected. @@ -335,7 +347,9 @@ fn sync_weights(app: &mut VectorcraftApp, d: &mut Dialog) { match app.session.execute("recolor.weigh", &json!({"map": rows(d), "weights": w})) { Ok(r) => { if let Some(m) = r["map"].as_array() { - d.fields.insert("rows".into(), Value::Array(m.clone())); + let mut m = m.clone(); + keep_marks(&rows(d), &mut m); + d.fields.insert("rows".into(), Value::Array(m)); } } Err(e) => app.status(e.to_string()), @@ -451,14 +465,14 @@ fn group_colors<'a>(app: &VectorcraftApp, d: &Dialog, rs: impl Iterator Result<(), String> { let rs = rows(d); let order: Vec = match which { - "prominent" => prominent_parts(d, &rs).into_iter().map(|p| p.0).collect(), - _ => (0..rs.len()).filter(|&i| in_group(&rs[i])).collect(), + "prominent" => prominent_parts(d, &rs).into_iter().map(|p| p.0).filter(|&i| to_color(&rs[i]).is_some()).collect(), + _ => (0..rs.len()).filter(|&i| in_group(&rs[i]) && to_color(&rs[i]).is_some()).collect(), }; let colors = group_colors(app, d, order.iter().filter_map(|&i| rs.get(i))); if colors.is_empty() { @@ -541,6 +555,7 @@ fn select_group(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> d.fields.remove(REDUCED); } else { let mut rs: Vec = assign.iter().map(|k| json!({"from": [k], "to": k})).collect(); + number_slots(&mut rs); snap(app, d, &mut rs); d.fields.insert("rows".into(), Value::Array(rs)); d.fields.insert("__sel".into(), json!([])); @@ -601,7 +616,7 @@ fn group_action(app: &mut VectorcraftApp, d: &mut Dialog, action: &Value) -> Res // An excluded row leaves its swatch the color it has now, as OK's `"keep"` does: with // art, the swatch's color in `__assign`; without art, the swatch's color in the group, // which an earlier Save Changes may have changed. - let filled: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).collect(); + let filled = by_place(&rs); let rest: Vec = p["groupColors"].as_array().map(|a| a.iter().skip(filled.len()).map(|k| json!({"from": [k], "to": k})).collect()).unwrap_or_default(); let assign: Vec = @@ -1169,7 +1184,7 @@ fn apply_params(d: &Dialog) -> Value { .chain(added) .collect() } else { - let filled: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).collect(); + let filled = by_place(&rs); let rest = assign.get(filled.len()..).unwrap_or_default(); let took = filled.iter().map(|r| if excluded(r) { &keep } else { &r["to"] }); took.chain(rest).chain(added).collect() @@ -1177,8 +1192,10 @@ fn apply_params(d: &Dialog) -> Value { }; Some(json!({"group": g, "groupColors": colors, "rename": rename})) }); - // A row edited with the sliders carries `model: "new"`: its art takes the mode they showed. - let mut p = json!({"map": rs, "method": d.str("method"), "limitTo": d.str("limitTo")}); + // A row edited with the sliders carries `model: "new"`: its art takes the mode they showed. The + // Edit tab's own marks (the base color, colors tied to a marker) stay in the dialog. + let map: Vec = rs.iter().map(without_marks).collect(); + let mut p = json!({"map": map, "method": d.str("method"), "limitTo": d.str("limitTo")}); // The Global Adjust amounts, kept while the sliders show another mode; at 0% they are left out. let values = adjust_values(d); if values.iter().any(|v| *v != 0.0) { @@ -1406,7 +1423,7 @@ fn main(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> Option<(usize, } let mut rs = rows(d); let top = ui.cursor().top(); - let (changed, pick) = if d.str("tab") == "edit" { (edit_tab(app, ui, d, &mut rs), None) } else { assign_tab(app, ui, d, &mut rs) }; + let (changed, pick) = if d.str("tab") == "edit" { edit_tab(app, ui, d, &mut rs) } else { assign_tab(app, ui, d, &mut rs) }; if d.str("tab") != "edit" { ui.add_space((TAB_H - (ui.cursor().top() - top)).max(0.0)); } @@ -1663,7 +1680,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { r?; } if d.bool("__newGroup") { - let colors = group_colors(app, &d, rows(&d).iter().filter(|r| in_group(r))); + let colors = group_colors(app, &d, rows(&d).iter().filter(|r| in_group(r) && to_color(r).is_some())); let r = form::commit_preview(app, "swatch.newGroup", json!({"name": d.str("groupName"), "colors": colors, "keepModel": true}))?; app.ui.recolor_history = History::default(); return Ok(r); @@ -1897,7 +1914,9 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut let p = json!({"map": rows, "order": !sb, "saturationBrightness": sb, "seed": seed}); match app.session.execute("recolor.randomize", &p) { Ok(r) => { - *rows = r["map"].as_array().cloned().unwrap_or_default(); + let mut shuffled = r["map"].as_array().cloned().unwrap_or_default(); + keep_marks(rows, &mut shuffled); + *rows = shuffled; if !sb { d.fields.insert(SHUFFLED.into(), json!(true)); } @@ -2264,6 +2283,21 @@ fn merge(rows: &mut Vec, sel: &[usize]) { for &i in rest.iter().rev() { let row = rows.remove(i); moved.splice(0..0, row["from"].as_array().cloned().unwrap_or_default()); + // The base color merged into another row makes that row the base, and the colors that + // followed the merged row's marker follow that row's. + if row[BASE] == json!(true) { + rows[first][BASE] = json!(true); + } + if let Some(t) = row[TIE].as_u64() { + match rows[first][TIE].as_u64() { + Some(to) => { + for r in rows.iter_mut().filter(|r| r[FOLLOWS].as_u64() == Some(t)) { + r[FOLLOWS] = json!(to); + } + } + None => rows[first][TIE] = json!(t), + } + } } if let Some(dst) = rows[first]["from"].as_array_mut() { dst.extend(moved); @@ -2275,7 +2309,17 @@ fn separate(rows: &mut Vec, sel: &[usize]) { let mut out = vec![]; for (i, row) in rows.drain(..).enumerate() { match row["from"].as_array() { - Some(a) if sel.contains(&i) && a.len() > 1 => out.extend(a.iter().map(|k| json!({"from": [k], "to": k}))), + Some(a) if sel.contains(&i) && a.len() > 1 => { + let at = out.len(); + out.extend(a.iter().map(|k| json!({"from": [k], "to": k}))); + // A separated row's marks (the base color, a marker's tie, a color it follows, its place) go + // to the row of its first color. + for k in [BASE, TIE, FOLLOWS, SLOT] { + if let Some(v) = row.get(k) { + out[at][k] = v.clone(); + } + } + } _ => out.push(row), } } @@ -2306,13 +2350,29 @@ fn edit_slider_row(d: &Dialog, rows: &[Value], active: &[usize], base: Option = if linked { + all + } else { + // Row `i` and the rows that follow it, directly or through another follower. + let mut moving = vec![i]; + let mut n = 0; + while let Some(&j) = moving.get(n) { + if let Some(t) = rows.get(j).and_then(|r| r[TIE].as_u64()) { + let next: Vec = all.iter().copied().filter(|&k| rows[k][FOLLOWS].as_u64() == Some(t) && !moving.contains(&k)).collect(); + moving.extend(next); + } + n += 1; + } + all.into_iter().filter(|j| moving.contains(j)).collect() + }; let Some(k) = active.iter().position(|&j| j == i) else { return }; let before: Vec = active.iter().filter_map(|&j| to_color(&rows[j])).collect(); let mut colors = before.clone(); - move_on_wheel(&mut colors, k, hsb, linked); + move_on_wheel(&mut colors, k, hsb, true); for ((&j, c), old) in active.iter().zip(&colors).zip(&before) { if key(c) != key(old) { set_to(&mut rows[j], c); @@ -2337,7 +2397,7 @@ fn wheel_axes(d: &Dialog) -> widgets::WheelAxes { /// The new color the Add Color tool gives a click at hue `h` (degrees) and `t`, the saturation (or /// with [`widgets::WheelAxes::HueBrightness`] the brightness) clicked: with the other component of -/// `base` (the base color, whose other component the wheel shows; full without one), the segmented +/// `base` (the selected color, whose other component the wheel shows; full without one), the segmented /// wheel's patch color with `segmented`, in `base`'s model. fn added_color(base: Option, h: f32, t: f32, segmented: bool, axes: widgets::WheelAxes) -> Color { let o = base.map_or(1.0, |b| b.to_hsb()[axes.other()]); @@ -2391,16 +2451,244 @@ fn removed(d: &mut Dialog, base: usize) { d.fields.remove(COMPS); } -/// The Edit tab. Returns true when the rows changed. -fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec) -> bool { +/// A row's mark as the base color, the color the harmony rules build from (`true`). +const BASE: &str = "base"; +/// A row's number on a marker that the colors added on its line follow. +const TIE: &str = "tie"; +/// A row's mark as a color added on a marker's line: the marker's `tie`, which it moves with. +const FOLLOWS: &str = "follows"; +/// A row's place when the rows were made (the group swatch it took), which it keeps when it moves. +const SLOT: &str = "slot"; + +/// Give each row its place in `rows` as its [`SLOT`]. +fn number_slots(rows: &mut [Value]) { + for (i, r) in rows.iter_mut().enumerate() { + r[SLOT] = json!(i); + } +} + +/// The rows with current colors in the order of their group swatches: each row takes the swatch at +/// its [`SLOT`], so a row moved among the color bars keeps its swatch; rows that don't all carry a +/// place go in row order. +fn by_place(rs: &[Value]) -> Vec<&Value> { + let mut filled: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).collect(); + if filled.iter().all(|r| r[SLOT].is_u64()) { + filled.sort_by_key(|r| r[SLOT].as_u64()); + } + filled +} + +/// The target of the wheel's right-click menu: `{marker, line, hs}` (row indexes and the hue and +/// saturation clicked). +const MENU_AT: &str = "__wheelMenu"; +/// Select Shade's grid: saturations across, from 0% to 100%, and brightnesses down, from 100%. +const SHADE_COLS: usize = 7; +const SHADE_ROWS: usize = 7; +const SHADE_CELL: f32 = 16.0; + +/// The base color's row: the row of `active` (the rows the Edit tab shows) marked `base`, else +/// the first of them. +fn base_row(rows: &[Value], active: &[usize]) -> Option { + active.iter().copied().find(|&i| rows[i][BASE] == json!(true)).or(active.first().copied()) +} + +/// Whether Set As Base Color would change anything for row `i`: it is shown on the Edit tab, and it +/// isn't the base already, or it is the base only because the marked row is hidden (excluded, or +/// with no new color), whose mark would make it the base again once shown. +fn can_set_base(rows: &[Value], i: usize) -> bool { + let active = active_rows(rows); + active.contains(&i) && (base_row(rows, &active) != Some(i) || rows.iter().enumerate().any(|(k, r)| k != i && r[BASE] == json!(true))) +} + +/// Make row `i` the base color (Set As Base Color). Returns false when that changes nothing +/// ([`can_set_base`]). +fn set_base(rows: &mut [Value], i: usize) -> bool { + if !can_set_base(rows, i) { + return false; + } + for r in rows.iter_mut() { + if let Some(o) = r.as_object_mut() { + o.remove(BASE); + } + } + rows[i][BASE] = json!(true); + true +} + +/// Make row `follower` move with the marker of row `leader`: the leader keeps its `tie` (a new +/// number, past every `tie` and `follows`, when it has none, so that colors left from a removed +/// marker follow no other) and the follower takes it as `follows`. +fn tie_to(rows: &mut [Value], leader: usize, follower: usize) { + if leader == follower || leader >= rows.len() || follower >= rows.len() { + return; + } + let used = rows.iter().flat_map(|r| [r[TIE].as_u64(), r[FOLLOWS].as_u64()]).flatten().max(); + let t = rows[leader][TIE].as_u64().unwrap_or_else(|| used.map_or(1, |m| m.saturating_add(1))); + rows[leader][TIE] = json!(t); + rows[follower][FOLLOWS] = json!(t); +} + +/// Give each row of `after` the base, tie and follows marks of the row at its place in `before`, +/// when the two have as many rows (the engine's `recolor.randomize` and `recolor.weigh` keep the +/// rows in order and return them without the dialog's own marks). +fn keep_marks(before: &[Value], after: &mut [Value]) { + if before.len() != after.len() { + return; + } + for (a, b) in after.iter_mut().zip(before) { + for k in [BASE, TIE, FOLLOWS, SLOT] { + if a.get(k).is_none() + && let Some(v) = b.get(k) + { + a[k] = v.clone(); + } + } + } +} + +/// `row` without the dialog's base, tie, follows and place marks. +fn without_marks(row: &Value) -> Value { + let mut r = row.clone(); + if let Some(o) = r.as_object_mut() { + for k in [BASE, TIE, FOLLOWS, SLOT] { + o.remove(k); + } + } + r +} + +/// The saturation and brightness of Select Shade's cell in column `col` and row `row`. +fn shade_at(col: usize, row: usize) -> [f32; 2] { + [col as f32 / (SHADE_COLS - 1) as f32, 1.0 - row as f32 / SHADE_ROWS as f32] +} + +/// Select Shade's grid of `c`'s hue, the cell nearest `c` framed. Returns the saturation and +/// brightness of the cell clicked. +fn shade_grid(ui: &mut Ui, c: &Color) -> Option<[f32; 2]> { + let t = Tokens::get(ui.ctx()); + let [h, s0, v0] = c.to_hsb(); + let near = ((s0 * (SHADE_COLS - 1) as f32).round() as usize, (((1.0 - v0) * SHADE_ROWS as f32).round() as usize).min(SHADE_ROWS - 1)); + let mut out = None; + egui::Grid::new("recolor-shades").spacing([2.0, 2.0]).show(ui, |ui| { + for row in 0..SHADE_ROWS { + for col in 0..SHADE_COLS { + let [s, v] = shade_at(col, row); + let (r, resp) = ui.allocate_exact_size(vec2(SHADE_CELL, SHADE_CELL), Sense::click()); + ui.painter().rect_filled(r, 1.0, c32(&Color::from_hsb(h, s, v))); + if (col, row) == near { + ui.painter().rect_stroke(r, 1.0, egui::Stroke::new(1.5, t.accent), egui::StrokeKind::Outside); + } + let name = format!("{} {}%, {} {}%", tl!("Saturation"), (s * 100.0).round(), tl!("Brightness"), (v * 100.0).round()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &name)); + if resp.clicked() { + out = Some([s, v]); + ui.close(); + } + } + ui.end_row(); + } + }); + out +} + +/// What a marker's or a color bar's right-click menu, or the wheel's, chose. +enum MenuChoice { + /// Set As Base Color for the row. + Base(usize), + /// Select Shade: the row's color at this saturation and brightness. + Shade(usize, [f32; 2]), + /// Color Picker for the row. + Picker(usize), + /// Remove Color for the row. + Remove(usize), + /// Add New Color at this hue and saturation, moving with the marker of the row on whose line + /// it is. + Add([f32; 2], Option), +} + +/// A marker's or a color bar's right-click menu for row `i`: Set As Base Color and Remove Color +/// (neither for the base color `base`), Select Shade and Color Picker. +fn color_menu(ui: &mut Ui, rows: &[Value], i: usize, base: Option) -> Option { + let mut choice = None; + if widgets::menu_item_name(ui, tl!("Set As Base Color"), can_set_base(rows, i), false) { + choice = Some(MenuChoice::Base(i)); + } + if let Some(c) = rows.get(i).and_then(to_color) { + // Indented like the items beside it (their check column). + ui.menu_button(format!(" {}", tl!("Select Shade")), |ui| { + if let Some(sv) = shade_grid(ui, &c) { + choice = Some(MenuChoice::Shade(i, sv)); + } + }); + } + if widgets::menu_item_name(ui, tl!("Color Picker"), true, false) { + choice = Some(MenuChoice::Picker(i)); + } + if widgets::menu_item_name(ui, tl!("Remove Color"), Some(i) != base, false) { + choice = Some(MenuChoice::Remove(i)); + } + choice +} + +/// Carry out a right-click menu's `choice` on the rows (`base`: the base color's row; `shown`: the +/// color whose brightness the wheel shows; `segmented`: the menu was on the segmented wheel). +/// Returns whether the rows changed and the row whose new color the Color Picker is to edit. +fn choose( + d: &mut Dialog, + rows: &mut Vec, + choice: MenuChoice, + base: Option, + shown: Option, + segmented: bool, + axes: widgets::WheelAxes, +) -> (bool, Option) { + match choice { + MenuChoice::Base(i) => (set_base(rows, i), None), + MenuChoice::Shade(i, [s, v]) => { + let Some(h) = rows.get(i).and_then(to_color).map(|c| c.to_hsb()[0]) else { return (false, None) }; + let before = rows.clone(); + move_color(rows, i, [h, s, v], d.bool("linked")); + d.fields.insert("__sel".into(), json!([i])); + d.fields.remove(COMPS); + (*rows != before, None) + } + MenuChoice::Picker(i) => { + d.fields.insert("__sel".into(), json!([i])); + (false, Some(i)) + } + MenuChoice::Remove(i) => match remove_color(rows, i, base, keeps_rows(d)) { + Some(b) => { + removed(d, b); + (true, None) + } + None => (false, None), + }, + MenuChoice::Add([h, s], line) => { + let i = add_color(rows, &added_color(shown, h, s, segmented, axes)); + if let Some(l) = line { + tie_to(rows, l, i); + } + d.fields.insert("__sel".into(), json!([i])); + d.fields.remove(COMPS); + (true, None) + } + } +} + +/// The Edit tab. Returns whether the rows changed and the row whose new color a right-click menu's +/// Color Picker is to edit. +fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec) -> (bool, Option<(usize, bool)>) { let top = ui.cursor().top(); let t = Tokens::get(ui.ctx()); let mut changed = false; + let mut pick = None; let linked = d.bool("linked"); let active = active_rows(rows); - let base = selection(d).into_iter().find(|i| active.contains(i)).or(active.first().copied()); - let slider_row = edit_slider_row(d, rows, &active, base); - let target = SliderTarget::at(app, d, rows, slider_row); + // The harmony rules build from the base color; the sliders and the Brightness slider edit the + // selected color (the base color when the tab does not show the first selected row). + let base = base_row(rows, &active); + let sel = edit_slider_row(d, rows, &active, base); + let target = SliderTarget::at(app, d, rows, sel); ui.horizontal(|ui| { ui.label(egui::RichText::new(tl!("Harmony Rules:")).color(t.text_dim)); let rule = Harmony::parse(&d.str("rule")).unwrap_or(Harmony::Complementary); @@ -2421,9 +2709,9 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec = active.iter().filter_map(|&i| to_color(&rows[i])).collect(); let marked = base.and_then(|b| active.iter().position(|&i| i == b)); + let selected = sel.and_then(|s| active.iter().position(|&i| i == s)); + let shown = sel.and_then(|s| to_color(&rows[s])); + let mut choice = None; let display = d.str("display"); let tool = d.str(WHEEL_TOOL); let axes = wheel_axes(d); @@ -2482,15 +2773,56 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec changed |= color_bars(ui, d, rows, &active, base), - _ => w = widgets::wheel_of(ui, "recolor-wheel", WHEEL, &colors, marked, display == "segmented", axes), + "bars" => { + let (moved, chosen) = color_bars(ui, d, rows, &active, base); + changed |= moved; + choice = chosen; + } + _ => w = widgets::recolor_wheel(ui, "recolor-wheel", WHEEL, &colors, marked, selected, display == "segmented", axes), }); }); + // A right-click on the wheel: a marker's menu, or Add New Color elsewhere. Its target is kept + // while the menu stays open. + if let Some((hit, line, hs)) = w.secondary { + d.fields.insert(MENU_AT.into(), json!({"marker": hit.map(|k| active[k]), "line": line.map(|k| active[k]), "hs": hs})); + } else if w.response.as_ref().is_some_and(egui::Response::secondary_clicked) { + // A right-click off the wheel (in a corner of its square) targets nothing: its menu's Add + // New Color is off, and no earlier marker is changed. + d.fields.remove(MENU_AT); + } + if let Some(resp) = &w.response { + let at = d.fields.get(MENU_AT).cloned().unwrap_or_default(); + let row = |k: &str| at[k].as_u64().map(|i| i as usize).filter(|i| active.contains(i)); + let hs = at["hs"].as_array().and_then(|a| Some([a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32])); + resp.context_menu(|ui| match row("marker") { + Some(i) => choice = color_menu(ui, rows, i, base), + None => { + if widgets::menu_item_name(ui, tl!("Add New Color"), hs.is_some(), false) + && let Some(hs) = hs + { + choice = Some(MenuChoice::Add(hs, row("line"))); + } + } + }); + } + // A menu's choice changes the rows the wheel's indexes were for, so the wheel's own clicks and + // drags of this frame are left alone. + let chosen = choice.is_some(); + if let Some(c) = choice { + let (did, picked) = choose(d, rows, c, base, shown, display == "segmented", axes); + changed |= did; + pick = picked.map(|i| (i, false)); + } + if chosen { + w.pressed = None; + w.moved = None; + w.clicked = None; + } // A click with a wheel tool adds a color there, or removes the color of the marker clicked. let clicked = w.clicked.filter(|_| on_wheel && matches!(tool.as_str(), "add" | "remove")); if let Some((hit, [h, out])) = clicked { if tool == "add" { - let c = added_color(base.and_then(|b| to_color(&rows[b])), h, out, display == "segmented", axes); + let c = added_color(shown, h, out, display == "segmented", axes); let i = add_color(rows, &c); d.fields.insert("__sel".into(), json!([i])); d.fields.remove(COMPS); @@ -2534,43 +2866,57 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec, active: &[usize], base: Option) -> bool { +/// the pointer shows, keeping every new color. A bar's right-click menu is a marker's +/// ([`color_menu`]). Returns true when the rows moved, and the menu's choice. +fn color_bars(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value], active: &[usize], base: Option) -> (bool, Option) { let t = Tokens::get(ui.ctx()); let mut rects: Vec = Vec::with_capacity(active.len()); - let (mut dragging, mut released, mut dropped, mut remove) = (None, None, None, None); + let (mut dragging, mut released, mut dropped, mut choice) = (None, None, None, None); // The area is given its full height first: in the row beside the display buttons a scroll area // alone is only as tall as the room the row has. let area = vec2(ui.available_width(), BARS_H); @@ -2603,8 +2949,8 @@ fn color_bars(ui: &mut Ui, d: &mut Dialog, rows: &mut Vec, active: &[usiz rects.push(r); let resp = resp.on_hover_text(rows[i]["to"].as_str().unwrap_or_default()); resp.context_menu(|ui| { - if widgets::menu_item_name(ui, tl!("Remove Color"), Some(i) != base, false) { - remove = Some(i); + if let Some(c) = color_menu(ui, rows, i, base) { + choice = Some(c); } }); } @@ -2621,15 +2967,14 @@ fn color_bars(ui: &mut Ui, d: &mut Dialog, rows: &mut Vec, active: &[usiz dropped = released.zip(at); }); }); - if let Some(b) = remove.and_then(|i| remove_color(rows, i, base, keeps_rows(d))) { - removed(d, b); - return true; + if choice.is_some() { + return (false, choice); } - let Some(moved) = dropped.and_then(|(n, to)| move_bar(rows, active, n, to)) else { return false }; + let Some(moved) = dropped.and_then(|(n, to)| move_bar(rows, active, n, to)) else { return (false, None) }; d.fields.insert("__sel".into(), json!([moved])); // The slider values held are those of a row index that may now hold another row. d.fields.remove(COMPS); - true + (true, None) } /// Move the row of the `from`th active row (of `active`, ascending row indexes) to before the @@ -2790,6 +3135,67 @@ mod tests { assert_eq!(apply_params(&d)["groupColors"], json!(["rgb 1 1 1", null, "rgb 3 3 3"])); } + /// An excluded row with current colors keeps the group's swatch at its place as it is, even + /// after its new color was edited or removed, and with Global Adjust on. + #[test] + fn an_excluded_row_keeps_its_group_swatch() { + let mut d = Dialog::new(KIND, json!({"group": "G", "groupName": "G", "__art": true, "__assign": ["rgb 1 1 1", "rgb 2 2 2", "rgb 3 3 3"]})); + let rs = json!([ + {"from": ["rgb 255 0 0"], "to": "rgb 7 7 7", "exclude": true}, + {"from": ["rgb 0 0 255"], "to": null, "exclude": true}, + {"from": ["rgb 0 255 0"], "to": "rgb 8 8 8"}, + ]); + d.fields.insert("rows".into(), rs); + assert_eq!(apply_params(&d)["groupColors"], json!(["keep", "keep", "rgb 8 8 8"])); + // Without art the rows are the group's colors. + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "G", "colors": ["#2878f0", "#ff0000"]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "G"})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + let mut rs = super::rows(&d); + rs[0]["to"] = json!("#00ff00"); + rs[0]["exclude"] = json!(true); + rs[1]["to"] = json!("#0000ff"); + d.fields.insert("rows".into(), json!(rs)); + d.fields.insert("globalAdjust".into(), json!({"brightness": -50})); + confirm(&mut app, &d).unwrap(); + let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "G").unwrap(); + let hex: Vec = g.swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect(); + assert_eq!(hex[0], "#2878f0", "{hex:?}"); + assert_ne!(hex[1], "#ff0000", "{hex:?}"); + } + + /// A row moved among the color bars keeps the group swatch it took when the rows were made, so + /// an excluded row's swatch stays as it is and the other swatches keep their places. + #[test] + fn a_moved_row_keeps_its_group_swatch() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "G", "colors": ["#ff0000", "#0000ff", "#00ff00"]})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "G"})).unwrap(); + let mut d = app.ui.dialog.clone().unwrap(); + let mut rs = super::rows(&d); + rs[1]["exclude"] = json!(true); + rs[2]["to"] = json!("#ffff00"); + let active = active_rows(&rs); + assert_eq!(active, [0, 2]); + // Drag the last bar (green, now yellow) above the first (red). + assert_eq!(move_bar(&mut rs, &active, 1, 0), Some(0)); + d.fields.insert("rows".into(), json!(rs)); + let colors = &apply_params(&d)["groupColors"]; + assert_eq!(colors[1], json!("keep"), "{colors}"); + confirm(&mut app, &d).unwrap(); + let g = app.session.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "G").unwrap(); + let hex: Vec = g.swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect(); + assert_eq!(hex, ["#ff0000", "#0000ff", "#ffff00"]); + // Rows reduced from art carry their place too, and `recolor.apply` gets none. + let mut rows = vec![json!({"from": ["rgb 255 0 0"], "to": "rgb 1 1 1"}), json!({"from": ["rgb 0 0 255"], "to": "rgb 2 2 2"})]; + number_slots(&mut rows); + assert_eq!(rows.iter().map(|r| r[SLOT].clone()).collect::>(), [json!(0), json!(1)]); + assert!(without_marks(&rows[0]).get(SLOT).is_none()); + } + #[test] fn merge_and_separate_rows() { let mut r = rows(); @@ -2927,6 +3333,117 @@ mod tests { assert_eq!([&r[0]["to"], &r[1]["to"], &r[2]["to"]], ["rgb 255 0 0", "rgb 0 255 0", "rgb 0 0 255"]); } + /// The base color is the row marked `base`, else the first row shown; Set As Base Color moves the + /// mark, and does nothing for the base row already or a row the Edit tab doesn't show. + #[test] + fn set_base_moves_the_base_mark() { + let mut r = rows(); + assert_eq!(base_row(&r, &active_rows(&r)), Some(0)); + assert!(!set_base(&mut r, 0), "the first row is the base already"); + assert!(set_base(&mut r, 2)); + assert_eq!(base_row(&r, &active_rows(&r)), Some(2)); + assert!(set_base(&mut r, 1)); + assert_eq!(r.iter().filter(|x| x[BASE] == json!(true)).count(), 1, "one base mark: {r:?}"); + assert!(!set_base(&mut r, 1)); + r[2]["exclude"] = json!(true); + assert!(!set_base(&mut r, 2), "an excluded row isn't shown"); + assert!(!set_base(&mut r, 9)); + // An excluded base row leaves the first row shown as the base. + r[1]["exclude"] = json!(true); + assert_eq!(base_row(&r, &active_rows(&r)), Some(0)); + // Setting that row as the base keeps it the base once the marked row is shown again. + assert!(set_base(&mut r, 0), "the hidden row's mark moves to it"); + r[1]["exclude"] = json!(false); + assert_eq!(base_row(&r, &active_rows(&r)), Some(0), "{r:?}"); + } + + /// Merge and Separate keep the base mark on a row of the base color's colors; Randomize's rows + /// (as the engine returns them) take the marks at their places again; `recolor.apply` gets no marks. + #[test] + fn the_base_mark_follows_merge_separate_and_randomize() { + let mut r = rows(); + set_base(&mut r, 2); + merge(&mut r, &[0, 2]); + assert_eq!(r[0][BASE], json!(true), "merged into the first row: {r:?}"); + let mut r = rows(); + set_base(&mut r, 1); + separate(&mut r, &[1]); + assert_eq!(r.len(), 4); + assert_eq!((r[1][BASE].clone(), r[2].get(BASE)), (json!(true), None), "{r:?}"); + // A marker's tie goes with it too. + let mut t = rows(); + t[1][TIE] = json!(1); + separate(&mut t, &[1]); + assert_eq!((t[1][TIE].clone(), t[2].get(TIE)), (json!(1), None)); + let mut t = rows(); + t[0][TIE] = json!(1); + t[2][TIE] = json!(3); + t.push(json!({"from": [], "to": "rgb 1 2 3", "follows": 3})); + merge(&mut t, &[0, 2]); + assert_eq!((t[0][TIE].clone(), t[2][FOLLOWS].clone()), (json!(1), json!(1)), "its follower follows the row merged into: {t:?}"); + let before = r.clone(); + let mut shuffled: Vec = r.iter().map(without_marks).collect(); + assert!(shuffled.iter().all(|x| x.get(BASE).is_none())); + keep_marks(&before, &mut shuffled); + assert_eq!(shuffled, before); + let mut fewer = vec![json!({"from": [], "to": "rgb 1 1 1"})]; + keep_marks(&before, &mut fewer); + assert!(fewer[0].get(BASE).is_none(), "rows of another count take no marks"); + let mut d = Dialog::new(KIND, json!({})); + d.fields.insert("rows".into(), json!(before)); + assert!(apply_params(&d)["map"].as_array().unwrap().iter().all(|x| x.get(BASE).is_none())); + } + + /// A color added on a marker's line moves with that marker when the colors are unlinked; it + /// moves alone itself, and linked colors all move together as before. + #[test] + fn a_color_added_on_a_markers_line_moves_with_it() { + let hue = |r: &[Value], i: usize| to_color(&r[i]).unwrap().to_hsb()[0]; + let mut r = rows(); + let added = add_color(&mut r, &Color::from_hsb(240.0, 0.5, 1.0)); + tie_to(&mut r, 1, added); + assert_eq!((r[1][TIE].clone(), r[added][FOLLOWS].clone()), (json!(1), json!(1))); + move_color(&mut r, 1, [270.0, 1.0, 1.0], false); + assert!((hue(&r, added) - 270.0).abs() < 0.5, "the added color turns with its marker: {}", hue(&r, added)); + assert!((hue(&r, 0) - 0.0).abs() < 0.5 && (hue(&r, 2) - 120.0).abs() < 0.5, "the others stay"); + move_color(&mut r, added, [300.0, 0.5, 1.0], false); + assert!((hue(&r, 1) - 270.0).abs() < 0.5, "its marker stays"); + // A second color tied to the same marker shares its number. + let next = add_color(&mut r, &Color::from_hsb(270.0, 0.2, 1.0)); + tie_to(&mut r, 1, next); + assert_eq!(r[next][FOLLOWS], json!(1)); + let other = add_color(&mut r, &Color::from_hsb(0.0, 0.2, 1.0)); + tie_to(&mut r, 0, other); + assert_eq!(r[0][TIE], json!(2), "another marker takes a new number"); + tie_to(&mut r, 0, 0); + assert!(r[0].get(FOLLOWS).is_none(), "a row isn't tied to itself"); + // Colors left from a removed marker follow no marker tied later. + let mut r = rows(); + let added = add_color(&mut r, &Color::from_hsb(240.0, 0.5, 1.0)); + tie_to(&mut r, 1, added); + r.remove(1); + let next = add_color(&mut r, &Color::from_hsb(0.0, 0.5, 1.0)); + tie_to(&mut r, 0, next); + assert_eq!(r[0][TIE], json!(2), "{r:?}"); + // A color added on an added color's line moves with the first marker too. + let mut r = rows(); + let added = add_color(&mut r, &Color::from_hsb(240.0, 0.5, 1.0)); + tie_to(&mut r, 1, added); + let chained = add_color(&mut r, &Color::from_hsb(240.0, 0.25, 1.0)); + tie_to(&mut r, added, chained); + move_color(&mut r, 1, [250.0, 1.0, 1.0], false); + assert!((hue(&r, chained) - 250.0).abs() < 0.5, "{r:?}"); + } + + /// Select Shade's grid runs from 0% to 100% saturation across and from 100% brightness down. + #[test] + fn the_shade_grid_spans_saturation_and_brightness() { + assert_eq!(shade_at(0, 0), [0.0, 1.0]); + assert_eq!(shade_at(SHADE_COLS - 1, 0)[0], 1.0); + let last = shade_at(0, SHADE_ROWS - 1)[1]; + assert!(last > 0.0 && last < 0.2, "{last}"); + } + /// A row made with New Row is not on the Edit tab while it is empty: a harmony rule gives it /// no color and a linked move leaves its new color as it is. #[test] @@ -3407,6 +3924,41 @@ mod tests { assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 2, "a step for each group"); } + /// A color removed on the Edit tab leaves its row with no new color, and neither Save All + /// Colors, Save Prominent Colors nor OK on colors opened alone puts the row's current color in + /// the new color group. + #[test] + fn a_removed_color_joins_no_saved_color_group() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + prominent_setup(&mut app, &ctx); + let last = |app: &VectorcraftApp| -> Vec { + let doc = &app.session.doc().unwrap().doc; + doc.swatch_groups.last().unwrap().swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect() + }; + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("rows".into(), json!([{"from": [BLUE], "to": null}, {"from": [RED, PURPLE], "to": "rgb 0 255 0"}])); + d.fields.insert(SAVE_GROUP.into(), json!("all")); + frame(&mut app, &ctx, 0.1, vec![], 0); + frame(&mut app, &ctx, 0.11, vec![], 0); + assert_eq!(last(&app), ["#00ff00"], "Save All Colors"); + let n = app.session.doc().unwrap().doc.swatch_groups.len(); + app.ui.dialog.as_mut().unwrap().fields.insert(SAVE_GROUP.into(), json!("prominent")); + frame(&mut app, &ctx, 0.2, vec![], 0); + frame(&mut app, &ctx, 0.21, vec![], 0); + assert_eq!(app.session.doc().unwrap().doc.swatch_groups.len(), n + 1, "Save Prominent Colors makes a group"); + assert_eq!(last(&app), ["#00ff00"], "Save Prominent Colors"); + + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("ui.recolorDialog", json!({"colors": ["#ff0000", "#0000ff"]})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("rows".into(), json!([{"from": ["rgb 255 0 0"], "to": "rgb 255 0 0"}, {"from": ["rgb 0 0 255"], "to": null}])); + let d = d.clone(); + confirm(&mut app, &d).unwrap(); + assert_eq!(last(&app), ["#ff0000"], "OK on colors opened alone"); + } + /// Save All Colors leaves out a row made with New Row while it is empty; with only empty rows /// it saves no group and records no step. #[test] @@ -3794,6 +4346,31 @@ mod tests { assert_eq!(group_hex(&app, "A"), Some(vec!["#ff0000".into(), "#00ff00".into()]), "other groups are left as they are"); } + /// Without art: rows of a group picked in the list keep their swatches when a color bar moves, + /// at OK and at Save Changes, and an excluded row's swatch stays as it is. + #[test] + fn a_moved_row_of_a_listed_group_keeps_its_swatch_at_save_changes() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.newGroup", json!({"name": "A", "colors": ["#000000"], "keepModel": true})).unwrap(); + app.run("swatch.newGroup", json!({"name": "G", "colors": ["#ff0000", "#0000ff", "#00ff00"], "keepModel": true})).unwrap(); + app.run("ui.recolorDialog", json!({"group": "A"})).unwrap(); + set(&mut app, "group", json!("G")).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + let mut rs = super::rows(d); + rs[1]["exclude"] = json!(true); + rs[2]["to"] = json!("#ffff00"); + let active = active_rows(&rs); + // Drag the last bar (green, now yellow) above the first (red). + assert_eq!(move_bar(&mut rs, &active, 1, 0), Some(0)); + d.fields.insert("rows".into(), Value::Array(rs)); + assert_eq!(apply_params(d)["groupColors"][1], json!("keep")); + act(&mut app, &ctx, 0.1, "save").unwrap(); + assert_eq!(group_hex(&app, "G"), Some(vec!["#ff0000".into(), "#0000ff".into(), "#ffff00".into()])); + } + /// Without art: selecting another color group in the list and Save Changes leave Undo Changes /// and Redo Changes no step to go to, so OK gives the selected group the rows read for it. #[test] diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 7ad629afb8..7376973d6f 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -232,7 +232,7 @@ pub(crate) fn browser_preview(app: &mut VectorcraftApp, p: &Value) -> Result Result { /// `root` ([`preview_folder_under`]). #[cfg(not(target_arch = "wasm32"))] pub(super) fn temp_folder_under(root: &str) -> Result { + #[cfg(test)] + if let Some(tmp) = TEST_TMP.with_borrow(Clone::clone) { + return preview_folder_under(&tmp, root, PREVIEW_KEEP); + } preview_folder_under(&std::env::temp_dir(), root, PREVIEW_KEEP) } +#[cfg(all(test, not(target_arch = "wasm32")))] +thread_local! { + /// The folder this test thread's browser previews go to instead of the system's temporary + /// folder, when set. + pub(super) static TEST_TMP: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// Remove the folder `dir` made for a browser preview whose files could not all be written, so +/// a failed preview leaves no folder behind. The log says when it can't be removed. +pub(super) fn remove_preview_folder(dir: &str) { + if let Err(e) = std::fs::remove_dir_all(dir) { + log::warn!("vectorcraft: the browser preview folder {dir} can't be removed: {e}"); + } +} + /// A new folder for a Save for Web browser preview in the temporary folder `tmp` /// ([`preview_folder_under`] with `VectorCraft Save for Web`). #[cfg(all(test, not(target_arch = "wasm32")))] diff --git a/crates/ui-egui/src/dialogs/svg_options.rs b/crates/ui-egui/src/dialogs/svg_options.rs index c185a3d5cb..99b471e3f6 100644 --- a/crates/ui-egui/src/dialogs/svg_options.rs +++ b/crates/ui-egui/src/dialogs/svg_options.rs @@ -354,7 +354,8 @@ fn encode_page<'a>( /// the default browser (desktop) → `{path, warnings}`. Nothing is written to the chosen /// destination, and the document, its path and the remembered choices are left as they were. /// When the export has warnings, the status bar shows them as [`io::report_saved`] shows a save's -/// notes. Nothing opens when a check, the encoding or a write fails. +/// notes. Nothing opens when a check, the encoding or a write fails, and a failed write removes +/// the new folder. pub(crate) fn browser_preview(app: &mut VectorcraftApp, p: &Value) -> Result { if io::is_web(app) { return Err("no file system here".into()); @@ -370,7 +371,7 @@ pub(crate) fn browser_preview(app: &mut VectorcraftApp, p: &Value) -> Result>>; - /// [`app`] whose browser records each URL it is asked to open. + /// [`app`] whose browser records each URL it is asked to open. Its previews go to a temporary + /// folder of the test's own ([`preview_tmp`]), not the system's. fn browsing(picked: &str) -> (VectorcraftApp, Written, Opened) { + static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let tmp = vectorcraft_testkit::temp_dir(&format!("svg-browser-{}", N.fetch_add(1, std::sync::atomic::Ordering::Relaxed))); + super::super::save_for_web::TEST_TMP.set(Some(tmp)); let (mut app, written) = app(picked); let opened = Opened::default(); let o = opened.clone(); @@ -489,6 +494,13 @@ mod tests { (app, written, opened) } + /// The SVG preview folder inside this test's temporary folder ([`browsing`]), with `/` between + /// its parts. + fn preview_tmp() -> String { + let tmp = super::super::save_for_web::TEST_TMP.with_borrow(Clone::clone).expect("browsing sets the temporary folder"); + tmp.join(PREVIEW_ROOT).to_string_lossy().replace('\\', "/") + } + /// Show in Browser for the open dialog's current choices, as its button runs it. fn show_in_browser(app: &mut VectorcraftApp) -> Result { let p = preview_params(app.ui.dialog.as_ref().expect("SVG Options open")); @@ -510,7 +522,7 @@ mod tests { let remembered = app.ui.svg_options.clone(); let r = show_in_browser(&mut app).unwrap_or_else(|e| panic!("{e}")); let path = r["path"].as_str().unwrap().to_string(); - assert!(path.contains("/VectorCraft SVG Preview/") && path.ends_with("/Untitled-1.svg"), "{path}"); + assert!(path.starts_with(&format!("{}/", preview_tmp())) && path.ends_with("/Untitled-1.svg"), "{path}"); assert_eq!(*opened.borrow(), [io::file_url(&path)]); assert_eq!(written.borrow().len(), 1); assert_eq!(written.borrow()[0].0, path); @@ -538,6 +550,18 @@ mod tests { assert!(app.ui.dialog.is_some()); } + /// A write that fails opens nothing and removes the folder made for that preview. + #[test] + fn show_in_browser_removes_its_folder_when_a_write_fails() { + let (mut app, _, opened) = browsing("/tmp/out.svg"); + app.services.write = Some(Box::new(|_: &str, _: &[u8]| Err("disk full".to_string()))); + app.run("file.export.svg", Value::Null).unwrap(); + assert!(show_in_browser(&mut app).unwrap_err().contains("disk full")); + assert!(opened.borrow().is_empty()); + let left: Vec<_> = std::fs::read_dir(preview_tmp()).map(|d| d.flatten().map(|e| e.file_name()).collect()).unwrap_or_default(); + assert!(left.is_empty(), "{left:?}"); + } + /// Under Export Selection the preview is the selection alone, cropped to it, as OK writes it. #[test] fn show_in_browser_under_export_selection_shows_the_selection() { @@ -606,7 +630,9 @@ mod tests { app.ui.answering_control = true; assert!(show_in_browser(&mut app).unwrap_err().contains("opens another app")); app.ui.answering_control = false; + assert!(crate::menus::enabled(&app, BROWSER)); app.services.download = Some(Box::new(|_: &str, _: &[u8]| Ok(()))); + assert!(!crate::menus::enabled(&app, BROWSER), "the command palette and menus show it disabled on the web"); assert!(show_in_browser(&mut app).is_err()); assert!(written.borrow().is_empty() && opened.borrow().is_empty()); } diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 43a37812b5..08866563fd 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -12,7 +12,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_tools::settings::SYMBOLISM; -use super::{DialogResult, DialogSpec, form, set_tool_options_and_close}; +use super::{DialogResult, DialogSpec, form, modal, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -55,6 +55,13 @@ pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { } fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + // The rows scroll when the window is shorter than they are, so the heading and the buttons + // stay in view. + modal::scrolled_rows(ui, "symbolism-options-rows", |ui| rows(app, ui, d)); + false +} + +fn rows(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let unit = app.session.general_unit(); // The tool whose options show below (the eight tools share one toolbar icon, so they are listed // by name). @@ -107,10 +114,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } ui.add_space(10.0); form::check(ui, d, "showBrush", tl!("Show Brush Size and Intensity")); - false } -/// The selected symbol sets that can be edited (not locked or hidden). +/// The selected symbol sets that can be edited (a locked or hidden one keeps its density). fn selected_sets(app: &VectorcraftApp) -> Vec { let Some(st) = app.session.active() else { return vec![] }; let editable = st.doc.editable(); @@ -123,39 +129,42 @@ fn selected_sets(app: &VectorcraftApp) -> Vec { } /// OK: set the brush the Symbolism tools share, after giving a new Symbol Set Density to the -/// selected symbol sets. Every option is checked first, so a value the tools refuse (a number out -/// of its range included) leaves the symbol sets and the options as they are. +/// selected symbol sets. A value outside its range is refused and changes nothing. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { - let mut values: Map = - NUMBERS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect(); - // The checkboxes and choices as the fields hold them, so a value the tools do not have is refused. - values.extend(SWITCHES.iter().chain(&SPRAY).chain(&["method"]).filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone())))); - // An option `tool.setOption` refuses leaves the symbol sets as they are too. + // Each value goes to the check as it is stored, so one of the wrong kind is refused rather than + // read as 0 or false. A number stored as text is read as the field reads it, and other text is + // refused. + let stored = |k: &str| match d.fields.get(k) { + Some(Value::String(s)) => Some(vectorcraft_doc::Unit::Points.parse(s).map_or_else(|| json!(s), |n| json!(n))), + v => v.cloned(), + }; + let mut values: Map = NUMBERS.iter().filter_map(|k| Some((k.to_string(), stored(k)?))).collect(); + values.extend(SWITCHES.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone())))); + values.extend(SPRAY.iter().chain(&["method"]).filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.str(k))))); + // A tool or a value `tool.setOption` refuses changes no density either: the values go through + // both of its checks, the kinds and then each option's range, before the density changes. let tool = d.str("tool"); if !SYMBOLISM.contains(&tool.as_str()) { return Err(format!("unknown tool `{tool}`")); } - // A number, or text that reads as one (a length with its unit for the diameter). - let readable = |v: &Value| match v { - Value::Number(_) => true, - Value::String(s) => vectorcraft_doc::Unit::Points.parse(s).is_some(), - _ => false, - }; - if let Some(k) = NUMBERS.iter().chain(&[DENSITY_WAS]).find(|k| d.fields.get(**k).is_some_and(|v| !readable(v))) { - return Err(format!("`{k}` must be a number")); - } vectorcraft_tools::symbolism::check_options(&tool, &values)?; + vectorcraft_tools::option_check::check_values(&vectorcraft_tools::symbolism::SymbolismTool::new(&tool), &values)?; + // The density the sets had when the dialog opened is read as a number too. + if stored(DENSITY_WAS).is_some_and(|v| !v.is_number()) { + return Err(format!("`{DENSITY_WAS}` must be a number")); + } let (from, to) = (d.f64(DENSITY_WAS, 0.0).clamp(1.0, 10.0), d.f64("density", 0.0).clamp(1.0, 10.0)); let sets = selected_sets(app); if d.fields.contains_key(DENSITY_WAS) && from != to && !sets.is_empty() { app.run("symbol.setDensity", json!({ "from": from, "to": to, "ids": sets }))?; } - set_tool_options_and_close(app, json!({ "tool": d.str("tool"), "values": values })) + set_tool_options_and_close(app, json!({ "tool": tool, "values": values })) } #[cfg(test)] mod tests { use super::*; + use egui_kittest::kittest::Queryable; use vectorcraft_engine::Session; fn app() -> VectorcraftApp { @@ -168,6 +177,39 @@ mod tests { crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) } + /// In a short window the rows scroll, and the heading, OK and Cancel stay on the screen. + #[test] + fn the_buttons_stay_in_view_in_a_short_window() { + let mut app = app(); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 800.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + super::super::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + for (physical, zoom) in [(egui::vec2(1366.0, 768.0), 1.5), (egui::vec2(1280.0, 720.0), 1.5), (egui::vec2(800.0, 600.0), 1.0)] { + h.ctx.set_zoom_factor(zoom); + for _ in 0..12 { + h.set_size(physical / zoom); + h.run_steps(1); + } + let screen = h.ctx.content_rect(); + let heading = h.get_by_role_and_label(egui::accesskit::Role::Label, "Symbolism Tools Options").rect(); + assert!(screen.contains_rect(heading), "{physical:?} at {zoom}: the heading {heading:?} in {screen:?}"); + for label in ["OK", "Cancel"] { + let rect = h.get_by_label(label).rect(); + assert!(screen.contains_rect(rect), "{physical:?} at {zoom}: {label} {rect:?} in {screen:?}"); + } + } + } + #[test] fn the_symbolism_tools_share_the_options_ok_sets() { let mut app = app(); @@ -280,6 +322,56 @@ mod tests { app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); super::super::confirm(&mut app).unwrap(); assert_eq!((width(&app), undo(&app)), (was, steps)); + // An option that `tool.setOption` refuses changes neither the density nor the set. + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let fields = &mut app.ui.dialog.as_mut().unwrap().fields; + fields.insert("density".into(), json!(9)); + fields.insert("method".into(), json!("smooth")); + assert!(super::super::confirm(&mut app).is_err()); + assert_eq!((width(&app), undo(&app)), (was, steps)); + assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(5.0)); + // So does a checkbox or a number stored as a value of the wrong kind, or a number outside its + // range. + for (k, v) in [ + ("diameter", json!(1)), + ("intensity", json!(11)), + ("usePressure", json!("invalid")), + ("proportional", json!(1)), + ("intensity", json!("strong")), + ("diameter", json!(true)), + ("tool", json!("pen")), + ("tool", json!(null)), + ] { + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let fields = &mut app.ui.dialog.as_mut().unwrap().fields; + fields.insert("density".into(), json!(9)); + fields.insert(k.into(), v); + assert!(super::super::confirm(&mut app).is_err(), "{k}"); + assert_eq!((width(&app), undo(&app)), (was, steps), "{k}"); + let o = app.session.tool_options_of("symbolSizer"); + assert_eq!((o["density"].as_f64(), o["usePressure"].as_bool()), (Some(5.0), Some(false)), "{k}"); + } + // A selected set that is locked keeps its density, and OK still sets the options. + let lock = |app: &mut VectorcraftApp, on: bool| { + app.session + .edit("Lock", |d, _| { + d.node_mut(vectorcraft_doc::NodeId(set)).unwrap().locked = on; + Ok(()) + }) + .unwrap(); + }; + lock(&mut app, true); + let steps_locked = undo(&app); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(8)); + super::super::confirm(&mut app).unwrap(); + assert_eq!((width(&app), undo(&app)), (was, steps_locked)); + assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(8.0)); + lock(&mut app, false); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(5)); + super::super::confirm(&mut app).unwrap(); + let steps = undo(&app); // A higher density packs the set closer, as one undo step. app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(9)); diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index c0eccbc56d..6d388f7950 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -259,11 +259,12 @@ fn the_format_list_shows_its_scroll_bar_at_rest_and_opens_with_the_chosen_format _ => {} } } - let labels: Vec<&str> = export_as::formats().iter().map(|f| f.label).collect(); // A built-in format six from the end of the built-in ones: out of view when the list opens at // its top, and far enough from the end that a plug-in format another test adds after the - // built-in ones does not move the rows shown around it. + // built-in ones does not move the rows shown around it. The window is short enough that the + // list centered on it stops short of its end. let built_in: Vec<_> = fileio::FORMATS.iter().filter(|f| f.write && !matches!(f.id, "vectorcraft" | "ai")).collect(); + let labels: Vec<&str> = built_in.iter().map(|f| f.label).collect(); let chosen = built_in.len().checked_sub(6).and_then(|i| built_in.get(i)).copied().expect("Export As lists formats"); let (mut app, _) = app(1); app.run("file.exportAs", json!({"format": chosen.id})).unwrap(); @@ -272,31 +273,38 @@ fn the_format_list_shows_its_scroll_bar_at_rest_and_opens_with_the_chosen_format theme::apply(&ctx, Default::default()); // Every scroll area takes the bar at rest from the theme, whatever style the list sets itself. assert_eq!(ctx.global_style().spacing.scroll, crate::widgets::list_scroll_style()); - let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1024.0, 480.0))); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1024.0, 280.0))); let mut time = 0.0; + let popup = std::cell::RefCell::new(vec![]); + // The texts and bars painted on the open list (without the dialog under it), and every text. let mut run = |app: &mut VectorcraftApp, events: Vec| { time += 0.25; - let mut out = ctx.run_ui(egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }, |ui| show(app, ui.ctx())); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }, |ui| { + show(app, ui.ctx()); + popup.replace(crate::widgets::top_popup_shapes(ui.ctx())); + }); out.textures_delta.clear(); - let (mut texts, mut bars) = (vec![], vec![]); - out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts, &mut bars)); - (texts, bars) + let (mut texts, mut bars, mut all) = (vec![], vec![], vec![]); + popup.take().iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts, &mut bars)); + out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut all, &mut vec![])); + (texts, bars, all) }; let away = egui::Event::PointerMoved(egui::pos2(1.0, 1.0)); run(&mut app, vec![away.clone()]); - let (texts, _) = run(&mut app, vec![]); + let (_, _, texts) = run(&mut app, vec![]); let field = texts.iter().find(|(s, ..)| s == chosen.label).map(|(_, r, _)| r.center()).expect("the Format field shows the chosen format"); let click_at = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; // Opens the list, moves the pointer away and returns the list's rect, the format names drawn in // it with their clip rects, and the bars drawn. - type Run<'r> = dyn FnMut(&mut VectorcraftApp, Vec) -> (Vec<(String, egui::Rect, egui::Rect)>, Vec) + 'r; + type Texts = Vec<(String, egui::Rect, egui::Rect)>; + type Run<'r> = dyn FnMut(&mut VectorcraftApp, Vec) -> (Texts, Vec, Texts) + 'r; let open = |run: &mut Run<'_>, app: &mut VectorcraftApp| { run(app, vec![egui::Event::PointerMoved(field), click_at(field, true)]); run(app, vec![click_at(field, false)]); run(app, vec![away.clone()]); let (mut texts, mut bars) = (vec![], vec![]); for _ in 0..4 { - (texts, bars) = run(app, vec![]); + (texts, bars, _) = run(app, vec![]); } let list = ctx .memory(|m| { @@ -334,11 +342,13 @@ fn the_format_list_shows_its_scroll_bar_at_rest_and_opens_with_the_chosen_format run(&mut app, vec![wheel]); let mut scrolled = vec![]; for _ in 0..4 { - (scrolled, _) = run(&mut app, vec![]); + (scrolled, ..) = run(&mut app, vec![]); } let scrolled: Vec<_> = scrolled.into_iter().filter(|(s, r, _)| labels.contains(&s.as_str()) && list.contains_rect(*r)).collect(); - run(&mut app, vec![egui::Event::PointerMoved(field), click_at(field, true)]); - run(&mut app, vec![click_at(field, false)]); + // Escape closes it: a list taller than the room beside its field covers the field. + let escape = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + run(&mut app, vec![escape(true)]); + run(&mut app, vec![escape(false)]); let (_, reopened, _) = open(&mut run, &mut app); if rows.len() < labels.len() { assert_ne!(tops(&scrolled), tops(&rows), "the wheel scrolled the list"); @@ -347,6 +357,83 @@ fn the_format_list_shows_its_scroll_bar_at_rest_and_opens_with_the_chosen_format assert!(whole(&reopened, chosen.label), "the chosen format shows whole: {:?}", tops(&reopened)); } +/// #5941: the Format list stopped at the room on one side of its field, so a window with room for +/// every format still cut the list short. In windows of 1280×900 and 1000×856 the list shows every +/// built-in format whole, the grayed-out DWG row after them included, inside the window, without a +/// scroll bar. A plug-in format that another test adds or removes meanwhile is not counted. +#[test] +fn the_format_list_shows_every_format_when_the_window_has_room() { + fn walk(shape: &egui::Shape, clip: egui::Rect, texts: &mut Vec<(String, egui::Rect, egui::Rect)>, bars: &mut Vec) { + match shape { + egui::Shape::Text(t) => texts.push((t.galley.text().into(), t.visual_bounding_rect(), clip)), + egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => bars.push(r.rect), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, texts, bars)), + _ => {} + } + } + let labels: Vec<&str> = + fileio::FORMATS.iter().filter(|f| f.write && !matches!(f.id, "vectorcraft" | "ai")).map(|f| f.label).chain(["DWG (use DXF)"]).collect(); + for (width, height) in [(1280.0, 900.0), (1000.0, 856.0)] { + let case = format!("{width}×{height}"); + let (mut app, _) = app(1); + app.run("file.exportAs", json!({"format": "png"})).unwrap(); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, height)); + let mut time = 0.0; + let popup = std::cell::RefCell::new(vec![]); + // The texts and bars painted on the open list (without the dialog under it), and every text. + let mut run = |app: &mut VectorcraftApp, events: Vec| { + time += 0.25; + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, time: Some(time), ..Default::default() }, |ui| { + show(app, ui.ctx()); + popup.replace(crate::widgets::top_popup_shapes(ui.ctx())); + }); + out.textures_delta.clear(); + let (mut texts, mut bars, mut all) = (vec![], vec![], vec![]); + popup.take().iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts, &mut bars)); + out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut all, &mut vec![])); + (texts, bars, all) + }; + let away = egui::Event::PointerMoved(egui::pos2(1.0, 1.0)); + run(&mut app, vec![away.clone()]); + let (_, _, all) = run(&mut app, vec![]); + let field = all.iter().find(|(s, ..)| s == "PNG").map(|(_, r, _)| r.center()).expect("the Format field shows PNG"); + let click = |pressed| egui::Event::PointerButton { pos: field, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(&mut app, vec![egui::Event::PointerMoved(field), click(true)]); + run(&mut app, vec![click(false)]); + run(&mut app, vec![away.clone()]); + let list_rect = || { + ctx.memory(|m| { + m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id)) + }) + }; + // A plug-in format that another test installs or removes changes the list's height, and the + // list is placed for its new height on the pass after. Read it once it keeps its rect. + let (mut texts, mut bars, mut list) = (vec![], vec![], None); + for _ in 0..12 { + (texts, bars, _) = run(&mut app, vec![]); + let now = list_rect(); + if now.is_some() && now == list { + break; + } + list = now; + } + let list = list.expect("the Format list is open"); + assert!(screen.contains_rect(list), "{case}: the list {list:?} is inside the window"); + let whole: Vec<&str> = labels + .iter() + .copied() + .filter(|name| { + texts.iter().any(|(s, r, clip)| s == name && list.contains_rect(*r) && r.top() >= clip.top() && r.bottom() <= clip.bottom()) + }) + .collect(); + assert_eq!(whole, labels, "{case}: every format shows whole in {list:?}"); + assert!(bars.is_empty(), "{case}: a list that shows every format draws no scroll bar: {bars:?}"); + } +} + #[test] fn svg_continues_in_svg_options() { let (mut app, written) = app(2); diff --git a/crates/ui-egui/src/dialogs/tests_save_for_web.rs b/crates/ui-egui/src/dialogs/tests_save_for_web.rs index a965977b14..63ed3e2ded 100644 --- a/crates/ui-egui/src/dialogs/tests_save_for_web.rs +++ b/crates/ui-egui/src/dialogs/tests_save_for_web.rs @@ -385,6 +385,8 @@ fn the_web_downloads_and_has_no_browser_preview() { let log = log.borrow().clone(); assert!(log[0].starts_with("download Untitled-1.html ") && log[1].starts_with("download Untitled-1.png "), "{log:?}"); assert!(app.run("file.saveForWeb.browser", json!({})).is_err()); + assert!(crate::menus::enabled(&app, "file.saveForWeb")); + assert!(!crate::menus::enabled(&app, "file.saveForWeb.browser"), "the command palette and menus show it disabled on the web"); } #[test] @@ -414,6 +416,19 @@ fn preview_in_browser_opens_the_page() { assert!(log.last().unwrap().starts_with("open file://") && log.last().unwrap().ends_with("Untitled-1.html"), "{log:?}"); } +/// A preview whose export fails opens nothing and removes the folder made for it. +#[test] +fn a_failed_browser_preview_removes_its_folder() { + let tmp = vectorcraft_testkit::temp_dir("sfw-browser-failed"); + save_for_web::TEST_TMP.set(Some(tmp.clone())); + let (mut app, log) = app(&tmp, false); + assert!(app.run("file.saveForWeb.browser", json!({"format": "bogus"})).is_err()); + assert!(!log.borrow().iter().any(|l| l.starts_with("open ")), "{:?}", log.borrow()); + let left: Vec<_> = + std::fs::read_dir(tmp.join("VectorCraft Save for Web")).map(|d| d.flatten().map(|e| e.file_name()).collect()).unwrap_or_default(); + assert!(left.is_empty(), "{left:?}"); +} + /// Each preview has its own folder: a second one, from another app or the same one, leaves the /// first page and its image as they were. #[test] diff --git a/crates/ui-egui/src/dialogs/three_point_arc_options.rs b/crates/ui-egui/src/dialogs/three_point_arc_options.rs new file mode 100644 index 0000000000..6d0eee96d1 --- /dev/null +++ b/crates/ui-egui/src/dialogs/three_point_arc_options.rs @@ -0,0 +1,84 @@ +//! Three-Point Arc Tool Options (double-click the Three-Point Arc tool, or `tool.options`): +//! Third Point Sets Direction, the tool's `direction` option. With it on, the third point gives the +//! direction the arc leaves an end in; with it off, the arc passes through the third point. OK +//! sets it with `tool.setOption {tool: "threePointArc", values: {direction}}`; it lasts across +//! tool switches and is saved with the preferences. `]` also switches it while an arc is drawn. + +use serde_json::{Map, Value, json}; +use vectorcraft_tools::three_point_arc::ID as TOOL; + +use super::{DialogSpec, run_and_close}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Three-Point Arc Tool Options. +pub const KIND: &str = "threePointArcOptions"; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 280.0, ..DialogSpec::FORM }; + +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 on = app.session.tool_options_of(TOOL).get("direction").and_then(Value::as_bool).unwrap_or(false); + let mut fields = Map::new(); + fields.insert("direction".into(), json!(on)); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + json!({ "dialog": KIND }) +} + +fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let on = d.bool("direction"); + if widgets::check(ui, tl!("Third Point Sets Direction"), on, true) { + d.fields.insert("direction".into(), json!(!on)); + } + false +} + +/// OK: set the tool's `direction`. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": { "direction": d.bool("direction") } })) +} + +#[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())) + } + + #[test] + fn double_clicking_the_tool_opens_its_options_and_ok_sets_the_direction() { + let mut app = app(); + assert_eq!(app.session.tool_options_of(TOOL)["direction"], json!(false)); + let r = app.run("tool.options", json!({"tool": TOOL})).unwrap(); + assert_eq!(r["dialog"], json!(KIND)); + let text = painted(&mut app); + for label in ["Three-Point Arc Tool Options", "Third Point Sets Direction", "OK", "Cancel"] { + assert!(text.contains(label), "{label} in {text}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + assert!(!d.bool("direction")); + d.fields.insert("direction".into(), json!(true)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.tool_options_of(TOOL)["direction"], json!(true)); + // It lasts while another tool is chosen, and the dialog opens on it again. + app.select_tool(TOOL); + app.select_tool("selection"); + app.run("tool.options", json!({"tool": TOOL})).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().bool("direction")); + } +} diff --git a/crates/ui-egui/src/dialogs/tools.rs b/crates/ui-egui/src/dialogs/tools.rs index 2a94ce4637..0ad9ed936c 100644 --- a/crates/ui-egui/src/dialogs/tools.rs +++ b/crates/ui-egui/src/dialogs/tools.rs @@ -124,6 +124,11 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) { } // Double-clicking a stop on the gradient annotator: its popover, next to the stop's chip. "gradientStop" => Dialog::new(kind, json!({"index": p.get("index").cloned().unwrap_or(json!(0)), "x": x, "y": y, "tab": "color"})), + // Image Trace's Ignore Color eyedropper updates the panel, not the document's paint. + "imageTraceIgnoreColor" => { + crate::panels::image_trace::apply_ignore_color_sample(app, &p); + return; + } // Brush Options › Key Color eyedropper: update the open dialog, do not replace it. "brushKeyColor" => { if let Some(c) = p.get("color") { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 3f6a956718..deaa95afea 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -126,6 +126,7 @@ Add to Selection Добавяне към селекцията Add to Swatches Добавяне към образци Add Used Colors Добавяне на използваните цветове + Add Selected Colors Добавяне на избраните цветове Additional Plug-ins Folder Допълнителна папка за плъгини Plug-in Instruction Budget Бюджет на инструкции за плъгини Additional Fonts Folder Допълнителна папка за шрифтове @@ -223,6 +224,10 @@ font-technology Variable Променливи Arc Дъга Arc Lower… Дъга надолу… Arc Tool Инструмент „Дъга“ + Three-Point Arc Tool Инструмент „Дъга през три точки“ + Three-Point Arc Дъга през три точки + Arc too large Дъгата е твърде голяма + Third Point Sets Direction Третата точка задава посоката Arc Upper… Дъга нагоре… Arch… Извиване… Arc… Дъга… @@ -627,6 +632,8 @@ font-technology Variable Променливи Contextual Task Bar Контекстна лента със задачи Pin Bar Position Закачане на позицията на лентата Reset Bar Position Нулиране на позицията на лентата + Bar Actions Действия на лентата + Reset Bar Actions Нулиране на действията на лентата Resize Преоразмеряване Contrast Контраст Control Контрол @@ -1630,6 +1637,10 @@ font-technology Variable Променливи Add Color Tool Инструмент „Добавяне на цвят“ Remove Color Tool Инструмент „Премахване на цвят“ Remove Color Премахване на цвят + Set As Base Color Задаване като основен цвят + Select Shade Избор на нюанс + Add New Color Добавяне на нов цвят + Set Current Color As Base Color Задаване на текущия цвят като основен Find the selected colors in the artwork Намиране на избраните цветове в илюстрацията Harmony Sets Набори от хармонии Height Височина @@ -1949,6 +1960,11 @@ font-technology Variable Променливи Knife Нож Knockout Group Група с изрязване Lab Lab + OKLCH Sliders Плъзгачи OKLCH + HSL Sliders Плъзгачи HSL + Chroma Хрома + The largest chroma sRGB holds at this lightness and hue Най-голямата хрома, която sRGB побира при тази светлина и този оттенък + OKLCH needs sRGB as the working RGB space OKLCH изисква sRGB като работно RGB пространство Lab Spot Colors: Спот цветове по Lab: Lab Values Стойности по Lab Landscape Пейзаж @@ -2010,6 +2026,7 @@ font-technology Variable Променливи Limit to Library: Ограничаване до библиотека: Limit: Ограничение: Line Линия + Line Arrow Линейна стрелка Line Art and Text Resolution: Разделителна способност на линеарна графика и текст: Line Breaks Паузи на редове Line Color Цвят на линията @@ -2762,6 +2779,11 @@ font-technology Variable Променливи Preserve Alpha Transparency Запазване на алфа прозрачността Preserve Appearance and Overprints Запазване на визията и надпечатите Preserve CMYK Numbers Запазване на CMYK стойностите + Preserve RGB Numbers Запазване на RGB стойностите + Device to Simulate: Устройство за симулиране: + Simulate Paper Color Симулиране на цвета на хартията + Simulate Black Ink Симулиране на черното мастило + Load… Зареди… Preserve Editing Capabilities Запазване на възможностите за редактиране Preserve editing capabilities Запазване на възможностите за редактиране Preserve Lightness Запазване на светлината @@ -3256,9 +3278,11 @@ digits Malayalam Малаялам Edit type set in fonts that aren't available? Да се редактира ли текст с шрифтове, които не са налични? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Показва номера на всяка отрязана част в каре в горния ѝ ляв ъгъл върху платното; когато е изключено, контурите на отрязаните части остават видими. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Цветът на контурите на потребителските и обектните отрязани части и на каретата с номерата им; автоматичните отрязани части използват по-блед нюанс на този цвят. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Новият текст получава този език, докато езикът в Настройка на документ е Английски: САЩ; текстът, който вече е в документа, запазва своя език. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Новият текст получава този език, докато езикът в Настройка на документ е Английски: САЩ и [Нормален стил на знак] не задава език; текстът, който вече е в документа, запазва своя език. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. В абзаците с включено Пренасяне на думи изброената дума се пренася само при въведените в нея тирета или никъде, ако няма такива, независимо от езика и регистъра ѝ. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. В настолната версия .wasm приставките в тази папка се зареждат при стартиране и когато щракнете върху ОК с нова папка тук, освен в Безопасен режим; уеб версията не ги зарежда. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. „Нормално“ запазва собствените ограничения на всеки плъгин; с „Голям“ филтър или команда на плъгин може да изпълни поне 250 милиона инструкции освен тези за входните си данни. Ограничението по време остава същото. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Колко инструкции може да използва всяко изпълнение на филтър за обекти от плъгин; „Голям“ позволява повече от „Нормално“ при същия лимит от 60 секунди. Тежките филтри запазват своя бюджет. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Първият избор на временен диск: Startup, None или път до папка; VectorCraft го запазва, но все още не използва временни дискове. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Вторият избор на временен диск: Startup, None или път до папка; VectorCraft го запазва, но все още не използва временни дискове. How light or dark the interface is. Колко светъл или тъмен е интерфейсът. @@ -3276,7 +3300,10 @@ digits Malayalam Малаялам The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Езикът на интерфейса; Автоматично използва езика на системата. Диалоговият прозорец сменя езика веднага щом изберете някой. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. „Анимирано мащабиране“ работи само докато това е включено; изключено, „Анимирано мащабиране“ е затъмнено и мащабирането не е анимирано. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Мащабирането с колелцето се плъзга плавно, а инструментът „Мащаб“ мащабира, докато плъзгате настрани или го задържите; изключено, той мащабира до областта, през която плъзнете. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. От следващото стартиране настолната версия показва платното чрез този вид графичен процесор; графиката винаги се рисува от централния процесор. „Автоматично“ предпочита интегрирания под Windows и macOS. Уеб версията не го използва. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. От следващото стартиране прозорецът показва всеки кадър, без да чака опресняването на дисплея, където графичният драйвер позволява, най-много 240 кадъра в секунда. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. От следващото стартиране настолната версия рисува с този вид графичен процесор; „Автоматично“ предпочита този, който управлява дисплея. Уеб версията не го използва. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. От следващото стартиране прозорецът показва кадрите, без да чака опресняването на дисплея, най-много 240 в секунда; изключено, темпото задава дисплеят. Режим на представяне, зададен при стартиране, има предимство. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Най-многото стъпки за отмяна, които всеки документ пази; по-малко число премахва най-старите стъпки, когато щракнете върху ОК. Стъпки може да отпаднат и по-рано, ако заемат твърде много памет. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Показва как рисунката се променя, докато плъзгате; изключено, контурите следват плъзгането, а рисунката се променя, когато отпуснете. Помощна линия от линийката винаги се движи, докато плъзгате. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Колко работни нишки рисуват рисунката; -1 използва с една по-малко от ядрата, които VectorCraft може да ползва, най-много 8, а 0 не използва нито една. Уеб версията никога не използва. @@ -3303,7 +3330,10 @@ digits Malayalam Малаялам VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft запазва този избор, но Копиране и Изрязване все още не използват формат на стария векторен клипборд. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. „Запазване на пътищата“ или „Запазване на визията и надпечатите“ за стария векторен клипборд; VectorCraft запазва избора, но все още не го използва. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. „Запазване на форматирането“ запазва стиловете на текст, копиран от текстов обект във VectorCraft, при поставяне в текстов обект; „Запазване като обикновен текст“ му дава стила на мястото, където попада. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Новият текст получава този език, докато езикът в Настройка на документ е Английски: САЩ и [Нормален стил на знак] не задава език; текстът, който вече е в документа, запазва своя език. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. „Показване на цялото черно като наситено черно“ показва чистото CMYK черно (само черно мастило на 100%) върху платното като RGB черно; „Показване на цялото черно точно“ го преобразува през работното CMYK пространство. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. „Изход на чисто черно като наситено черно“ рисува чистото CMYK черно като RGB черно в растерните RGB и черно-бели експорти и при „Печат като растерно изображение“; не променя векторните експорти, CMYK JPEG, TIFF и PSD и другия печат. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. На сензорен екран превключва към работното пространство за докосване; изключването на настройката или изчезването на сензорния екран връща работното пространство отпреди това. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Докосване с два пръста върху платното отменя, а в работното пространство за докосване превключва между инструментите за селекция и за рисуване; докосване с три пръста повтаря. Нито едното не действа в режим на презентация. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. В абзаците с включено Пренасяне на думи изброената дума се пренася само при въведените в нея тирета или никъде, ако няма такива, независимо от регистъра ѝ; корейските думи не получават тире, а думите на индийски езици не се пренасят вътре в група от знаци. Reset all preferences to their defaults? Да се нулират ли всички настройки до стойностите по подразбиране? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Стойностите по подразбиране се прилагат, когато щракнете върху ОК в Настройки. Отказ там запазва текущите ви настройки. @@ -4732,6 +4762,8 @@ axis Both И двете @msg `aspect` must be a number (%) `aspect` трябва да бъде число (%) @msg `at` must be [x, y] `at` трябва да бъде [x, y] @msg `color` must be a colour `color` трябва да бъде цвят +@msg `sliders` must be none, oklch or hsl `sliders` трябва да бъде none, oklch или hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH изисква sRGB като работно RGB пространство @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` трябва да бъде команда, чийто елемент от менюто отваря диалогов прозорец (вижте ui.menuDialog) @msg `freeform.points` must be an array `freeform.points` трябва да бъде масив @msg `freeform.lines` must be an array `freeform.lines` трябва да бъде масив @@ -5845,6 +5877,7 @@ lighting Light Светлина B5 B5 Bar Лента Barbed С кукички +arrowhead Feather Перо Baseline (Standard) Основна линия (стандартна) Baseline Optimized Оптимизирана основна линия Basic Основен @@ -7448,6 +7481,7 @@ breakText Glyphs Глифи Remove Strokes Премахване на щрихи Place Brush Art Поставяне на графика на четка Replace Brush Art Замяна на графика на четка + Replace Pattern Art Замяна на графика на мостра Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Щрихи използват тази четка. Да се приложи ли новата графика към тези щрихи, или те да останат както са и да се добави копие на четката с новата графика? Apply to Strokes Прилагане към щрихите Leave Strokes Оставяне на щрихите @@ -7863,6 +7897,25 @@ breakText Glyphs Глифи @msg A joint does not close by {gap} pt. Една връзка не се затваря с {gap} pt. @msg Two panels pass through each other. Два панела минават един през друг. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" + Orbit Lines Орбитални линии + Petal Garland Гирлянд от венчелистчета + Lattice Braid Решетъчна плетка + Facet Sweep Фасетен щрих + Artistic Brushes Художествени четки + Paint Боя + Flat Sweep Плосък замах + Dry Drag Сухо влачене + Loaded Stroke Плътен мазок + Fan Sweep Ветрилообразен замах +@msg `at` must be "start" or "end" `at` трябва да е "start" или "end" +@msg give exactly one of `through` and `toward` посочете точно едно от `through` и `toward` +@msg no arc fits these points: two are the same or all three lie on one line няма дъга през тези точки: две съвпадат или и трите лежат на една права +@msg give `at` only with `toward` задайте `at` само заедно с `toward` + Engraving Гравюра + Fine Hatching Фино щриховане + Dense Hatching Гъсто щриховане + Tapered Hatching Изтъняващо щриховане + Broken Hatching Прекъснато щриховане Image Brush Четки за изображения Soft Bloom Мек цъфтеж Halftone Field Полутоново поле diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 89c1fd0e89..fd89216bfc 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -797,6 +797,8 @@ Contextual Task Bar Kontekstna traka zadataka Pin Bar Position Položaj prikvačene trake Reset Bar Position Vrati položaj trake na početno + Bar Actions Radnje trake + Reset Bar Actions Vrati radnje trake na početno Resize Promijeni veličinu Tools Alati Toolbars Trake s alatima @@ -1506,6 +1508,10 @@ lighting Light Svjetlo Add Anchor Point Tool Alat za dodavanje sidrene tačke Anchor Point Tool Alat sidrena tačka Arc Tool Alat luk + Three-Point Arc Tool Alat luk kroz tri tačke + Three-Point Arc Luk kroz tri tačke + Arc too large Luk je prevelik + Third Point Sets Direction Treća tačka određuje smjer Area Graph Tool Alat za površinski grafikon Area Type Tool Alat za tekst u području Artboard Tool Alat radna ploča @@ -3026,6 +3032,11 @@ digits Malayalam Malajalam Place the pages with the placement again Ponovo postavi stranice s postavljanjem Placement: Postavljanje: Preserve CMYK Numbers Očuvaj CMYK brojeve + Preserve RGB Numbers Očuvaj RGB brojeve + Device to Simulate: Uređaj za simulaciju: + Simulate Paper Color Simuliraj boju papira + Simulate Black Ink Simuliraj crnu tintu + Load… Učitaj… Previous page Prethodna stranica Print Layers: Štampaj slojeve: Print Preset: Predložak štampanja: @@ -3102,6 +3113,10 @@ digits Malayalam Malajalam Add Color Tool Alat za dodavanje boje Remove Color Tool Alat za uklanjanje boje Remove Color Ukloni boju + Set As Base Color Postavi kao osnovnu boju + Select Shade Odaberi nijansu + Add New Color Dodaj novu boju + Set Current Color As Base Color Postavi trenutnu boju kao osnovnu Find the selected colors in the artwork Pronađi odabrane boje u crtežu Harmony Rules Pravila harmonije Keep this row's colors (exclude) Zadrži boje ovog reda (isključi) @@ -4329,6 +4344,7 @@ theme Appearance Izgled Add to Graphic Styles Dodaj u grafičke stilove Graphic Style Library Biblioteka grafičkih stilova Add Used Colors Dodaj korištene boje + Add Selected Colors Dodaj odabrane boje Delete Swatch Izbriši uzorak boje Duplicate Swatch Dupliciraj uzorak boje Merge Swatches Spoji uzorke boja @@ -4535,6 +4551,11 @@ axis Both Obje Image Slika Ink Tinta Lab Lab + OKLCH Sliders OKLCH klizači + HSL Sliders HSL klizači + Chroma Hroma + The largest chroma sRGB holds at this lightness and hue Najveća hroma koju sRGB obuhvata pri ovoj svjetloći i nijansi + OKLCH needs sRGB as the working RGB space OKLCH zahtijeva sRGB kao radni RGB prostor Medium Srednje Name Naziv None Ništa @@ -4747,9 +4768,10 @@ font-technology Variable Varijabilni Edit type set in fonts that aren't available? Urediti tekst u fontovima koji nisu dostupni? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Prikazuje broj svakog isječka u okviru u njegovom gornjem lijevom uglu na platnu; kada je isključeno, obrisi isječaka i dalje se prikazuju. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Boja obrisa korisničkih i objektnih isječaka i okvira s njihovim brojevima; automatski isječci koriste blijeđu nijansu te boje. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Novi tekst dobija ovaj jezik dok je jezik u Postavkama dokumenta Engleski: SAD; tekst koji je već u dokumentu zadržava svoj jezik. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. U pasusima s uključenom opcijom Rastavljaj riječi navedena riječ se rastavlja samo na crticama upisanim u nju, ili nigdje ako ih nema, bez obzira na jezik i velika ili mala slova. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. U desktop verziji .wasm dodaci iz ove mape učitavaju se pri pokretanju i kada kliknete U redu s novom mapom ovdje, osim u sigurnom načinu rada; web verzija ih ne učitava. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normalno zadržava vlastita ograničenja svakog dodatka; uz Veliko filter ili naredba dodatka može izvršiti najmanje 250 miliona instrukcija pored onih za svoj ulaz. Vremensko ograničenje ostaje isto. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Koliko instrukcija smije koristiti svako pokretanje filtera objekata iz dodatka; Veliko dopušta više od Normalno uz isto ograničenje od 60 sekundi. Teški filteri zadržavaju svoj budžet. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Prvi izbor radnog diska: Startup, None ili putanja do mape; VectorCraft ga sprema, ali još ne koristi radne diskove. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Drugi izbor radnog diska: Startup, None ili putanja do mape; VectorCraft ga sprema, ali još ne koristi radne diskove. How light or dark the interface is. Koliko je interfejs svijetao ili taman. @@ -4767,7 +4789,10 @@ font-technology Variable Varijabilni The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Jezik interfejsa; Automatski koristi jezik sistema. Dijalog mijenja jezik čim ga odaberete. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Animirano zumiranje radi samo dok je ovo uključeno; isključeno, Animirano zumiranje je zatamnjeno i zumiranje nije animirano. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Zumiranje točkićem glatko klizi, a Alat za zumiranje zumira dok vučete ustranu ili ga držite; isključeno, Alat za zumiranje zumira na područje preko kojeg prevučete. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Od sljedećeg pokretanja desktop verzija prikazuje platno preko ove vrste grafičkog procesora; crtež se u svakom slučaju iscrtava na CPU-u. Automatski daje prednost integrisanom na Windowsu i macOS-u. Web verzija ga ne koristi. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Od sljedećeg pokretanja prozor prikazuje svaki kadar bez čekanja na osvježavanje ekrana gdje grafički drajver to dozvoljava, najviše 240 kadrova u sekundi. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Od sljedećeg pokretanja desktop verzija crta ovom vrstom grafičkog procesora; Automatski daje prednost onom koji pokreće ekran. Web verzija ga ne koristi. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Od sljedećeg pokretanja prozor prikazuje kadrove bez čekanja na osvježavanje ekrana, najviše 240 u sekundi; isključeno, ritam određuje ekran. Način prikaza zadan pri pokretanju ima prednost. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Najveći broj koraka poništavanja koje svaki dokument čuva; manji broj uklanja najstarije korake kada kliknete U redu. Koraci mogu nestati i ranije kada zauzimaju previše memorije. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Prikazuje kako se crtež mijenja dok vučete; isključeno, obrisi prate povlačenje, a crtež se mijenja kada pustite. Vodilja s ravnala se uvijek pomiče dok vučete. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Koliko radnih niti crta crtež; -1 koristi jednu manje od jezgri koje VectorCraft smije koristiti, najviše 8, a 0 nijednu. Web verzija nikad ne koristi nijednu. @@ -4794,6 +4819,10 @@ font-technology Variable Varijabilni VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft čuva ovaj izbor, ali Kopiraj i Izreži još ne koriste format naslijeđenog vektorskog međuspremnika. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Očuvaj putanje ili Očuvaj izgled i pretiske za naslijeđeni vektorski međuspremnik; VectorCraft čuva izbor, ali ga još ne koristi. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. Zadrži oblikovanje čuva stilove teksta kopiranog iz tekstualnog objekta u VectorCraftu kada se zalijepi u tekstualni objekt; Zadrži običan tekst daje mu stil mjesta na koje dospije. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. Prikaži sve crne kao bogatu crnu prikazuje čistu CMYK crnu (samo crnu boju na 100%) na platnu kao RGB crnu; Prikaži sve crne tačno je pretvara kroz radni CMYK prostor. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Izlaz svih crnih kao bogata crna crta čistu CMYK crnu kao RGB crnu u RGB rasterskim izvozima i izvozima u nijansama sive te uz Štampaj kao bitmapu; ne mijenja vektorske izvoze, CMYK JPEG, TIFF i PSD niti ostalu štampu. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Na ekranu osjetljivom na dodir prelazi u radni prostor za dodir; isključivanje postavke ili gubitak ekrana osjetljivog na dodir vraća radni prostor iz kojeg je prešao. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Dodir s dva prsta na platnu poništava, a u radnom prostoru za dodir prebacuje između alata za odabir i crtanje; dodir s tri prsta ponavlja. Nijedan ne radi u načinu prezentacije. New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Novi tekst dobija ovaj jezik dok je jezik u Postavkama dokumenta Engleski: SAD i [Normalni stil znakova] ne postavlja jezik; tekst koji je već u dokumentu zadržava svoj jezik. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. U pasusima s uključenom opcijom Rastavljaj riječi navedena riječ se rastavlja samo na crticama upisanim u nju, ili nigdje ako ih nema, bez obzira na velika ili mala slova; korejske riječi ne dobijaju crticu, a riječi na indijskim jezicima ne rastavljaju se unutar skupine znakova. Reset all preferences to their defaults? Vratiti sve postavke na zadane vrijednosti? @@ -5181,6 +5210,8 @@ imageTrace Outline Obris @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` mora biti grayscale, rgb, hsb, cmyk ili websafe @msg `view` must be wheel or box `view` mora biti wheel ili box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` mora biti hue, saturation, brightness, red, green ili blue +@msg `sliders` must be none, oklch or hsl `sliders` mora biti none, oklch ili hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH zahtijeva sRGB kao radni RGB prostor @msg `{k}` must be [x, y] `{k}` mora biti [x, y] @msg `{name}` has no options `{name}` nema opcija @msg `{name}` is a built-in workspace; choose another name `{name}` je ugrađeni radni prostor; odaberite drugi naziv @@ -6050,6 +6081,7 @@ imageTrace Outline Obris Arrow Strelica Arrow (open) Strelica (otvorena) Barbed Bodljikavo +arrowhead Feather Pero Half Arrow (left) Polustrelica (lijevo) Half Arrow (right) Polustrelica (desno) Concave Konkavno @@ -6077,6 +6109,7 @@ imageTrace Outline Obris Kite Zmaj Triangle to Bar Trougao u traku Oval Oval + Line Arrow Linijska strelica Complementary Komplementarne Complementary 2 Komplementarne 2 Split Complementary Podijeljene komplementarne @@ -7497,6 +7530,7 @@ shape Open Otvoren Remove Strokes Ukloni poteze Place Brush Art Postavi crtež četkice Replace Brush Art Zamijeni crtež četkice + Replace Pattern Art Zamijeni crtež uzorka Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Potezi koriste ovu četkicu. Primijeniti novi crtež na te poteze ili ih ostaviti kakvi jesu i dodati kopiju četkice s novim crtežom? Apply to Strokes Primijeni na poteze Leave Strokes Ostavi poteze @@ -7918,6 +7952,25 @@ shape Open Otvoren @msg A joint does not close by {gap} pt. Spoj se ne zatvara za {gap} pt. @msg Two panels pass through each other. Dva panela prolaze jedan kroz drugi. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" + Orbit Lines Orbitalne linije + Petal Garland Vijenac od latica + Lattice Braid Rešetkasti preplet + Facet Sweep Fasetni potez + Artistic Brushes Umjetničke četke + Paint Boja + Flat Sweep Ravni potez + Dry Drag Suhi potez + Loaded Stroke Bogati potez + Fan Sweep Lepezasti potez +@msg `at` must be "start" or "end" `at` mora biti "start" ili "end" +@msg give exactly one of `through` and `toward` navedite tačno jedno od `through` i `toward` +@msg no arc fits these points: two are the same or all three lie on one line nijedan luk ne odgovara ovim tačkama: dvije su iste ili sve tri leže na jednoj pravoj +@msg give `at` only with `toward` navedite `at` samo uz `toward` + Engraving Gravura + Fine Hatching Fino šrafiranje + Dense Hatching Gusto šrafiranje + Tapered Hatching Suženo šrafiranje + Broken Hatching Isprekidano šrafiranje Image Brush Slikovni kistovi Soft Bloom Meko cvjetanje Halftone Field Polutonsko polje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 8d9e51facd..599988d3fc 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -221,6 +221,7 @@ Add to Symbols Afegeix als símbols Add to the Current Shortcuts Afegeix a les dreceres actuals Add Used Colors Afegeix els colors utilitzats + Add Selected Colors Afegeix els colors seleccionats Additional Fonts Folder Carpeta addicional de tipus de lletra Additional Plug-ins Folder Carpeta addicional de complements Plug-in Instruction Budget Pressupost d’instruccions dels complements @@ -344,6 +345,10 @@ antiAlias Sharp Nítid Arc Lower… Arc inferior… Arc Segment Tool Options Opcions de l’eina de segment d’arc Arc Tool Eina d’arc + Three-Point Arc Tool Eina d’arc per tres punts + Three-Point Arc Arc per tres punts + Arc too large Arc massa gran + Third Point Sets Direction El tercer punt indica la direcció Arc Upper… Arc superior… Arch… Arqueja… Arc… Arc… @@ -456,6 +461,8 @@ antiAlias Sharp Nítid Bar Barra Bar Graph Tool Eina de gràfic de barres Barbed Amb pues +arrowhead Feather Ploma +arrowhead Target Diana Bas Relief Baix relleu Bas Relief… Baix relleu… Base Along: Base al llarg de: @@ -2195,6 +2202,10 @@ digits Malayalam Malaiàlam Add Color Tool Eina Afegeix color Remove Color Tool Eina Elimina color Remove Color Elimina el color + Set As Base Color Defineix com a color base + Select Shade Selecciona el to + Add New Color Afegeix un color nou + Set Current Color As Base Color Defineix el color actual com a color base Find the selected colors in the artwork Troba els colors seleccionats a l’obra Harmony Sets Conjunts d’harmonia HDTV 1080p HDTV 1080p @@ -2488,6 +2499,11 @@ digits Malayalam Malaiàlam Knife Ganivet Knockout Group Grup knockout Lab Lab + OKLCH Sliders Controls lliscants OKLCH + HSL Sliders Controls lliscants HSL + Chroma Croma + The largest chroma sRGB holds at this lightness and hue El croma més gran que sRGB admet amb aquesta lluminositat i aquest to + OKLCH needs sRGB as the working RGB space OKLCH necessita sRGB com a espai RGB de treball Lab Spot Colors Colors directes Lab Lab Spot Colors: Colors directes Lab: Lab Values Valors Lab @@ -2606,6 +2622,7 @@ digits Malayalam Malaiàlam Limit: Límit: Limited Limitat Line Línia + Line Arrow Fletxa de línies Line Art Art lineal Line Art and Text Resolution: Resolució de l’art lineal i del text: Line Breaks Salts de línia @@ -3565,6 +3582,11 @@ digits Malayalam Malaiàlam Preserve Appearance Conserva l’aparença Preserve Appearance and Overprints Conserva l’aparença i les sobrempressions Preserve CMYK Numbers Conserva els valors CMYK + Preserve RGB Numbers Conserva els valors RGB + Device to Simulate: Dispositiu que se simula: + Simulate Paper Color Simula el color del paper + Simulate Black Ink Simula la tinta negra + Load… Carrega… Preserve Editing Capabilities Conserva les capacitats d’edició Preserve editing capabilities Conserva les capacitats d’edició Preserve Lightness Conserva la lluminositat @@ -3932,6 +3954,8 @@ digits Malayalam Malaiàlam Reset all Revolve settings to their defaults. Restableix tots els paràmetres de revolució als valors predeterminats. Reset Automation Restableix Automation Reset Bar Position Restableix la posició de la barra + Bar Actions Accions de la barra + Reset Bar Actions Restableix les accions de la barra Reset Bounding Box Restableix el quadre delimitador Rotate Bounding Box Gira el quadre delimitador Rotate Bounding Box… Gira el quadre delimitador… @@ -4112,9 +4136,11 @@ digits Malayalam Malaiàlam Edit type set in fonts that aren't available? Voleu editar el text en tipus de lletra que no estan disponibles? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Mostra al llenç el número de cada tall en un requadre a la seva cantonada superior esquerra; si està desactivat, els contorns dels talls continuen visibles. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. El color dels contorns dels talls d’usuari i d’objecte i dels requadres amb el seu número; els talls automàtics fan servir un to més apagat d’aquest color. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. El text nou pren aquest idioma mentre l’idioma de Configuració del document sigui Anglès: EUA; el text que ja és en un document conserva el seu idioma. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. El text nou pren aquest idioma mentre l’idioma de Configuració del document sigui Anglès: EUA i [Estil de caràcter normal] no en defineixi cap; el text que ja és en un document conserva el seu idioma. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. En els paràgrafs amb Particiona activat, una paraula de la llista es parteix només als guionets que s’hi han escrit, o enlloc si no en té, sigui quin sigui el seu idioma o l’ús de majúscules. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. A la versió d’escriptori, els complements .wasm d’aquesta carpeta es carreguen en iniciar i quan feu clic a D’acord amb una carpeta nova aquí, excepte en Mode segur; la versió web no els carrega. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normal manté els límits propis de cada complement; amb Gran, un filtre o una ordre d’un complement pot executar com a mínim 250 milions d’instruccions a més de les de la seva entrada. El límit de temps no canvia. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Quantes instruccions pot fer servir cada execució d’un filtre d’objectes d’un complement; Gran en permet més que Normal amb el mateix límit de 60 segons. Els filtres pesants conserven el seu pressupost. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. La primera opció de disc d’intercanvi: Startup, None o el camí d’una carpeta; VectorCraft la desa, però encara no fa servir discs d’intercanvi. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. La segona opció de disc d’intercanvi: Startup, None o el camí d’una carpeta; VectorCraft la desa, però encara no fa servir discs d’intercanvi. How light or dark the interface is. Com de clara o fosca és la interfície. @@ -4132,7 +4158,10 @@ digits Malayalam Malaiàlam The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. La llengua de la interfície; Automàtic fa servir la llengua del sistema. El diàleg canvia de llengua tan bon punt en trieu una. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. El Zoom animat només funciona mentre això està activat; desactivat, el Zoom animat apareix atenuat i el zoom no s’anima. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. El zoom amb la roda llisca suaument, i l’Eina de zoom fa zoom mentre arrossegueu de costat o la manteniu premuda; desactivat, l’Eina de zoom fa zoom a l’àrea que arrossegueu. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. A partir del pròxim inici, la versió d’escriptori mostra el llenç a través d’aquest tipus de processador gràfic; la il·lustració sempre es dibuixa a la CPU. Automàtic prefereix l’integrat a Windows i macOS. La versió web no l’utilitza. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. A partir del pròxim inici, la finestra mostra cada fotograma sense esperar el refresc de la pantalla quan el controlador gràfic ho permet, com a màxim 240 fotogrames per segon. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. A partir del pròxim inici, la versió d’escriptori dibuixa amb aquest tipus de processador gràfic; Automàtic prefereix el que controla la pantalla. La versió web no l’utilitza. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. A partir del pròxim inici, la finestra mostra els fotogrames sense esperar que la pantalla es refresqui, com a màxim 240 per segon; desactivat, la pantalla marca el ritme. Un mode de presentació definit en iniciar té prioritat. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. El màxim de passos de desfer que conserva cada document; un nombre més baix elimina els passos més antics quan feu clic a D’acord. Els passos també poden desaparèixer abans si ocupen massa memòria. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Mostra com canvia l’art mentre arrossegueu; desactivat, els contorns segueixen l’arrossegament i l’art canvia quan deixeu anar. Una guia de regle sempre es mou mentre arrossegueu. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Quants fils de treball dibuixen l’art; -1 en fa servir un menys que els nuclis que VectorCraft pot usar, com a màxim 8, i 0 cap. La versió web no en fa servir mai cap. @@ -4159,7 +4188,10 @@ digits Malayalam Malaiàlam VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft desa aquesta opció, però Copia i Retalla encara no fan servir cap format de porta-retalls vectorial heredat. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Conserva els traçats o Conserva l’aparença i les sobrempressions per al porta-retalls vectorial heredat; VectorCraft desa l’opció però encara no la fa servir. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. Conserva el format manté els estils del text copiat d’un objecte de text de VectorCraft quan s’enganxa en un objecte de text; Conserva el text sense format li dona l’estil del lloc on va a parar. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. El text nou pren aquest idioma mentre l’idioma de Configuració del document sigui Anglès: EUA i [Estil de caràcter normal] no en defineixi cap; el text que ja és en un document conserva el seu idioma. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. Mostra tots els negres com a negre ric mostra el negre CMYK pur (només tinta negra al 100%) com a negre RGB al llenç; Mostra tots els negres amb precisió el converteix a través de l’espai CMYK de treball. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Genera tots els negres com a negre ric dibuixa el negre CMYK pur com a negre RGB a les exportacions ràster RGB i en escala de grisos i amb Imprimeix com a mapa de bits; no canvia les exportacions vectorials, els JPEG, TIFF i PSD CMYK ni la resta d’impressions. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. En una pantalla tàctil, canvia a l’espai de treball tàctil; si es desactiva o es perd la pantalla tàctil, torna a l’espai de treball d’abans del canvi. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Un toc amb dos dits al llenç desfà o, a l’espai de treball tàctil, alterna entre les eines de selecció i de dibuix, i un toc amb tres dits refà; cap dels dos funciona en el mode de presentació. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. En els paràgrafs amb Particiona activat, una paraula de la llista es parteix només als guionets que s’hi han escrit, o enlloc si no en té, sigui quin sigui l’ús de majúscules; les paraules coreanes no prenen guionet, i les paraules en llengües índies no es parteixen dins d’un grup de caràcters. Reset all preferences to their defaults? Voleu restablir totes les preferències als valors predeterminats? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Els valors predeterminats s’apliquen quan feu clic a D’acord a Preferències. Cancel·la allà conserva les preferències actuals. @@ -6121,6 +6153,8 @@ digits Malayalam Malaiàlam @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` ha de ser grayscale, rgb, hsb, cmyk o websafe @msg `view` must be wheel or box `view` ha de ser wheel o box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` ha de ser hue, saturation, brightness, red, green o blue +@msg `sliders` must be none, oklch or hsl `sliders` ha de ser none, oklch o hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH necessita sRGB com a espai RGB de treball @msg `name` is empty `name` és buit @msg `newName` is empty `newName` és buit @msg `pathfinder` must be an object `pathfinder` ha de ser un objecte @@ -6780,6 +6814,10 @@ liquify-list-end {0}, {1} {0} i {1} @msg a guide has no curvature circle una guia no té cercle de curvatura @msg the circle that matches the path there would reach past the canvas el cercle que coincideix amb el traçat en aquest punt sortiria del llenç @msg no circle passes through these points: two are the same or all three lie on one line cap cercle no passa per aquests punts: dos són iguals o tots tres són en una mateixa recta +@msg `at` must be "start" or "end" `at` ha de ser "start" o "end" +@msg give exactly one of `through` and `toward` indiqueu exactament un de `through` i `toward` +@msg no arc fits these points: two are the same or all three lie on one line cap arc no s’ajusta a aquests punts: dos són iguals o tots tres són en una mateixa recta +@msg give `at` only with `toward` indiqueu `at` només amb `toward` @msg no app to open files here aquí no hi ha cap aplicació per obrir fitxers @msg no artboard no hi ha tauler @msg no artboard {i} (0-based; the document has {_1}) no hi ha el tauler {i} (basat en 0; el document en té {_1}) @@ -6838,6 +6876,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg no native format no hi ha format natiu @msg no pages no hi ha pàgines @msg no pattern `{name}` no hi ha el motiu `{name}` +@msg art painted with `{name}` can't be its tile un art pintat amb `{name}` no pot ser el seu mosaic @msg no pattern swatch `{name}` no hi ha la mostra de motiu `{name}` @msg no perspective grid preset named `{name}` no hi ha cap preajust de quadrícula de perspectiva anomenat `{name}` @msg no plug-in {0} is installed no hi ha instal·lat el complement {0} @@ -8314,6 +8353,7 @@ breakText Glyphs Glifs Remove Strokes Elimina els traços Place Brush Art Col·loca l’art del pinzell Replace Brush Art Substitueix l’art del pinzell + Replace Pattern Art Substitueix l’art del motiu Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Hi ha traços que fan servir aquest pinzell. Voleu aplicar l’art nou a aquests traços, o deixar-los com estan i afegir una còpia del pinzell amb l’art nou? Apply to Strokes Aplica als traços Leave Strokes Deixa els traços @@ -8893,6 +8933,21 @@ breakText Glyphs Glifs @msg A joint does not close by {gap} pt. Una unió no es tanca per {gap} pt. @msg Two panels pass through each other. Dos panells es travessen l’un a l’altre. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" + Orbit Lines Línies orbitals + Petal Garland Garlanda de pètals + Lattice Braid Trena reticular + Facet Sweep Traç facetat + Artistic Brushes Pinzells artístics + Paint Pintura + Flat Sweep Traç pla + Dry Drag Arrossegament sec + Loaded Stroke Traç carregat + Fan Sweep Traç en ventall + Engraving Gravat + Fine Hatching Ratllat fi + Dense Hatching Ratllat dens + Tapered Hatching Ratllat afilat + Broken Hatching Ratllat interromput Image Brush Pinzells d'imatge Soft Bloom Floració suau Halftone Field Camp de semitons diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 650dfb646e..c0c143f893 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -809,6 +809,8 @@ Contextual Task Bar Kontextový panel úloh Pin Bar Position Připnout polohu panelu Reset Bar Position Obnovit polohu panelu + Bar Actions Akce panelu + Reset Bar Actions Obnovit akce panelu Resize Změnit velikost Tools Nástroje Toolbars Panely nástrojů @@ -1531,6 +1533,10 @@ lighting Light Světlo Add Anchor Point Tool Nástroj Přidat kotevní bod Anchor Point Tool Nástroj Kotevní bod Arc Tool Nástroj Oblouk + Three-Point Arc Tool Nástroj Oblouk třemi body + Three-Point Arc Oblouk třemi body + Arc too large Oblouk je příliš velký + Third Point Sets Direction Třetí bod určuje směr Area Graph Tool Nástroj Plošný graf Area Type Tool Nástroj Text v oblasti Artboard Tool Nástroj Pracovní plocha @@ -3108,6 +3114,11 @@ digits Malayalam Malajálamské Place the pages with the placement again Znovu rozmístit stránky podle umístění Placement: Umístění: Preserve CMYK Numbers Zachovat hodnoty CMYK + Preserve RGB Numbers Zachovat hodnoty RGB + Device to Simulate: Simulované zařízení: + Simulate Paper Color Simulovat barvu papíru + Simulate Black Ink Simulovat černou barvu + Load… Načíst… Previous page Předchozí stránka Print Layers: Tisknout vrstvy: Print Preset: Přednastavení tisku: @@ -3185,6 +3196,10 @@ digits Malayalam Malajálamské Add Color Tool Nástroj Přidat barvu Remove Color Tool Nástroj Odstranit barvu Remove Color Odstranit barvu + Set As Base Color Nastavit jako základní barvu + Select Shade Vybrat odstín + Add New Color Přidat novou barvu + Set Current Color As Base Color Nastavit aktuální barvu jako základní Find the selected colors in the artwork Najít vybrané barvy v kresbě Harmony Rules Pravidla harmonie Keep this row's colors (exclude) Ponechat barvy tohoto řádku (vyloučit) @@ -4438,6 +4453,7 @@ theme Appearance Motiv Add to Graphic Styles Přidat do grafických stylů Graphic Style Library Knihovna grafických stylů Add Used Colors Přidat použité barvy + Add Selected Colors Přidat vybrané barvy Delete Swatch Odstranit položku vzorníku Duplicate Swatch Duplikovat položku vzorníku Merge Swatches Sloučit položky vzorníku @@ -4644,6 +4660,11 @@ axis Both Obě Image Obraz Ink Inkoust Lab Lab + OKLCH Sliders Posuvníky OKLCH + HSL Sliders Posuvníky HSL + Chroma Chroma + The largest chroma sRGB holds at this lightness and hue Největší chroma, kterou sRGB obsáhne při této světlosti a odstínu + OKLCH needs sRGB as the working RGB space OKLCH vyžaduje sRGB jako pracovní prostor RGB Medium Střední Name Název None Žádné @@ -4856,9 +4877,10 @@ font-technology Variable Variabilní Edit type set in fonts that aren't available? Upravit text v písmech, která nejsou k dispozici? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Zobrazí na plátně číslo každého řezu v rámečku v jeho levém horním rohu; když je vypnuto, obrysy řezů zůstanou zobrazené. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Barva obrysů uživatelských a objektových řezů a rámečků s jejich čísly; automatické řezy používají tlumenější odstín této barvy. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Nový text dostane tento jazyk, dokud je jazyk v Nastavení dokumentu Angličtina: USA; text, který už v dokumentu je, si ponechá svůj jazyk. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. V odstavcích se zapnutou volbou Dělit slova se uvedené slovo dělí jen u spojovníků, které v něm napíšete, nebo nikde, pokud žádné nemá, bez ohledu na jazyk a velikost písmen. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. V desktopové verzi se zásuvné moduly .wasm z této složky načtou při spuštění a po klepnutí na OK s novou složkou zde, kromě nouzového režimu; webová verze je nenačítá. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normální zachová vlastní limity každého zásuvného modulu; s volbou Velké může filtr nebo příkaz zásuvného modulu provést nejméně 250 milionů instrukcí navíc k těm pro svůj vstup. Časový limit zůstává stejný. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Kolik instrukcí smí použít každé spuštění filtru objektů ze zásuvného modulu; Velké povoluje víc než Normální při stejném limitu 60 sekund. Náročné filtry si ponechají vlastní rozpočet. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. První volba odkládacího disku: Startup, None nebo cesta ke složce; VectorCraft ji uloží, ale odkládací disky zatím nepoužívá. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Druhá volba odkládacího disku: Startup, None nebo cesta ke složce; VectorCraft ji uloží, ale odkládací disky zatím nepoužívá. How light or dark the interface is. Jak světlé nebo tmavé je rozhraní. @@ -4876,7 +4898,10 @@ font-technology Variable Variabilní The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Jazyk rozhraní; Automaticky použije jazyk systému. Dialog přepne jazyk, jakmile nějaký zvolíte. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Animované zvětšení funguje, jen když je toto zapnuto; při vypnutí je Animované zvětšení zašedlé a zvětšování není animované. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Zvětšení kolečkem plynule dojede a Nástroj Lupa zvětšuje, když táhnete do strany nebo ho podržíte; při vypnutí Nástroj Lupa zvětší oblast, přes kterou táhnete. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Od příštího spuštění zobrazuje desktopová verze plátno přes tento druh grafického procesoru; kresba se v každém případě vykresluje na CPU. Automaticky dává ve Windows a macOS přednost integrovanému. Webová verze ho nepoužívá. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Od příštího spuštění okno zobrazuje každý snímek bez čekání na obnovení displeje, kde to grafický ovladač dovolí, nejvýše 240 snímků za sekundu. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Od příštího spuštění kreslí desktopová verze tímto druhem grafického procesoru; Automaticky dává přednost tomu, který řídí displej. Webová verze ho nepoužívá. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Od příštího spuštění okno zobrazuje snímky bez čekání na obnovení displeje, nejvýše 240 za sekundu; vypnuto, tempo určuje displej. Režim zobrazení nastavený při spuštění má přednost. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Nejvyšší počet kroků zpět, které si každý dokument ponechá; nižší číslo po klepnutí na OK odstraní nejstarší kroky. Kroky mohou zmizet i dříve, když zabírají příliš paměti. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Ukazuje, jak se kresba mění, zatímco táhnete; při vypnutí sledují tažení obrysy a kresba se změní, až pustíte. Vodítko z pravítka se při tažení pohybuje vždy. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Kolik pracovních vláken kreslí kresbu; -1 použije o jedno méně, než je jader, která VectorCraft smí použít, nejvýše 8, a 0 žádné. Webová verze nepoužívá žádné. @@ -4903,6 +4928,10 @@ font-technology Variable Variabilní VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft tuto volbu uloží, ale Kopírovat a Vyjmout zatím nepoužívají formát starší vektorové schránky. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Zachovat cesty nebo Zachovat vzhled a přetisky pro starší vektorovou schránku; VectorCraft volbu uloží, ale zatím ji nepoužívá. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. Zachovat formátování ponechá styly textu zkopírovaného z textového objektu ve VectorCraftu při vložení do textového objektu; Zachovat prostý text mu dá styl místa, kam se vloží. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. Volba „Zobrazovat všechny černé jako sytou černou“ zobrazí na plátně čistou černou CMYK (jen černou barvu na 100 %) jako černou RGB; volba „Zobrazovat všechny černé přesně“ ji převede přes pracovní prostor CMYK. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Volba „Ve výstupu všechny černé jako sytou černou“ vykreslí čistou černou CMYK jako černou RGB v rastrových exportech RGB a ve stupních šedi a při Tisknout jako bitmapu; nemění vektorové exporty, CMYK JPEG, TIFF a PSD ani jiný tisk. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Na dotykové obrazovce přepne do dotykového pracovního prostoru; vypnutí volby nebo ztráta dotykové obrazovky vrátí pracovní prostor, ze kterého přepnul. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Klepnutí dvěma prsty na plátno vrátí krok zpět, v dotykovém pracovním prostoru přepne mezi nástroji pro výběr a kreslení; klepnutí třemi prsty krok zopakuje. V režimu prezentace nefunguje ani jedno. New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Nový text dostane tento jazyk, dokud je jazyk v Nastavení dokumentu Angličtina: USA a [Normální styl znaků] žádný jazyk nenastavuje; text, který už v dokumentu je, si ponechá svůj jazyk. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. V odstavcích se zapnutou volbou Dělit slova se uvedené slovo dělí jen u spojovníků, které v něm napíšete, nebo nikde, pokud žádné nemá, bez ohledu na velikost písmen; korejská slova spojovník nedostanou a slova v indických jazycích se nedělí uvnitř skupiny znaků. Reset all preferences to their defaults? Obnovit všechny předvolby na výchozí hodnoty? @@ -5476,6 +5505,8 @@ liquify-list-end {0}, {1} {0} a {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` musí být grayscale, rgb, hsb, cmyk nebo websafe @msg `view` must be wheel or box `view` musí být wheel nebo box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` musí být hue, saturation, brightness, red, green nebo blue +@msg `sliders` must be none, oklch or hsl `sliders` musí být none, oklch nebo hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH vyžaduje sRGB jako pracovní prostor RGB @msg `{k}` must be [x, y] `{k}` musí být [x, y] @msg `{name}` has no options `{name}` nemá žádné možnosti @msg `{name}` is a built-in workspace; choose another name `{name}` je vestavěný pracovní prostor; zvolte jiný název @@ -5669,6 +5700,10 @@ liquify-list-end {0}, {1} {0} a {1} @msg a guide has no curvature circle vodítko nemá kružnici křivosti @msg the circle that matches the path there would reach past the canvas kružnice odpovídající cestě v tomto místě by přesáhla plátno @msg no circle passes through these points: two are the same or all three lie on one line těmito body neprochází žádná kružnice: dva jsou stejné nebo všechny tři leží na jedné přímce +@msg `at` must be "start" or "end" `at` musí být "start" nebo "end" +@msg give exactly one of `through` and `toward` zadejte právě jeden z parametrů `through` a `toward` +@msg no arc fits these points: two are the same or all three lie on one line těmto bodům neodpovídá žádný oblouk: dva jsou stejné nebo všechny tři leží na jedné přímce +@msg give `at` only with `toward` parametr `at` zadejte jen s `toward` @msg no app to open files here zde chybí aplikace pro otevírání souborů @msg no artboard žádná pracovní plocha @msg no artboard {i} (0-based; the document has {_1}) pracovní plocha {i} neexistuje (číslováno od 0; dokument jich má {_1}) @@ -5714,6 +5749,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg no native format chybí nativní formát @msg no pages žádné stránky @msg no pattern `{name}` vzorek `{name}` neexistuje +@msg art painted with `{name}` can't be its tile kresba vybarvená vzorkem `{name}` nemůže být jeho dlaždicí @msg no perspective grid preset named `{name}` přednastavení perspektivní mřížky s názvem `{name}` neexistuje @msg no plug-in {0} is installed zásuvný modul {0} není nainstalován @msg no plug-in {id} is installed zásuvný modul {id} není nainstalován @@ -6501,6 +6537,7 @@ variable-list-end {0}, {1} {0} a {1} Arrow Šipka Arrow (open) Šipka (otevřená) Barbed S protihroty +arrowhead Feather Pírko Half Arrow (left) Poloviční šipka (vlevo) Half Arrow (right) Poloviční šipka (vpravo) Concave Vkleslá @@ -6528,6 +6565,7 @@ variable-list-end {0}, {1} {0} a {1} Kite Deltoid Triangle to Bar Trojúhelník k příčce Oval Ovál + Line Arrow Čárová šipka # Colour harmony rules (Color Guide, Recolor Artwork, Color Themes) Complementary Komplementární Complementary 2 Komplementární 2 @@ -8296,6 +8334,7 @@ breakText Glyphs Glyfy Remove Strokes Odebrat tahy Place Brush Art Umístit kresbu štětce Replace Brush Art Nahradit kresbu štětce + Replace Pattern Art Nahradit kresbu vzorku Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Tahy používají tento štětec. Použít novou kresbu na tyto tahy, nebo je ponechat beze změny a přidat kopii štětce s novou kresbou? Apply to Strokes Použít na tahy Leave Strokes Ponechat tahy @@ -10718,6 +10757,21 @@ breakText Glyphs Glyfy @msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu. @msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, panty: {hinges}, chyby: {errors}, upozornění: {warnings} + Orbit Lines Orbitální čáry + Petal Garland Okvětní girlanda + Lattice Braid Mřížkový cop + Facet Sweep Fazetový tah + Artistic Brushes Umělecké štětce + Paint Malba + Flat Sweep Plochý tah + Dry Drag Suchý tah + Loaded Stroke Sytý tah + Fan Sweep Vějířový tah + Engraving Rytina + Fine Hatching Jemné šrafování + Dense Hatching Husté šrafování + Tapered Hatching Zúžené šrafování + Broken Hatching Přerušované šrafování Image Brush Obrazové štětce Soft Bloom Jemný květ Halftone Field Polotónové pole diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 6bb9e6b405..7e22ccf3d7 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3507,6 +3507,8 @@ liquify-list-end {0}, {1} {0} og {1} Contextual Task Bar Kontekstuel opgavelinje Pin Bar Position Fastgør linjens placering Reset Bar Position Nulstil linjens placering + Bar Actions Linjens handlinger + Reset Bar Actions Nulstil linjens handlinger Tools Værktøjer Toolbars Værktøjslinjer Advanced Avanceret @@ -4184,6 +4186,10 @@ lighting Light Lys Add Anchor Point Tool Tilføj ankerpunkt-værktøj Anchor Point Tool Ankerpunktværktøj Arc Tool Bueværktøj + Three-Point Arc Tool Værktøj til bue gennem tre punkter + Three-Point Arc Bue gennem tre punkter + Arc too large Buen er for stor + Third Point Sets Direction Tredje punkt angiver retningen Area Graph Tool Områdediagramværktøj Area Type Tool Områdetekstværktøj Artboard Tool Tegnebrætværktøj @@ -5632,6 +5638,11 @@ digits Malayalam Malayalam Place the pages with the placement again Placér siderne igen med placeringen Placement: Placering: Preserve CMYK Numbers Bevar CMYK-tal + Preserve RGB Numbers Bevar RGB-tal + Device to Simulate: Enhed, der simuleres: + Simulate Paper Color Simulér papirfarve + Simulate Black Ink Simulér sort blæk + Load… Indlæs… Previous page Forrige side Print Layers: Udskriv lag: Print Preset: Udskriftsforudindstilling: @@ -5709,6 +5720,10 @@ digits Malayalam Malayalam Add Color Tool Værktøjet Tilføj farve Remove Color Tool Værktøjet Fjern farve Remove Color Fjern farve + Set As Base Color Angiv som grundfarve + Select Shade Vælg nuance + Add New Color Tilføj ny farve + Set Current Color As Base Color Angiv aktuel farve som grundfarve Find the selected colors in the artwork Find de valgte farver i grafikken Harmony Rules Harmoniregler Keep this row's colors (exclude) Behold farverne i denne række (ekskludér) @@ -6892,6 +6907,7 @@ theme Appearance Udseende Add to Graphic Styles Føj til grafikstile Graphic Style Library Grafikstilbibliotek Add Used Colors Tilføj anvendte farver + Add Selected Colors Tilføj valgte farver Delete Swatch Slet farveprøve Duplicate Swatch Duplikér farveprøve Merge Swatches Flet farveprøver @@ -7089,6 +7105,11 @@ axis Both Begge Image Billede Ink Blæk Lab Lab + OKLCH Sliders OKLCH-skydere + HSL Sliders HSL-skydere + Chroma Kroma + The largest chroma sRGB holds at this lightness and hue Den største kroma, sRGB kan rumme ved denne lyshed og farvetone + OKLCH needs sRGB as the working RGB space OKLCH kræver sRGB som RGB-arbejdsfarverum Medium Medium Name Navn None Ingen @@ -7299,9 +7320,10 @@ font-technology Variable Variable Edit type set in fonts that aren't available? Rediger tekst i skrifttyper, der ikke er tilgængelige? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Viser hvert udsnits nummer i en boks i dets øverste venstre hjørne på lærredet; når den er slået fra, vises udsnittenes konturer stadig. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Farven på konturerne af bruger- og objektudsnit og på boksene med deres numre; automatiske udsnit bruger en svagere nuance af den. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Ny tekst får dette sprog, så længe sproget i Dokumentopsætning er Engelsk: USA; tekst, der allerede er i et dokument, beholder sit eget sprog. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. I afsnit med Orddeling slået til deles et ord på listen kun ved de bindestreger, der er skrevet i det, eller slet ikke uden nogen, uanset sprog og store eller små bogstaver. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. I desktopversionen indlæses .wasm-plug-ins i denne mappe ved start, og når du klikker på OK med en ny mappe her, undtagen i sikker tilstand; webversionen indlæser dem ikke. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normal beholder hvert plug-ins egne grænser; med Stor kan et plug-in-filter eller en plug-in-kommando køre mindst 250 millioner instruktioner ud over dem til sit input. Tidsgrænsen forbliver den samme. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Hvor mange instruktioner hver kørsel af et plug-ins objektfilter må bruge; Stor tillader flere end Normal med den samme grænse på 60 sekunder. Tunge filtre beholder deres eget budget. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Det første valg af midlertidig disk: Startup, None eller en mappesti; VectorCraft gemmer det, men bruger endnu ikke midlertidige diske. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Det andet valg af midlertidig disk: Startup, None eller en mappesti; VectorCraft gemmer det, men bruger endnu ikke midlertidige diske. How light or dark the interface is. Hvor lys eller mørk brugergrænsefladen er. @@ -7319,7 +7341,10 @@ font-technology Variable Variable The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Brugergrænsefladens sprog; Auto bruger systemets sprog. Dialogen skifter sprog, så snart du vælger et. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Animeret zoom virker kun, mens dette er slået til; slået fra er Animeret zoom nedtonet, og zoom animeres ikke. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Zoom med hjulet glider blødt ind, og Zoomværktøjet zoomer, mens du trækker til siden eller holder det nede; slået fra zoomer Zoomværktøjet til det område, du trækker hen over. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Fra næste start viser desktopversionen lærredet gennem denne type grafikprocessor; illustrationen tegnes altid på CPU'en. Automatisk foretrækker den integrerede på Windows og macOS. Webversionen bruger den ikke. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Fra næste start viser vinduet hvert billede uden at vente på skærmens opdatering, hvor grafikdriveren tillader det, højst 240 billeder i sekundet. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Fra næste start tegner desktopversionen med denne type grafikprocessor; Automatisk foretrækker den, der styrer skærmen. Webversionen bruger den ikke. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Fra næste start viser vinduet billeder uden at vente på, at skærmen opdateres, højst 240 i sekundet; slået fra bestemmer skærmen tempoet. En visningstilstand angivet ved start har forrang. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Det største antal fortryd-trin, hvert dokument beholder; et lavere tal fjerner de ældste trin, når du klikker på OK. Trin kan også forsvinde tidligere, når de bruger for meget hukommelse. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Viser grafikken ændre sig, mens du trækker; slået fra følger konturer trækket, og grafikken ændres, når du slipper. En hjælpelinje fra linealen flytter sig altid, mens du trækker. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Hvor mange arbejdstråde der tegner grafikken; -1 bruger én færre end de kerner, VectorCraft må bruge, højst 8, og 0 ingen. Webversionen bruger aldrig nogen. @@ -7346,6 +7371,10 @@ font-technology Variable Variable VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft gemmer dette valg, men Kopiér og Klip bruger endnu ikke et format til den ældre vektorudklipsholder. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Bevar stier eller Bevar udseende og overprint for den ældre vektorudklipsholder; VectorCraft gemmer valget, men bruger det endnu ikke. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. Bevar formatering beholder typografierne for tekst kopieret fra et tekstobjekt i VectorCraft, når den indsættes i et tekstobjekt; Bevar almindelig tekst giver den typografien, hvor den lander. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. Vis alle sorte som rich black viser ren CMYK-sort (kun sort blæk ved 100 %) som RGB-sort på lærredet; Vis alle sorte nøjagtigt konverterer den gennem arbejds-CMYK-farverummet. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Udskriv alle sorte som rich black tegner ren CMYK-sort som RGB-sort i RGB- og gråtone-rastereksporter og med Udskriv som bitmap; den ændrer ikke vektoreksporter, CMYK-JPEG, -TIFF og -PSD eller anden udskrivning. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. På en touchskærm skiftes til touch-arbejdsområdet; slås indstillingen fra, eller forsvinder touchskærmen, skiftes tilbage til det arbejdsområde, der var før. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Et tryk med to fingre på lærredet fortryder eller skifter i touch-arbejdsområdet mellem markerings- og tegneværktøjer, og et tryk med tre fingre gør om; ingen af dem virker i præsentationstilstand. New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Ny tekst får dette sprog, så længe sproget i Dokumentopsætning er Engelsk: USA og [Normal tegnstil] ikke angiver et sprog; tekst, der allerede er i et dokument, beholder sit eget sprog. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. I afsnit med Orddeling slået til deles et ord på listen kun ved de bindestreger, der er skrevet i det, eller slet ikke uden nogen, uanset store eller små bogstaver; koreanske ord får ingen bindestreg, og ord på indiske sprog deles ikke inde i en tegngruppe. Reset all preferences to their defaults? Nulstil alle præferencer til standard? @@ -7865,6 +7894,10 @@ imageTrace Outline Kontur @msg a guide has no curvature circle en hjælpelinje har ingen krumningscirkel @msg the circle that matches the path there would reach past the canvas cirklen, der passer til kurven der, ville gå ud over lærredet @msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går gennem disse punkter: to er ens, eller alle tre ligger på én linje +@msg `at` must be "start" or "end" `at` skal være "start" eller "end" +@msg give exactly one of `through` and `toward` angiv præcis én af `through` og `toward` +@msg no arc fits these points: two are the same or all three lie on one line ingen bue passer til disse punkter: to er ens, eller alle tre ligger på én linje +@msg give `at` only with `toward` angiv kun `at` sammen med `toward` @msg no app to open files here ingen app til at åbne filer her @msg no artboard ingen tegneflade @msg no artboard {i} (0-based; the document has {_1}) ingen tegneflade {i} (0-baseret; dokumentet har {_1}) @@ -7908,6 +7941,7 @@ imageTrace Outline Kontur @msg no native format intet indbygget format @msg no pages ingen sider @msg no pattern `{name}` intet mønster `{name}` +@msg art painted with `{name}` can't be its tile grafik malet med `{name}` kan ikke være dens flise @msg no perspective grid preset named `{name}` ingen perspektivgitterforudindstilling med navnet `{name}` @msg no plug-in {0} is installed plug-in'et {0} er ikke installeret @msg no plug-in {id} is installed plug-in'et {id} er ikke installeret @@ -8577,6 +8611,7 @@ imageTrace Outline Kontur Arrow Pil Arrow (open) Pil (åben) Barbed Modhager +arrowhead Feather Fjer Half Arrow (left) Halvpil (venstre) Half Arrow (right) Halvpil (højre) Concave Konkav @@ -8604,6 +8639,7 @@ imageTrace Outline Kontur Kite Drage Triangle to Bar Trekant til bjælke Oval Oval + Line Arrow Stregpil Complementary Komplementær Complementary 2 Komplementær 2 Split Complementary Delt komplementær @@ -9080,6 +9116,8 @@ variable-list-end {0}, {1} {0} og {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` skal være grayscale, rgb, hsb, cmyk eller websafe @msg `view` must be wheel or box `view` skal være wheel eller box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` skal være hue, saturation, brightness, red, green eller blue +@msg `sliders` must be none, oklch or hsl `sliders` skal være none, oklch eller hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH kræver sRGB som RGB-arbejdsfarverum @msg the Color Picker is not open farvevælgeren er ikke åben @msg the screen color sampler is already open skærmfarvesampleren er allerede åben @msg this system has no screen color sampler dette system har ingen skærmfarvesampler @@ -10352,6 +10390,7 @@ breakText Glyphs Glyffer Remove Strokes Fjern streger Place Brush Art Placér penselgrafik Replace Brush Art Erstat penselgrafik + Replace Pattern Art Erstat mønstergrafik Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Streger bruger denne pensel. Anvend den nye grafik på stregerne, eller lad dem være, som de er, og tilføj en kopi af penslen med den nye grafik? Apply to Strokes Anvend på streger Leave Strokes Bevar streger @@ -10780,6 +10819,21 @@ breakText Glyphs Glyffer @msg A joint does not close by {gap} pt. En samling lukker ikke med {gap} pt. @msg Two panels pass through each other. To paneler går gennem hinanden. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine" + Orbit Lines Banekurver + Petal Garland Kronbladsguirlande + Lattice Braid Gitterfletning + Facet Sweep Facetteret strøg + Artistic Brushes Kunstneriske pensler + Paint Maling + Flat Sweep Fladt strøg + Dry Drag Tørt træk + Loaded Stroke Fyldigt strøg + Fan Sweep Viftestrøg + Engraving Gravering + Fine Hatching Fin skravering + Dense Hatching Tæt skravering + Tapered Hatching Tilspidset skravering + Broken Hatching Afbrudt skravering Image Brush Billedpensler Soft Bloom Blød blomstring Halftone Field Halvtonefelt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index e7f4550cca..2060bc330b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -115,6 +115,7 @@ Add to Selection Zur Auswahl hinzufügen Add to Swatches Zu Farbfeldern hinzufügen Add Used Colors Verwendete Farben hinzufügen + Add Selected Colors Ausgewählte Farben hinzufügen Additional Plug-ins Folder Zusätzlicher Plug-in-Ordner Plug-in Instruction Budget Anweisungsbudget für Plug-ins Additional Fonts Folder Zusätzlicher Schriftenordner @@ -214,6 +215,10 @@ font-technology Variable Variabel Arc Bogen Arc Lower… Bogen unten… Arc Tool Bogen-Werkzeug + Three-Point Arc Tool Dreipunkt-Bogen-Werkzeug + Three-Point Arc Dreipunkt-Bogen + Arc too large Bogen zu groß + Third Point Sets Direction Dritter Punkt gibt die Richtung an Arc Upper… Bogen oben… Arch… Torbogen… Arc… Bogen… @@ -631,6 +636,8 @@ font-technology Variable Variabel Contextual Task Bar Kontextbezogene Taskleiste Pin Bar Position Position der Leiste fixieren Reset Bar Position Position der Leiste zurücksetzen + Bar Actions Aktionen der Leiste + Reset Bar Actions Aktionen der Leiste zurücksetzen Resize Größe ändern Contrast Kontrast Control Steuerung @@ -1694,6 +1701,10 @@ file-filter Templates Vorlagen Add Color Tool Farbe-hinzufügen-Werkzeug Remove Color Tool Farbe-entfernen-Werkzeug Remove Color Farbe entfernen + Set As Base Color Als Grundfarbe festlegen + Select Shade Schattierung auswählen + Add New Color Neue Farbe hinzufügen + Set Current Color As Base Color Aktuelle Farbe als Grundfarbe festlegen Find the selected colors in the artwork Ausgewählte Farben in der Grafik finden Harmony Sets Harmoniesätze Height Höhe @@ -2029,6 +2040,11 @@ file-filter Templates Vorlagen Knife Messer Knockout Group Aussparungsgruppe Lab Lab + OKLCH Sliders OKLCH-Regler + HSL Sliders HSL-Regler + Chroma Chroma + The largest chroma sRGB holds at this lightness and hue Das größte Chroma, das sRGB bei dieser Helligkeit und diesem Farbton enthält + OKLCH needs sRGB as the working RGB space OKLCH erfordert sRGB als RGB-Arbeitsfarbraum Lab Spot Colors: Lab-Volltonfarben: Lab Values Lab-Werte Landscape Querformat @@ -2826,6 +2842,11 @@ diagnostics ui Oberfläche Preserve Alpha Transparency Alphatransparenz beibehalten Preserve Appearance and Overprints Aussehen und Überdrucken beibehalten Preserve CMYK Numbers CMYK-Werte beibehalten + Preserve RGB Numbers RGB-Werte beibehalten + Device to Simulate: Zu simulierendes Gerät: + Simulate Paper Color Papierfarbe simulieren + Simulate Black Ink Schwarze Druckfarbe simulieren + Load… Laden… Preserve Editing Capabilities Bearbeitungsfunktionen beibehalten Preserve editing capabilities Bearbeitungsfunktionen beibehalten Preserve Lightness Helligkeit beibehalten @@ -3326,9 +3347,11 @@ digits Malayalam Malayalam Edit type set in fonts that aren't available? Text in Schriften bearbeiten, die nicht verfügbar sind? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Zeigt auf der Arbeitsfläche die Nummer jedes Slices in einem Kästchen oben links im Slice; ist die Option aus, werden die Slice-Umrisse weiterhin angezeigt. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Die Farbe der Umrisse von Benutzer- und Objekt-Slices und ihrer Nummernkästchen; automatische Slices verwenden einen blasseren Ton davon. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Neuer Text erhält diese Sprache, solange die Sprache unter „Dokument einrichten“ Englisch: USA ist; Text, der bereits in einem Dokument steht, behält seine Sprache. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Neuer Text erhält diese Sprache, solange die Sprache unter „Dokument einrichten“ Englisch: USA ist und [Normales Zeichenformat] keine Sprache festlegt; Text, der bereits in einem Dokument steht, behält seine Sprache. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. In Absätzen mit eingeschalteter Silbentrennung wird ein aufgeführtes Wort nur an den darin eingegebenen Bindestrichen getrennt oder gar nicht, wenn es keine hat, unabhängig von Sprache und Groß- und Kleinschreibung. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. In der Desktop-Version werden die .wasm-Plug-ins in diesem Ordner beim Start geladen und wenn Sie hier mit einem neuen Ordner auf OK klicken, außer im abgesicherten Modus; die Webversion lädt sie nicht. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. „Normal“ behält die eigenen Grenzen jedes Plug-ins; mit „Groß“ darf ein Plug-in-Filter oder -Befehl mindestens 250 Millionen Anweisungen zusätzlich zu denen für seine Eingabe ausführen. Das Zeitlimit bleibt gleich. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Wie viele Anweisungen jeder Lauf eines Objektfilters aus einem Plug-in verwenden darf; „Groß“ erlaubt mehr als „Normal“, bei derselben Grenze von 60 Sekunden. Aufwendige Filter behalten ihr eigenes Budget. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Die erste Wahl für das Arbeitsvolume: Startup, None oder ein Ordnerpfad; VectorCraft speichert sie, verwendet aber noch keine Arbeitsvolumes. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Die zweite Wahl für das Arbeitsvolume: Startup, None oder ein Ordnerpfad; VectorCraft speichert sie, verwendet aber noch keine Arbeitsvolumes. How light or dark the interface is. Wie hell oder dunkel die Benutzeroberfläche ist. @@ -3346,7 +3369,10 @@ digits Malayalam Malayalam The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Die Sprache der Benutzeroberfläche; „Auto“ verwendet die Sprache des Systems. Der Dialog wechselt die Sprache, sobald Sie eine wählen. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. „Animierter Zoom“ funktioniert nur, solange dies eingeschaltet ist; ausgeschaltet ist „Animierter Zoom“ abgeblendet und das Zoomen wird nicht animiert. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Der Zoom mit dem Mausrad gleitet weich, und das Zoom-Werkzeug zoomt, während Sie seitwärts ziehen oder es gedrückt halten; ausgeschaltet zoomt es auf den Bereich, über den Sie ziehen. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Ab dem nächsten Start zeigt die Desktop-Version die Zeichenfläche über diese Art von Grafikprozessor an; das Bildmaterial wird in jedem Fall auf der CPU gezeichnet. „Automatisch“ bevorzugt unter Windows und macOS den integrierten. Die Webversion verwendet sie nicht. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Ab dem nächsten Start zeigt das Fenster jedes Bild, ohne auf die Bildwiederholung des Bildschirms zu warten, wo der Grafiktreiber es zulässt, höchstens 240 Bilder pro Sekunde. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Ab dem nächsten Start zeichnet die Desktop-Version mit dieser Art von Grafikprozessor; „Automatisch“ bevorzugt den, der den Bildschirm ansteuert. Die Webversion verwendet sie nicht. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Ab dem nächsten Start zeigt das Fenster Bilder, ohne auf die Bildwiederholung des Bildschirms zu warten, höchstens 240 pro Sekunde; aus, gibt der Bildschirm den Takt vor. Ein beim Start festgelegter Darstellungsmodus hat Vorrang. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Die Höchstzahl der Rückgängig-Schritte, die jedes Dokument behält; eine kleinere Zahl entfernt beim Klick auf OK die ältesten Schritte. Schritte können auch früher entfallen, wenn sie zu viel Speicher belegen. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Zeigt beim Ziehen, wie sich das Bildmaterial ändert; ausgeschaltet folgen Umrisse dem Ziehen, und das Bildmaterial ändert sich beim Loslassen. Eine Hilfslinie aus dem Lineal bewegt sich beim Ziehen immer mit. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Wie viele Worker-Threads das Bildmaterial zeichnen; -1 verwendet einen weniger als die Kerne, die VectorCraft nutzen darf, höchstens 8, und 0 keinen. Die Webversion verwendet nie einen. @@ -3373,7 +3399,10 @@ digits Malayalam Malayalam VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft speichert diese Wahl, aber Kopieren und Ausschneiden verwenden noch kein Format der älteren Vektorzwischenablage. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. „Pfade beibehalten“ oder „Aussehen und Überdrucken beibehalten“ für die ältere Vektorzwischenablage; VectorCraft speichert die Wahl, verwendet sie aber noch nicht. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. „Formatierung beibehalten“ behält die Stile von Text aus einem Textobjekt in VectorCraft beim Einfügen in ein Textobjekt; „Nur Text beibehalten“ gibt ihm den Stil der Einfügestelle. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Neuer Text erhält diese Sprache, solange die Sprache unter „Dokument einrichten“ Englisch: USA ist und [Normales Zeichenformat] keine Sprache festlegt; Text, der bereits in einem Dokument steht, behält seine Sprache. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. „Alle Schwarztöne als tiefes Schwarz anzeigen“ zeigt reines CMYK-Schwarz (nur schwarze Farbe mit 100 %) auf der Arbeitsfläche als RGB-Schwarz; „Alle Schwarztöne genau anzeigen“ wandelt es über den CMYK-Arbeitsfarbraum um. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. „Alle Schwarztöne als tiefes Schwarz ausgeben“ zeichnet reines CMYK-Schwarz in RGB- und Graustufen-Rasterexporten und bei „Als Bitmap drucken“ als RGB-Schwarz; Vektorexporte, CMYK-JPEG, -TIFF und -PSD und anderes Drucken ändert es nicht. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Auf einem Touchscreen wird zum Touch-Arbeitsbereich gewechselt; beim Ausschalten oder wenn kein Touchscreen mehr erkannt wird, kehrt es zum vorherigen Arbeitsbereich zurück. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Tippen mit zwei Fingern auf die Arbeitsfläche macht rückgängig oder wechselt im Touch-Arbeitsbereich zwischen Auswahl- und Zeichenwerkzeugen, Tippen mit drei Fingern wiederholt; beides wirkt nicht im Präsentationsmodus. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. In Absätzen mit Silbentrennung wird ein aufgeführtes Wort nur an seinen eingegebenen Bindestrichen getrennt, ohne solche gar nicht, unabhängig von Groß- und Kleinschreibung; koreanische Wörter erhalten keinen Trennstrich, Wörter indischer Sprachen keine Trennung in einer Zeichengruppe. Reset all preferences to their defaults? Alle Voreinstellungen auf ihre Standardwerte zurücksetzen? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Die Standardwerte werden angewendet, wenn Sie in den Voreinstellungen auf OK klicken. Abbrechen dort behält Ihre aktuellen Voreinstellungen. @@ -5052,6 +5081,8 @@ liquify-list-end {0}, {1} {0} und {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` muss grayscale, rgb, hsb, cmyk oder websafe sein @msg `view` must be wheel or box `view` muss wheel oder box sein @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` muss hue, saturation, brightness, red, green oder blue sein +@msg `sliders` must be none, oklch or hsl `sliders` muss none, oklch oder hsl sein +@msg OKLCH needs sRGB as the working RGB space OKLCH erfordert sRGB als RGB-Arbeitsfarbraum @msg `{k}` must be [x, y] `{k}` muss [x, y] sein @msg `{name}` has no options `{name}` hat keine Optionen @msg `{name}` is a built-in workspace; choose another name `{name}` ist ein integrierter Arbeitsbereich; wählen Sie einen anderen Namen @@ -5245,6 +5276,10 @@ liquify-list-end {0}, {1} {0} und {1} @msg a guide has no curvature circle eine Hilfslinie hat keinen Krümmungskreis @msg the circle that matches the path there would reach past the canvas der Kreis, der dort zum Pfad passt, würde über die Arbeitsfläche hinausreichen @msg no circle passes through these points: two are the same or all three lie on one line durch diese Punkte verläuft kein Kreis: zwei sind gleich oder alle drei liegen auf einer Linie +@msg `at` must be "start" or "end" `at` muss „start“ oder „end“ sein +@msg give exactly one of `through` and `toward` geben Sie genau eines von `through` und `toward` an +@msg no arc fits these points: two are the same or all three lie on one line zu diesen Punkten passt kein Bogen: zwei sind gleich oder alle drei liegen auf einer Linie +@msg give `at` only with `toward` geben Sie `at` nur zusammen mit `toward` an @msg no app to open files here hier gibt es keine App zum Öffnen von Dateien @msg no artboard keine Zeichenfläche @msg no artboard {i} (0-based; the document has {_1}) keine Zeichenfläche {i} (Zählung ab 0; das Dokument hat {_1}) @@ -5291,6 +5326,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg no native format kein natives Format @msg no pages keine Seiten @msg no pattern `{name}` kein Muster `{name}` +@msg art painted with `{name}` can't be its tile mit `{name}` gefärbtes Bildmaterial kann nicht dessen Kachel sein @msg no perspective grid preset named `{name}` keine Vorgabe für Perspektivenraster namens `{name}` @msg no plug-in {0} is installed es ist kein Plug-in {0} installiert @msg no plug-in {id} is installed es ist kein Plug-in {id} installiert @@ -7602,6 +7638,36 @@ anchor Points: Punkte: @msg `{id}` is not a colour adjustment `{id}` ist keine Farbkorrektur @msg missing `effect` `effect` fehlt @msg `params` must be an object `params` muss ein Objekt sein +# Stroke arrowheads (Stroke panel, Dimension Tool Options and Properties › Arrow Style). + Triangle (open) Dreieck (offen) + Circle (open) Kreis (offen) + Square (open) Quadrat (offen) + Arrow (open) Pfeil (offen) + Barbed Mit Widerhaken +arrowhead Feather Feder + Half Arrow (left) Halber Pfeil (links) + Half Arrow (right) Halber Pfeil (rechts) + Double Bar Doppelbalken + Dot on Bar Punkt auf Balken + Chevron Winkel + Plus Plus + Hexagon (open) Sechseck (offen) + Tag Etikett + Tag (open) Etikett (offen) + Half Circle Halbkreis + Drop Tropfen + Slash Schrägstrich + Double Slash Doppelter Schrägstrich + Diamond (open) Raute (offen) + Reverse Triangle Umgekehrtes Dreieck + Swallowtail Schwalbenschwanz + Bracket Klammer + Fork Gabel + Leaf Blatt + Kite Drachen + Triangle to Bar Dreieck zu Balken + Oval Oval + Line Arrow Linienpfeil # Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. Path Precision Tools Pfad-Präzisionswerkzeuge Anchor Eraser Brush Ankerpunkt-Radierpinsel @@ -7892,6 +7958,7 @@ breakText Glyphs Glyphen Remove Strokes Konturen entfernen Place Brush Art Pinselgrafik platzieren Replace Brush Art Pinselgrafik ersetzen + Replace Pattern Art Mustergrafik ersetzen Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Konturen verwenden diesen Pinsel. Die neue Grafik auf diese Konturen anwenden oder sie unverändert lassen und eine Kopie des Pinsels mit der neuen Grafik hinzufügen? Apply to Strokes Auf Konturen anwenden Leave Strokes Konturen beibehalten @@ -10331,6 +10398,21 @@ breakText Glyphs Glyphen @msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden. @msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Scharniere: {hinges}, Fehler: {errors}, Warnungen: {warnings} + Orbit Lines Orbitlinien + Petal Garland Blütengirlande + Lattice Braid Gittergeflecht + Facet Sweep Facettenstrich + Artistic Brushes Künstlerische Pinsel + Paint Farbe + Flat Sweep Flacher Schwung + Dry Drag Trockener Zug + Loaded Stroke Satter Pinselstrich + Fan Sweep Fächerschwung + Engraving Gravur + Fine Hatching Feine Schraffur + Dense Hatching Dichte Schraffur + Tapered Hatching Verjüngte Schraffur + Broken Hatching Unterbrochene Schraffur Image Brush Bildpinsel Soft Bloom Sanfte Blüte Halftone Field Rasterfeld diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 4c51f54dd3..1223d2ed28 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -120,6 +120,7 @@ Add to Selection Προσθήκη στην επιλογή Add to Swatches Προσθήκη στα δείγματα χρωμάτων Add Used Colors Προσθήκη των χρησιμοποιημένων χρωμάτων + Add Selected Colors Προσθήκη των επιλεγμένων χρωμάτων Additional Plug-ins Folder Πρόσθετος φάκελος επεκτάσεων Plug-in Instruction Budget Προϋπολογισμός εντολών επεκτάσεων Additional Fonts Folder Πρόσθετος φάκελος γραμματοσειρών @@ -216,6 +217,10 @@ font-technology Variable Μεταβλητές Arc Τόξο Arc Lower… Κάτω τόξο… Arc Tool Τόξο (Arc Tool) + Three-Point Arc Tool Εργαλείο τόξου τριών σημείων + Three-Point Arc Τόξο τριών σημείων + Arc too large Το τόξο είναι πολύ μεγάλο + Third Point Sets Direction Το τρίτο σημείο ορίζει την κατεύθυνση Arc Upper… Πάνω τόξο… Arch… Αψίδα… Arc… Τόξο… @@ -605,6 +610,8 @@ font-technology Variable Μεταβλητές Contextual Task Bar Γραμμή εργασιών βάσει περιβάλλοντος Pin Bar Position Σταθεροποίηση θέσης γραμμής Reset Bar Position Επαναφορά θέσης γραμμής + Bar Actions Ενέργειες γραμμής + Reset Bar Actions Επαναφορά ενεργειών γραμμής Resize Αλλαγή μεγέθους Contrast Αντίθεση Control Έλεγχος @@ -1617,6 +1624,10 @@ font-technology Variable Μεταβλητές Add Color Tool Εργαλείο προσθήκης χρώματος Remove Color Tool Εργαλείο αφαίρεσης χρώματος Remove Color Αφαίρεση χρώματος + Set As Base Color Ορισμός ως βασικό χρώμα + Select Shade Επιλογή απόχρωσης + Add New Color Προσθήκη νέου χρώματος + Set Current Color As Base Color Ορισμός τρέχοντος χρώματος ως βασικού Find the selected colors in the artwork Εύρεση των επιλεγμένων χρωμάτων στο σχέδιο Harmony Sets Σύνολα χρωματικής αρμονίας Height Ύψος @@ -1924,6 +1935,11 @@ font-technology Variable Μεταβλητές Knife Μαχαίρι (Knife) Knockout Group Ομάδα διάτρησης Lab Lab + OKLCH Sliders Ρυθμιστικά OKLCH + HSL Sliders Ρυθμιστικά HSL + Chroma Χρωματική ένταση + The largest chroma sRGB holds at this lightness and hue Η μεγαλύτερη χρωματική ένταση που χωρά το sRGB σε αυτή τη φωτεινότητα και απόχρωση + OKLCH needs sRGB as the working RGB space Το OKLCH απαιτεί sRGB ως χώρο εργασίας RGB Lab Spot Colors: Πλακάτα χρώματα Lab: Lab Values Τιμές Lab Landscape Οριζόντιος προσανατολισμός @@ -1972,6 +1988,7 @@ font-technology Variable Μεταβλητές Lighten Φώτισμα Lightness Φωτεινότητα Line Γραμμή + Line Arrow Γραμμικό βέλος Line Segment Tool Ευθύγραμμο τμήμα (Line Segment Tool) Linear Gradient Γραμμικό ντεγκραντέ Lines Γραμμές @@ -3762,6 +3779,11 @@ theme Appearance Εμφάνιση Preserve Alpha Transparency Διατήρηση διαφάνειας άλφα Preserve Appearance and Overprints Διατήρηση εμφάνισης και υπερεκτυπώσεων Preserve CMYK Numbers Διατήρηση τιμών CMYK + Preserve RGB Numbers Διατήρηση τιμών RGB + Device to Simulate: Συσκευή προς προσομοίωση: + Simulate Paper Color Προσομοίωση χρώματος χαρτιού + Simulate Black Ink Προσομοίωση μαύρης μελάνης + Load… Φόρτωση… Preserve Editing Capabilities Διατήρηση δυνατοτήτων επεξεργασίας Preserve editing capabilities Διατήρηση δυνατοτήτων επεξεργασίας Preserve Lightness Διατήρηση φωτεινότητας @@ -4178,9 +4200,11 @@ digits Malayalam Μαλαγιάλαμ Edit type set in fonts that aren't available? Επεξεργασία κειμένου σε γραμματοσειρές που δεν είναι διαθέσιμες; Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Εμφανίζει στον καμβά τον αριθμό κάθε τομής σε ένα πλαίσιο πάνω αριστερά της· όταν είναι απενεργοποιημένο, τα περιγράμματα των τομών εξακολουθούν να εμφανίζονται. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Το χρώμα των περιγραμμάτων των τομών χρήστη και αντικειμένου και των πλαισίων με τους αριθμούς τους· οι αυτόματες τομές χρησιμοποιούν μια πιο αχνή απόχρωσή του. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Το νέο κείμενο παίρνει αυτήν τη γλώσσα όσο η γλώσσα στη Ρύθμιση εγγράφου είναι Αγγλικά: ΗΠΑ· το κείμενο που υπάρχει ήδη σε ένα έγγραφο κρατά τη δική του γλώσσα. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Το νέο κείμενο παίρνει αυτήν τη γλώσσα όσο η γλώσσα στη Ρύθμιση εγγράφου είναι Αγγλικά: ΗΠΑ και το [Κανονικό στυλ χαρακτήρων] δεν ορίζει γλώσσα· το κείμενο που υπάρχει ήδη σε ένα έγγραφο κρατά τη δική του γλώσσα. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. Σε παραγράφους με ενεργό τον Συλλαβισμό, μια λέξη της λίστας χωρίζεται μόνο στα ενωτικά που έχουν πληκτρολογηθεί σε αυτήν ή πουθενά αν δεν έχει, ανεξάρτητα από τη γλώσσα ή τα πεζά-κεφαλαία της. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. Στην έκδοση για υπολογιστή, τα πρόσθετα .wasm αυτού του φακέλου φορτώνονται κατά την εκκίνηση και όταν κάνετε κλικ στο Εντάξει με νέο φάκελο εδώ, εκτός από την Ασφαλή λειτουργία· η έκδοση web δεν τα φορτώνει. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Το Κανονική διατηρεί τα δικά όρια κάθε επέκτασης· με το Μεγάλο, ένα φίλτρο ή μια εντολή επέκτασης μπορεί να εκτελέσει τουλάχιστον 250 εκατομμύρια εντολές επιπλέον εκείνων για την είσοδό του. Το χρονικό όριο μένει το ίδιο. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Πόσες εντολές μπορεί να χρησιμοποιεί κάθε εκτέλεση φίλτρου αντικειμένων επέκτασης· το Μεγάλο επιτρέπει περισσότερες από το Κανονική, με το ίδιο όριο 60 δευτερολέπτων. Τα βαριά φίλτρα κρατούν το δικό τους όριο. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Η πρώτη επιλογή δίσκου προσωρινής αποθήκευσης: Startup, None ή διαδρομή φακέλου· το VectorCraft την αποθηκεύει, αλλά δεν χρησιμοποιεί ακόμη δίσκους προσωρινής αποθήκευσης. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Η δεύτερη επιλογή δίσκου προσωρινής αποθήκευσης: Startup, None ή διαδρομή φακέλου· το VectorCraft την αποθηκεύει, αλλά δεν χρησιμοποιεί ακόμη δίσκους προσωρινής αποθήκευσης. How light or dark the interface is. Πόσο φωτεινό ή σκοτεινό είναι το περιβάλλον χρήστη. @@ -4198,7 +4222,10 @@ digits Malayalam Μαλαγιάλαμ The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Η γλώσσα του περιβάλλοντος χρήστη· το Αυτόματα χρησιμοποιεί τη γλώσσα του συστήματος. Ο διάλογος αλλάζει γλώσσα μόλις επιλέξετε μία. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Η Κινούμενη μεγέθυνση λειτουργεί μόνο όσο αυτό είναι ενεργό· όταν είναι ανενεργό, η Κινούμενη μεγέθυνση είναι αχνή και η μεγέθυνση δεν κινείται. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Η μεγέθυνση με τον τροχό γλιστρά ομαλά, και το εργαλείο Μεγέθυνση μεγεθύνει καθώς σύρετε στο πλάι ή το κρατάτε πατημένο· όταν είναι ανενεργό, μεγεθύνει στην περιοχή που σύρετε. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Από την επόμενη εκκίνηση, η έκδοση για υπολογιστή εμφανίζει τον καμβά μέσω αυτού του είδους επεξεργαστή γραφικών· το έργο σχεδιάζεται πάντα στη CPU. Το Αυτόματο προτιμά τον ενσωματωμένο σε Windows και macOS. Η έκδοση web δεν το χρησιμοποιεί. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Από την επόμενη εκκίνηση, το παράθυρο εμφανίζει κάθε καρέ χωρίς να περιμένει την ανανέωση της οθόνης, όπου το επιτρέπει το πρόγραμμα οδήγησης γραφικών, έως 240 καρέ το δευτερόλεπτο. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Από την επόμενη εκκίνηση, η έκδοση για υπολογιστή σχεδιάζει με αυτό το είδος επεξεργαστή γραφικών· το Αυτόματο προτιμά αυτόν που οδηγεί την οθόνη. Η έκδοση web δεν το χρησιμοποιεί. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Από την επόμενη εκκίνηση, το παράθυρο δείχνει τα καρέ χωρίς αναμονή για ανανέωση της οθόνης, έως 240 το δευτερόλεπτο· ανενεργό, τα ρυθμίζει η οθόνη. Υπερισχύει η λειτουργία που ορίζεται στην εκκίνηση. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Τα περισσότερα βήματα αναίρεσης που κρατά κάθε έγγραφο· μικρότερος αριθμός αφαιρεί τα παλαιότερα βήματα όταν κάνετε κλικ στο Εντάξει. Βήματα μπορεί να φύγουν και νωρίτερα αν πιάνουν πολλή μνήμη. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Δείχνει το έργο να αλλάζει όσο σύρετε· όταν είναι ανενεργό, περιγράμματα ακολουθούν τη μεταφορά και το έργο αλλάζει όταν αφήσετε. Ένας οδηγός χάρακα κινείται πάντα όσο σύρετε. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Πόσα νήματα εργασίας σχεδιάζουν το έργο· το -1 χρησιμοποιεί ένα λιγότερο από τους πυρήνες που επιτρέπονται στο VectorCraft, έως 8, και το 0 κανένα. Η έκδοση web δεν χρησιμοποιεί ποτέ. @@ -4225,7 +4252,10 @@ digits Malayalam Μαλαγιάλαμ VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. Το VectorCraft αποθηκεύει αυτή την επιλογή, αλλά η Αντιγραφή και η Αποκοπή δεν χρησιμοποιούν ακόμη μορφή του πρόχειρου διανυσμάτων παλαιού τύπου. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Διατήρηση διαδρομών ή Διατήρηση εμφάνισης και υπερεκτυπώσεων για το πρόχειρο διανυσμάτων παλαιού τύπου· το VectorCraft αποθηκεύει την επιλογή αλλά δεν τη χρησιμοποιεί ακόμη. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. Η Διατήρηση μορφοποίησης κρατά τα στυλ κειμένου από αντικείμενο κειμένου του VectorCraft όταν επικολλάται σε αντικείμενο κειμένου· η Διατήρηση απλού κειμένου του δίνει το στυλ του σημείου όπου καταλήγει. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Το νέο κείμενο παίρνει αυτήν τη γλώσσα όσο η γλώσσα στη Ρύθμιση εγγράφου είναι Αγγλικά: ΗΠΑ και το [Κανονικό στυλ χαρακτήρων] δεν ορίζει γλώσσα· το κείμενο που υπάρχει ήδη σε ένα έγγραφο κρατά τη δική του γλώσσα. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. Η Εμφάνιση όλων των μαύρων ως πλούσιο μαύρο δείχνει το καθαρό μαύρο CMYK (μόνο μαύρο μελάνι στο 100%) ως μαύρο RGB στον καμβά· η Ακριβής απεικόνιση όλων των μαύρων το μετατρέπει μέσω του χώρου εργασίας CMYK. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Η Απόδοση όλων των μαύρων ως πλούσιο μαύρο σχεδιάζει το καθαρό μαύρο CMYK ως μαύρο RGB στις εξαγωγές raster RGB και κλίμακας του γκρι και με την Εκτύπωση ως bitmap· δεν αλλάζει τις διανυσματικές εξαγωγές, τα CMYK JPEG, TIFF και PSD ή την άλλη εκτύπωση. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Σε οθόνη αφής μεταβαίνει στον χώρο εργασίας αφής· η απενεργοποίηση ή η απώλεια της οθόνης αφής επαναφέρει τον χώρο εργασίας που υπήρχε πριν. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Το πάτημα με δύο δάχτυλα στον καμβά κάνει αναίρεση ή, στον χώρο εργασίας αφής, εναλλάσσει εργαλεία επιλογής και σχεδίασης, και το πάτημα με τρία δάχτυλα κάνει επανάληψη· κανένα δεν λειτουργεί στη λειτουργία παρουσίασης. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. Με Συλλαβισμό, μια λέξη της λίστας χωρίζεται μόνο στα ενωτικά της ή πουθενά αν δεν έχει, με πεζά ή κεφαλαία· οι κορεατικές λέξεις δεν παίρνουν ενωτικό, οι λέξεις ινδικών γλωσσών δεν χωρίζονται μέσα σε ομάδα χαρακτήρων. Reset all preferences to their defaults? Επαναφορά όλων των προτιμήσεων στις προεπιλογές τους; The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Οι προεπιλογές εφαρμόζονται όταν κάνετε κλικ στο Εντάξει στις Προτιμήσεις. Το Ακύρωση εκεί διατηρεί τις τρέχουσες προτιμήσεις σας. @@ -5305,6 +5335,10 @@ digits Malayalam Μαλαγιάλαμ @msg a guide has no curvature circle ένας οδηγός δεν έχει κύκλο καμπυλότητας @msg the circle that matches the path there would reach past the canvas ο κύκλος που ταιριάζει με τη διαδρομή εκεί θα υπερέβαινε τον καμβά @msg no circle passes through these points: two are the same or all three lie on one line κανένας κύκλος δεν περνά από αυτά τα σημεία: δύο είναι ίδια ή και τα τρία βρίσκονται σε μία ευθεία +@msg `at` must be "start" or "end" το `at` πρέπει να είναι "start" ή "end" +@msg give exactly one of `through` and `toward` δώστε ακριβώς ένα από τα `through` και `toward` +@msg no arc fits these points: two are the same or all three lie on one line κανένα τόξο δεν ταιριάζει σε αυτά τα σημεία: δύο είναι ίδια ή και τα τρία βρίσκονται σε μία ευθεία +@msg give `at` only with `toward` δώστε το `at` μόνο μαζί με το `toward` @msg no app to open files here δεν υπάρχει εφαρμογή για άνοιγμα αρχείων εδώ @msg no artboard δεν υπάρχει πίνακας σχεδίασης @msg no artboard {i} (0-based; the document has {_1}) δεν υπάρχει πίνακας σχεδίασης {i} (αρίθμηση από 0· το έγγραφο περιέχει {_1}) @@ -5350,6 +5384,7 @@ digits Malayalam Μαλαγιάλαμ @msg no native format δεν υπάρχει εγγενής μορφή @msg no pages δεν υπάρχουν σελίδες @msg no pattern `{name}` δεν υπάρχει μοτίβο `{name}` +@msg art painted with `{name}` can't be its tile σχέδιο βαμμένο με `{name}` δεν μπορεί να είναι το πλακίδιό του @msg no perspective grid preset named `{name}` δεν υπάρχει προεπιλογή πλέγματος προοπτικής με όνομα `{name}` @msg no plug-in {0} is installed δεν είναι εγκατεστημένο το πρόσθετο {0} @msg no plug-in {id} is installed δεν είναι εγκατεστημένο το πρόσθετο {id} @@ -6287,6 +6322,7 @@ variable-list-end {0}, {1} {0} και {1} Auto Size Αυτόματο μέγεθος Bar Ράβδος Barbed Αγκιστρωτό +arrowhead Feather Φτερό Baseline (Standard) Γραμμή βάσης (τυπική) Baseline Optimized Βελτιστοποιημένο για γραμμή βάσης Black Outline Μαύρο περίγραμμα @@ -6956,6 +6992,8 @@ effect Points Σημεία @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe το `mode` πρέπει να είναι grayscale, rgb, hsb, cmyk ή websafe @msg `view` must be wheel or box το `view` πρέπει να είναι wheel ή box @msg `channel` must be hue, saturation, brightness, red, green or blue το `channel` πρέπει να είναι hue, saturation, brightness, red, green ή blue +@msg `sliders` must be none, oklch or hsl Το `sliders` πρέπει να είναι none, oklch ή hsl +@msg OKLCH needs sRGB as the working RGB space Το OKLCH απαιτεί sRGB ως χώρο εργασίας RGB @msg `{key}` must be an array of these names: {_1} το `{key}` πρέπει να είναι πίνακας με αυτά τα ονόματα: {_1} @msg choose a destination folder επιλέξτε φάκελο προορισμού @msg choose a source folder επιλέξτε φάκελο προέλευσης @@ -8287,6 +8325,7 @@ breakText Glyphs Γλύφοι Remove Strokes Αφαίρεση περιγραμμάτων Place Brush Art Τοποθέτηση σχεδίου πινέλου Replace Brush Art Αντικατάσταση σχεδίου πινέλου + Replace Pattern Art Αντικατάσταση σχεδίου μοτίβου Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Περιγράμματα χρησιμοποιούν αυτό το πινέλο. Να εφαρμοστεί το νέο σχέδιο σε αυτά τα περιγράμματα ή να μείνουν ως έχουν και να προστεθεί αντίγραφο του πινέλου με το νέο σχέδιο; Apply to Strokes Εφαρμογή στα περιγράμματα Leave Strokes Διατήρηση περιγραμμάτων @@ -8867,6 +8906,21 @@ breakText Glyphs Γλύφοι @msg A joint does not close by {gap} pt. Μια ένωση δεν κλείνει κατά {gap} pt. @msg Two panels pass through each other. Δύο πάνελ διαπερνούν το ένα το άλλο. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" + Orbit Lines Τροχιακές γραμμές + Petal Garland Γιρλάντα πετάλων + Lattice Braid Πλεξούδα πλέγματος + Facet Sweep Πολυεδρική πινελιά + Artistic Brushes Καλλιτεχνικά πινέλα + Paint Ζωγραφική + Flat Sweep Επίπεδη πινελιά + Dry Drag Στεγνό σύρσιμο + Loaded Stroke Γεμάτη πινελιά + Fan Sweep Βεντάλια + Engraving Χαρακτική + Fine Hatching Λεπτή διαγράμμιση + Dense Hatching Πυκνή διαγράμμιση + Tapered Hatching Κωνική διαγράμμιση + Broken Hatching Διακεκομμένη διαγράμμιση Image Brush Πινέλα εικόνας Soft Bloom Απαλό άνθος Halftone Field Πεδίο ημιτόνων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 45d0400579..9bccf48eb8 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -140,6 +140,7 @@ Add to Selection Agregar a la selección Add to Swatches Agregar a muestras Add Used Colors Agregar colores usados + Add Selected Colors Agregar colores seleccionados Additional Plug-ins Folder Carpeta de plugins adicionales Plug-in Instruction Budget Presupuesto de instrucciones de plugins Additional Fonts Folder Carpeta de fuentes adicionales @@ -237,6 +238,10 @@ font-technology Variable Variables Arc Arco Arc Lower… Arco inferior… Arc Tool Herramienta Arco + Three-Point Arc Tool Herramienta Arco por tres puntos + Three-Point Arc Arco por tres puntos + Arc too large Arco demasiado grande + Third Point Sets Direction El tercer punto indica la dirección Arc Upper… Arco superior… Arch… Arcada… Arc… Arco… @@ -651,6 +656,8 @@ font-technology Variable Variables Contextual Task Bar Barra de tareas contextual Pin Bar Position Fijar posición de la barra Reset Bar Position Restablecer posición de la barra + Bar Actions Acciones de la barra + Reset Bar Actions Restablecer acciones de la barra Resize Cambiar tamaño Contrast Contraste Control Control @@ -1707,6 +1714,10 @@ font-technology Variable Variables Add Color Tool Herramienta Añadir color Remove Color Tool Herramienta Eliminar color Remove Color Eliminar color + Set As Base Color Establecer como color base + Select Shade Seleccionar matiz + Add New Color Añadir nuevo color + Set Current Color As Base Color Establecer el color actual como color base Find the selected colors in the artwork Buscar los colores seleccionados en la ilustración Harmony Sets Conjuntos de armonía Height Altura @@ -2028,6 +2039,11 @@ font-technology Variable Variables Knife Cuchilla Knockout Group Grupo de exclusión Lab Lab + OKLCH Sliders Controles deslizantes OKLCH + HSL Sliders Controles deslizantes HSL + Chroma Croma + The largest chroma sRGB holds at this lightness and hue El croma más alto que admite sRGB con esta luminosidad y este tono + OKLCH needs sRGB as the working RGB space OKLCH necesita sRGB como espacio de trabajo RGB Lab Spot Colors: Tintas planas Lab: Lab Values Valores Lab Landscape Horizontal @@ -2866,6 +2882,11 @@ font-technology Variable Variables Preserve Alpha Transparency Conservar transparencia alfa Preserve Appearance and Overprints Conservar apariencia y sobreimpresiones Preserve CMYK Numbers Conservar valores CMYK + Preserve RGB Numbers Conservar valores RGB + Device to Simulate: Dispositivo que simular: + Simulate Paper Color Simular color del papel + Simulate Black Ink Simular tinta negra + Load… Cargar… Preserve Editing Capabilities Conservar capacidades de edición Preserve editing capabilities Conservar capacidades de edición Preserve Lightness Conservar luminosidad @@ -3363,9 +3384,11 @@ digits Malayalam Malayálam Edit type set in fonts that aren't available? ¿Editar el texto en fuentes que no están disponibles? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Muestra en el lienzo el número de cada sector en un recuadro en su esquina superior izquierda; si está desactivado, los contornos de los sectores siguen visibles. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. El color de los contornos de los sectores de usuario y de objeto y de los recuadros con su número; los sectores automáticos usan un tono más apagado de ese color. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. El texto nuevo toma este idioma mientras el idioma de Ajustar documento sea Inglés: Estados Unidos; el texto que ya está en un documento conserva su idioma. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. El texto nuevo toma este idioma mientras el idioma de Ajustar documento sea Inglés: Estados Unidos y [Estilo de carácter normal] no defina ninguno; el texto que ya está en un documento conserva su idioma. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. En los párrafos con Separar con guiones activado, una palabra de la lista se divide solo en los guiones escritos en ella, o en ningún punto si no tiene, sea cual sea su idioma o uso de mayúsculas. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. En la versión de escritorio, los plugins .wasm de esta carpeta se cargan al iniciar y al hacer clic en Aceptar con una carpeta nueva aquí, salvo en Modo seguro; la versión web no los carga. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normal mantiene los límites propios de cada plugin; con Grande, un filtro o un comando de un plugin puede ejecutar al menos 250 millones de instrucciones además de las de su entrada. El límite de tiempo no cambia. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Cuántas instrucciones puede usar cada ejecución de un filtro de objetos de un plugin; Grande permite más que Normal con el mismo límite de 60 segundos. Los filtros pesados conservan su propio presupuesto. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. La primera opción de disco de memoria virtual: Startup, None o la ruta de una carpeta; VectorCraft la guarda, pero aún no usa discos de memoria virtual. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. La segunda opción de disco de memoria virtual: Startup, None o la ruta de una carpeta; VectorCraft la guarda, pero aún no usa discos de memoria virtual. How light or dark the interface is. Lo clara u oscura que es la interfaz. @@ -3383,7 +3406,10 @@ digits Malayalam Malayálam The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. El idioma de la interfaz; Auto usa el idioma del sistema. El cuadro de diálogo cambia de idioma en cuanto elige uno. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. El Zoom animado solo funciona mientras esto está activado; desactivado, el Zoom animado aparece atenuado y el zoom no se anima. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. El zoom con la rueda se desliza suavemente, y la Herramienta Zoom amplía mientras arrastra de lado o la mantiene pulsada; desactivado, la Herramienta Zoom amplía el área que arrastra. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. A partir del próximo inicio, la versión de escritorio muestra el lienzo a través de este tipo de procesador gráfico; la ilustración siempre se dibuja en la CPU. Automático prefiere el integrado en Windows y macOS. La versión web no lo usa. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. A partir del próximo inicio, la ventana muestra cada fotograma sin esperar la actualización de la pantalla cuando el controlador gráfico lo permite, con un máximo de 240 fotogramas por segundo. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. A partir del próximo inicio, la versión de escritorio dibuja con este tipo de procesador gráfico; Automático prefiere el que controla la pantalla. La versión web no lo usa. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. A partir del próximo inicio, la ventana muestra los fotogramas sin esperar a que la pantalla se actualice, como máximo 240 por segundo; desactivado, la pantalla marca el ritmo. Un modo de presentación definido al iniciar tiene prioridad. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. El máximo de pasos de deshacer que conserva cada documento; un número menor quita los pasos más antiguos al hacer clic en Aceptar. Los pasos también pueden irse antes si ocupan demasiada memoria. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Muestra cómo cambia el arte mientras arrastra; desactivado, los contornos siguen el arrastre y el arte cambia al soltar. Una guía de regla siempre se mueve mientras arrastra. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Cuántos hilos de trabajo dibujan el arte; -1 usa uno menos que los núcleos que VectorCraft puede usar, como máximo 8, y 0 ninguno. La versión web nunca usa ninguno. @@ -3410,7 +3436,10 @@ digits Malayalam Malayálam VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft guarda esta opción, pero Copiar y Cortar aún no usan ningún formato de portapapeles vectorial heredado. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Conservar trazados o Conservar apariencia y sobreimpresiones para el portapapeles vectorial heredado; VectorCraft guarda la opción, pero aún no la usa. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. Mantener formato conserva los estilos del texto copiado de un objeto de texto de VectorCraft al pegarlo en un objeto de texto; Mantener texto sin formato le da el estilo del lugar donde cae. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. El texto nuevo toma este idioma mientras el idioma de Ajustar documento sea Inglés: Estados Unidos y [Estilo de carácter normal] no defina ninguno; el texto que ya está en un documento conserva su idioma. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. Mostrar todos los negros como negro enriquecido muestra el negro CMYK puro (solo tinta negra al 100 %) como negro RGB en el lienzo; Mostrar todos los negros con precisión lo convierte mediante el espacio CMYK de trabajo. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Imprimir todos los negros como negro enriquecido dibuja el negro CMYK puro como negro RGB en las exportaciones ráster RGB y en escala de grises y con Imprimir como mapa de bits; no cambia las exportaciones vectoriales, los JPEG, TIFF y PSD CMYK ni otras impresiones. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. En una pantalla táctil, cambia al espacio de trabajo táctil; al desactivarlo o dejar de detectarse la pantalla táctil, vuelve al espacio de trabajo anterior al cambio. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Un toque con dos dedos en el lienzo deshace o, en el espacio de trabajo táctil, alterna entre herramientas de selección y de dibujo, y un toque con tres dedos rehace; ninguno funciona en el modo de presentación. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. En los párrafos con Separar con guiones activado, una palabra de la lista se divide solo en los guiones escritos en ella, o en ningún punto si no tiene, sea cual sea su uso de mayúsculas; las palabras coreanas no llevan guion, y las palabras en lenguas indias no se dividen dentro de un grupo de caracteres. Reset all preferences to their defaults? ¿Restablecer todas las preferencias a sus valores predeterminados? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Los valores predeterminados se aplican al hacer clic en Aceptar en Preferencias. Cancelar ahí conserva sus preferencias actuales. @@ -5164,6 +5193,8 @@ liquify-list-end {0}, {1} {0}, {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` debe ser grayscale, rgb, hsb, cmyk o websafe @msg `view` must be wheel or box `view` debe ser wheel o box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` debe ser hue, saturation, brightness, red, green o blue +@msg `sliders` must be none, oklch or hsl `sliders` debe ser none, oklch o hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH necesita sRGB como espacio de trabajo RGB @msg `{k}` must be [x, y] `{k}` debe ser [x, y] @msg `{name}` has no options `{name}` no tiene opciones @msg `{name}` is a built-in workspace; choose another name `{name}` es un espacio de trabajo integrado; elige otro nombre @@ -5357,6 +5388,10 @@ liquify-list-end {0}, {1} {0}, {1} @msg a guide has no curvature circle una guía no tiene círculo de curvatura @msg the circle that matches the path there would reach past the canvas el círculo que coincide con el trazado en ese punto excedería el lienzo @msg no circle passes through these points: two are the same or all three lie on one line ningún círculo pasa por estos puntos: dos son iguales o los tres están en una misma línea +@msg `at` must be "start" or "end" `at` debe ser "start" o "end" +@msg give exactly one of `through` and `toward` indique exactamente uno de `through` y `toward` +@msg no arc fits these points: two are the same or all three lie on one line ningún arco se ajusta a estos puntos: dos son iguales o los tres están en una misma línea +@msg give `at` only with `toward` indique `at` solo junto con `toward` @msg no app to open files here aquí no hay ninguna aplicación para abrir archivos @msg no artboard no hay mesa de trabajo @msg no artboard {i} (0-based; the document has {_1}) no existe la mesa de trabajo {i} (contando desde 0; el documento tiene {_1}) @@ -5402,6 +5437,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg no native format no hay formato nativo @msg no pages no hay páginas @msg no pattern `{name}` no existe el motivo `{name}` +@msg art painted with `{name}` can't be its tile una ilustración pintada con `{name}` no puede ser su azulejo @msg no perspective grid preset named `{name}` no hay ningún preajuste de cuadrícula de perspectiva llamado `{name}` @msg no plug-in {0} is installed no hay ningún plugin {0} instalado @msg no plug-in {id} is installed no hay ningún plugin {id} instalado @@ -6454,6 +6490,8 @@ effect Regular Regular Arrow Flecha Arrow (open) Flecha (abierta) Barbed Con púas +arrowhead Feather Emplumado +arrowhead Target Diana Half Arrow (left) Media flecha (izquierda) Half Arrow (right) Media flecha (derecha) Concave Cóncava @@ -6481,6 +6519,7 @@ effect Regular Regular Kite Cometa Triangle to Bar Triángulo a barra Oval Óvalo + Line Arrow Flecha de líneas Complementary Complementario Complementary 2 Complementario 2 Split Complementary Complementario dividido @@ -8272,6 +8311,7 @@ breakText Glyphs Glifos Remove Strokes Quitar trazos Place Brush Art Colocar ilustración del pincel Replace Brush Art Reemplazar ilustración del pincel + Replace Pattern Art Reemplazar ilustración del motivo Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Algunos trazos usan este pincel. ¿Aplicar la nueva ilustración a esos trazos, o dejarlos como están y añadir una copia del pincel con la nueva ilustración? Apply to Strokes Aplicar a los trazos Leave Strokes Dejar los trazos @@ -10610,6 +10650,21 @@ breakText Glyphs Glifos @msg A joint does not close by {gap} pt. Una unión no cierra por {gap} pt. @msg Two panels pass through each other. Dos paneles se atraviesan entre sí. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" + Orbit Lines Líneas orbitales + Petal Garland Guirnalda de pétalos + Lattice Braid Trenza reticular + Facet Sweep Trazo facetado + Artistic Brushes Pinceles artísticos + Paint Pintura + Flat Sweep Barrido plano + Dry Drag Arrastre seco + Loaded Stroke Trazo cargado + Fan Sweep Barrido en abanico + Engraving Grabado + Fine Hatching Rayado fino + Dense Hatching Rayado denso + Tapered Hatching Rayado afilado + Broken Hatching Rayado discontinuo Image Brush Pinceles de imagen Soft Bloom Flor suave Halftone Field Campo de semitonos diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 6299b74738..f8110fcd97 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -795,6 +795,8 @@ Contextual Task Bar Kontekstuaalinen tehtäväpalkki Pin Bar Position Kiinnitä palkin sijainti Reset Bar Position Palauta palkin sijainti + Bar Actions Palkin toiminnot + Reset Bar Actions Palauta palkin toiminnot Resize Muuta kokoa Tools Työkalut Toolbars Työkalurivit @@ -1502,6 +1504,10 @@ lighting Light Valo Add Anchor Point Tool Lisää ankkuripiste -työkalu Anchor Point Tool Ankkuripistetyökalu Arc Tool Kaarityökalu + Three-Point Arc Tool Kolmen pisteen kaaren työkalu + Three-Point Arc Kolmen pisteen kaari + Arc too large Kaari on liian suuri + Third Point Sets Direction Kolmas piste määrää suunnan Area Graph Tool Aluekaaviotyökalu Area Type Tool Aluetekstityökalu Artboard Tool Piirtoalustatyökalu @@ -3050,6 +3056,11 @@ digits Malayalam Malajalam Place the pages with the placement again Sijoita sivut uudelleen sijoittelun mukaan Placement: Sijoittelu: Preserve CMYK Numbers Säilytä CMYK-arvot + Preserve RGB Numbers Säilytä RGB-arvot + Device to Simulate: Simuloitava laite: + Simulate Paper Color Simuloi paperin väriä + Simulate Black Ink Simuloi mustaa mustetta + Load… Lataa… Previous page Edellinen sivu Print Layers: Tulosta tasot: Print Preset: Tulostuksen esiasetus: @@ -3127,6 +3138,10 @@ digits Malayalam Malajalam Add Color Tool Lisää väri -työkalu Remove Color Tool Poista väri -työkalu Remove Color Poista väri + Set As Base Color Aseta perusväriksi + Select Shade Valitse sävy + Add New Color Lisää uusi väri + Set Current Color As Base Color Aseta nykyinen väri perusväriksi Find the selected colors in the artwork Etsi valitut värit kuvituksesta Harmony Rules Harmoniasäännöt Keep this row's colors (exclude) Säilytä tämän rivin värit (jätä pois) @@ -4355,6 +4370,7 @@ theme Appearance Ulkoasu Add to Graphic Styles Lisää grafiikkatyyleihin Graphic Style Library Grafiikkatyylikirjasto Add Used Colors Lisää käytetyt värit + Add Selected Colors Lisää valitut värit Delete Swatch Poista värimalli Duplicate Swatch Monista värimalli Merge Swatches Yhdistä värimallit @@ -4554,6 +4570,11 @@ axis Both Molemmat Image Kuva Ink Muste Lab Lab + OKLCH Sliders OKLCH-liukusäätimet + HSL Sliders HSL-liukusäätimet + Chroma Kroma + The largest chroma sRGB holds at this lightness and hue Suurin kroma, jonka sRGB sisältää tällä vaaleudella ja sävyllä + OKLCH needs sRGB as the working RGB space OKLCH vaatii sRGB:n RGB-työväriavaruudeksi Medium Keskitaso Name Nimi None Ei mitään @@ -4766,9 +4787,11 @@ font-technology Variable Muuttuvat Edit type set in fonts that aren't available? Muokataanko tekstiä, jonka fontit eivät ole käytettävissä? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Näyttää piirtopinnalla kunkin viipaleen numeron ruudussa sen vasemmassa yläkulmassa; kun asetus on pois päältä, viipaleiden ääriviivat näkyvät edelleen. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Käyttäjä- ja objektiviipaleiden ääriviivojen ja niiden numeroruutujen väri; automaattiset viipaleet käyttävät siitä himmeämpää sävyä. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Uusi teksti saa tämän kielen, kun Asiakirjan asetusten kieli on Englanti: USA; asiakirjassa jo oleva teksti säilyttää oman kielensä. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Uusi teksti saa tämän kielen, kun Asiakirjan asetusten kieli on Englanti: USA eikä [Normaali merkkityyli] määritä kieltä; asiakirjassa jo oleva teksti säilyttää oman kielensä. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. Kappaleissa, joissa Tavuta on käytössä, luettelon sana tavutetaan vain siihen kirjoitettujen yhdysmerkkien kohdalta tai ei lainkaan, jos niitä ei ole, kielestä ja kirjainkoosta riippumatta. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. Työpöytäversiossa tämän kansion .wasm-laajennukset ladataan käynnistettäessä ja kun napsautat OK uuden kansion kanssa tässä, paitsi vikasietotilassa; verkkoversio ei lataa niitä. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normaali säilyttää kunkin laajennuksen omat rajat; Suuri-asetuksella laajennuksen suodin tai komento voi suorittaa vähintään 250 miljoonaa käskyä syötteensä käskyjen lisäksi. Aikaraja pysyy samana. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Kuinka monta käskyä laajennuksen objektisuotimen kukin suorituskerta saa käyttää; Suuri sallii enemmän kuin Normaali samalla 60 sekunnin rajalla. Raskaat suotimet säilyttävät oman budjettinsa. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Ensimmäinen työlevyvalinta: Startup, None tai kansiopolku; VectorCraft tallentaa sen, mutta ei vielä käytä työlevyjä. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Toinen työlevyvalinta: Startup, None tai kansiopolku; VectorCraft tallentaa sen, mutta ei vielä käytä työlevyjä. How light or dark the interface is. Kuinka vaalea tai tumma käyttöliittymä on. @@ -4786,7 +4809,10 @@ font-technology Variable Muuttuvat The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Käyttöliittymän kieli; Automaattinen käyttää järjestelmän kieltä. Valintaikkuna vaihtaa kielen heti, kun valitset sellaisen. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Animoitu zoomaus toimii vain, kun tämä on päällä; pois päältä Animoitu zoomaus on himmennetty eikä zoomausta animoida. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Rullalla zoomaus liukuu pehmeästi, ja Zoomaustyökalu zoomaa, kun vedät sivulle tai pidät sitä painettuna; pois päältä Zoomaustyökalu zoomaa alueeseen, jonka yli vedät. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Seuraavasta käynnistyksestä alkaen työpöytäversio näyttää piirtoalueen tämän tyyppisen grafiikkasuorittimen kautta; kuvitus piirretään joka tapauksessa suorittimella. Automaattinen suosii integroitua Windowsissa ja macOS:ssä. Verkkoversio ei käytä sitä. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Seuraavasta käynnistyksestä alkaen ikkuna näyttää jokaisen kuvan odottamatta näytön virkistystä, kun grafiikkaohjain sallii sen, enintään 240 kuvaa sekunnissa. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Seuraavasta käynnistyksestä alkaen työpöytäversio piirtää tämän tyyppisellä grafiikkasuorittimella; Automaattinen suosii näyttöä ohjaavaa. Verkkoversio ei käytä sitä. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Seuraavasta käynnistyksestä alkaen ikkuna näyttää kuvat odottamatta näytön virkistystä, enintään 240 sekunnissa; pois päältä näyttö tahdittaa ne. Käynnistettäessä asetettu esitystila ohittaa sen. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Kumoamisvaiheiden enimmäismäärä, jonka kukin asiakirja säilyttää; pienempi luku poistaa vanhimmat vaiheet, kun napsautat OK. Vaiheita voi poistua aiemmin, jos ne vievät liikaa muistia. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Näyttää kuvituksen muuttuvan vetäessäsi; pois päältä ääriviivat seuraavat vetoa ja kuvitus muuttuu, kun vapautat. Viivaimen apuviiva liikkuu aina vetäessäsi. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Montako työsäiettä piirtää kuvituksen; -1 käyttää yhden vähemmän kuin VectorCraftin käytettävissä olevia ytimiä, enintään 8, ja 0 ei yhtään. Verkkoversio ei käytä koskaan yhtään. @@ -4813,7 +4839,10 @@ font-technology Variable Muuttuvat VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft tallentaa tämän valinnan, mutta Kopioi ja Leikkaa eivät vielä käytä vanhan vektorileikepöydän muotoa. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Säilytä polut tai Säilytä ulkoasu ja päällepainatukset vanhalle vektorileikepöydälle; VectorCraft tallentaa valinnan, mutta ei vielä käytä sitä. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. Säilytä muotoilu säilyttää VectorCraftin tekstiobjektista kopioidun tekstin tyylit, kun se liitetään tekstiobjektiin; Säilytä pelkkä teksti antaa sille liittämiskohdan tyylin. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Uusi teksti saa tämän kielen, kun Asiakirjan asetusten kieli on Englanti: USA eikä [Normaali merkkityyli] määritä kieltä; asiakirjassa jo oleva teksti säilyttää oman kielensä. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. Näytä kaikki mustat syvämustina näyttää puhtaan CMYK-mustan (pelkkä musta muste 100 %:na) RGB-mustana piirtopinnalla; Näytä kaikki mustat tarkasti muuntaa sen työ-CMYK-väriavaruuden kautta. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Tulosta kaikki mustat syvämustina piirtää puhtaan CMYK-mustan RGB-mustana RGB- ja harmaasävyrasterivienneissä ja Tulosta bittikarttana -asetuksella; se ei muuta vektorivientejä, CMYK-JPEG-, -TIFF- ja -PSD-tiedostoja eikä muuta tulostusta. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Kosketusnäytöllä vaihtaa kosketustyötilaan; asetuksen poistaminen käytöstä tai kosketusnäytön katoaminen palauttaa työtilan, josta vaihdettiin. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Kahden sormen napautus piirtopinnalla kumoaa tai vaihtaa kosketustyötilassa valinta- ja piirtotyökalujen välillä, ja kolmen sormen napautus tekee uudelleen; kumpikaan ei toimi esitystilassa. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. Kappaleissa, joissa Tavuta on käytössä, luettelon sana tavutetaan vain siihen kirjoitettujen yhdysmerkkien kohdalta tai ei lainkaan, jos niitä ei ole, kirjainkoosta riippumatta; korealaisiin sanoihin ei tule tavuviivaa, eikä intialaisten kielten sanoja tavuteta merkkiryhmän sisältä. Reset all preferences to their defaults? Palautetaanko kaikki asetukset oletuksiin? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Oletukset otetaan käyttöön, kun valitset Asetuksissa OK. Peruuta siellä säilyttää nykyiset asetuksesi. @@ -5590,6 +5619,10 @@ liquify-list-end {0}, {1} {0} ja {1} @msg a guide has no curvature circle apuviivalla ei ole kaarevuusympyrää @msg the circle that matches the path there would reach past the canvas ympyrä, joka vastaa polkua siinä kohdassa, ylittäisi kankaan @msg no circle passes through these points: two are the same or all three lie on one line näiden pisteiden kautta ei kulje ympyrää: kaksi pisteistä on samoja tai kaikki kolme ovat samalla suoralla +@msg `at` must be "start" or "end" `at` on oltava "start" tai "end" +@msg give exactly one of `through` and `toward` anna täsmälleen yksi parametreista `through` ja `toward` +@msg no arc fits these points: two are the same or all three lie on one line näihin pisteisiin ei sovi kaarta: kaksi pisteistä on samoja tai kaikki kolme ovat samalla suoralla +@msg give `at` only with `toward` anna `at` vain yhdessä parametrin `toward` kanssa @msg no app to open files here täällä ei ole sovellusta tiedostojen avaamiseen @msg no artboard ei piirtoalustaa @msg no artboard {i} (0-based; the document has {_1}) ei piirtoalustaa {i} (0-pohjainen; asiakirjassa on {_1}) @@ -5635,6 +5668,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg no native format ei omaa tiedostomuotoa @msg no pages ei sivuja @msg no pattern `{name}` ei kuviota `{name}` +@msg art painted with `{name}` can't be its tile kuviolla `{name}` maalattu kuvitus ei voi olla sen ruutu @msg no perspective grid preset named `{name}` ei perspektiiviruudukon esiasetusta nimeltä `{name}` @msg no plug-in {0} is installed laajennusta {0} ei ole asennettu @msg no plug-in {id} is installed laajennusta {id} ei ole asennettu @@ -6416,6 +6450,7 @@ variable-list-end {0}, {1} {0} ja {1} Arrow Nuoli Arrow (open) Nuoli (avoin) Barbed Väkänen +arrowhead Feather Sulka Half Arrow (left) Puolinuoli (vasen) Half Arrow (right) Puolinuoli (oikea) Concave Kovera @@ -6443,6 +6478,7 @@ variable-list-end {0}, {1} {0} ja {1} Kite Leija Triangle to Bar Kolmiosta palkkiin Oval Soikio + Line Arrow Viivanuoli Complementary Vastaväri Complementary 2 Vastaväri 2 Split Complementary Jaettu vastaväri @@ -6961,6 +6997,8 @@ mark-style Japanese Japanilainen @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`-arvon on oltava grayscale, rgb, hsb, cmyk tai websafe @msg `view` must be wheel or box `view`-arvon on oltava wheel tai box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel`-arvon on oltava hue, saturation, brightness, red, green tai blue +@msg `sliders` must be none, oklch or hsl `sliders` on oltava none, oklch tai hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH vaatii sRGB:n RGB-työväriavaruudeksi @msg `{key}` must be an array of these names: {_1} `{key}`-arvon on oltava taulukko, jossa on näitä nimiä: {_1} @msg choose a destination folder valitse kohdekansio @msg choose a source folder valitse lähdekansio @@ -8363,6 +8401,7 @@ breakText Glyphs Merkit Remove Strokes Poista viivat Place Brush Art Sijoita siveltimen kuvitus Replace Brush Art Korvaa siveltimen kuvitus + Replace Pattern Art Korvaa kuvion kuvitus Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Viivat käyttävät tätä sivellintä. Käytetäänkö uutta kuvitusta näissä viivoissa, vai jätetäänkö ne ennalleen ja lisätään siveltimestä kopio, jossa on uusi kuvitus? Apply to Strokes Käytä viivoihin Leave Strokes Jätä viivat ennalleen @@ -8950,6 +8989,21 @@ breakText Glyphs Merkit @msg A joint does not close by {gap} pt. Liitos ei sulkeudu, rako {gap} pt. @msg Two panels pass through each other. Kaksi paneelia kulkee toistensa läpi. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" + Orbit Lines Kiertoradan viivat + Petal Garland Terälehtiköynnös + Lattice Braid Ristikkopunos + Facet Sweep Särmikäs veto + Artistic Brushes Taidesiveltimet + Paint Maalaus + Flat Sweep Tasainen veto + Dry Drag Kuiva veto + Loaded Stroke Runsas siveltimenveto + Fan Sweep Viuhkaveto + Engraving Kaiverrus + Fine Hatching Hieno viivoitus + Dense Hatching Tiheä viivoitus + Tapered Hatching Kapeneva viivoitus + Broken Hatching Katkoviivoitus Image Brush Kuvasiveltimet Soft Bloom Pehmeä kukinta Halftone Field Rasterikenttä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 0bf3c4eba5..d3208f8c6b 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -141,6 +141,7 @@ Add to Selection Ajouter à la sélection Add to Swatches Ajouter au nuancier Add Used Colors Ajouter les couleurs utilisées + Add Selected Colors Ajouter les couleurs sélectionnées Additional Plug-ins Folder Dossier de modules externes supplémentaires Plug-in Instruction Budget Budget d’instructions des modules externes Additional Fonts Folder Dossier de polices supplémentaires @@ -238,6 +239,10 @@ font-technology Variable Variables Arc Arc Arc Lower… Arc inférieur… Arc Tool Outil Arc + Three-Point Arc Tool Outil Arc par trois points + Three-Point Arc Arc par trois points + Arc too large Arc trop grand + Third Point Sets Direction Le troisième point indique la direction Arc Upper… Arc supérieur… Arch… Arche… Arc… Arc… @@ -652,6 +657,8 @@ font-technology Variable Variables Contextual Task Bar Barre des tâches contextuelle Pin Bar Position Épingler la position de la barre Reset Bar Position Réinitialiser la position de la barre + Bar Actions Actions de la barre + Reset Bar Actions Réinitialiser les actions de la barre Resize Redimensionner Contrast Contraste Control Contrôle @@ -1696,6 +1703,10 @@ font-technology Variable Variables Add Color Tool Outil Ajouter une couleur Remove Color Tool Outil Supprimer une couleur Remove Color Supprimer la couleur + Set As Base Color Définir comme couleur de base + Select Shade Sélectionner une nuance + Add New Color Ajouter une nouvelle couleur + Set Current Color As Base Color Définir la couleur actuelle comme couleur de base Find the selected colors in the artwork Rechercher les couleurs sélectionnées dans l’illustration Harmony Rules: Règles d’harmonie : Harmony Sets Ensembles d’harmonies @@ -2018,6 +2029,11 @@ font-technology Variable Variables Knife Cutter Knockout Group Groupe perçant Lab Lab + OKLCH Sliders Curseurs OKLCH + HSL Sliders Curseurs HSL + Chroma Chroma + The largest chroma sRGB holds at this lightness and hue Le plus grand chroma que sRGB contient à cette luminosité et cette teinte + OKLCH needs sRGB as the working RGB space OKLCH nécessite sRGB comme espace de travail RGB Lab Spot Colors: Tons directs Lab : Lab Values Valeurs Lab Landscape Paysage @@ -2854,6 +2870,11 @@ font-technology Variable Variables Preserve Alpha Transparency Conserver la transparence alpha Preserve Appearance and Overprints Conserver l’aspect et les surimpressions Preserve CMYK Numbers Conserver les valeurs CMJN + Preserve RGB Numbers Conserver les valeurs RVB + Device to Simulate: Périphérique à simuler : + Simulate Paper Color Simuler la couleur du papier + Simulate Black Ink Simuler l’encre noire + Load… Charger… Preserve Editing Capabilities Conserver les fonctions d’édition Preserve editing capabilities Conserver les fonctions d’édition Preserve Lightness Conserver la luminosité @@ -3351,9 +3372,11 @@ digits Malayalam Malayalam Edit type set in fonts that aren't available? Modifier le texte composé dans des polices non disponibles ? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Affiche sur la zone de travail le numéro de chaque tranche dans un cadre en haut à gauche de la tranche. Désactivée, les contours des tranches restent affichés. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. La couleur des contours des tranches utilisateur et objet et de leurs cadres de numéro. Les tranches automatiques utilisent une nuance plus terne de cette couleur. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Le nouveau texte prend cette langue tant que la langue de Format de document est l’anglais des États-Unis. Le texte déjà présent dans un document garde sa langue. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Le nouveau texte prend cette langue tant que la langue de Format de document est l’anglais des États-Unis et que [Style de caractère normal] n’en définit aucune. Le texte déjà présent dans un document garde sa langue. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. Dans les paragraphes où Césure est activée, un mot de la liste n’est coupé qu’aux traits d’union saisis dedans, ou nulle part s’il n’en a pas, quelles que soient sa langue et sa casse. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. Dans la version de bureau, les modules externes .wasm de ce dossier se chargent au démarrage et lorsque vous cliquez sur OK avec un nouveau dossier ici, sauf en mode sans échec. La version web ne les charge pas. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normal conserve les limites propres à chaque module externe. Avec Grand, un filtre ou une commande d’un module externe peut exécuter au moins 250 millions d’instructions en plus de celles de son entrée. La limite de temps reste la même. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Le nombre d’instructions que chaque exécution d’un filtre d’objets d’un module externe peut utiliser. Grand en autorise plus que Normal, avec la même limite de 60 secondes. Les filtres lourds gardent leur propre budget. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Premier disque de travail (Startup, None ou le chemin d’un dossier). VectorCraft l’enregistre, mais n’utilise pas encore de disques de travail. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Second disque de travail (Startup, None ou le chemin d’un dossier). VectorCraft l’enregistre, mais n’utilise pas encore de disques de travail. How light or dark the interface is. Le degré de clarté de l’interface, du plus sombre au plus clair. @@ -3371,7 +3394,10 @@ digits Malayalam Malayalam The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. La langue de l’interface. Auto utilise la langue du système. La boîte de dialogue change de langue dès que vous en choisissez une. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Le Zoom animé ne fonctionne que si cette option est activée. Désactivée, le Zoom animé est grisé et le zoom n’est pas animé. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Le zoom à la molette glisse en douceur, et l’Outil Zoom zoome quand vous faites glisser de côté ou le maintenez enfoncé. Désactivée, l’Outil Zoom zoome sur la zone que vous parcourez. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. À partir du prochain démarrage, la version de bureau affiche le canevas par ce type de processeur graphique. L’illustration est toujours dessinée par le processeur central. Automatique préfère le processeur intégré sous Windows et macOS. La version web ne l’utilise pas. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. À partir du prochain démarrage, la fenêtre affiche chaque image sans attendre le rafraîchissement de l’écran lorsque le pilote graphique le permet, au plus 240 images par seconde. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. À partir du prochain démarrage, la version de bureau dessine avec ce type de processeur graphique. Automatique préfère celui qui pilote l’écran. La version web ne l’utilise pas. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. À partir du prochain démarrage, la fenêtre affiche les images sans attendre le rafraîchissement de l’écran, au plus 240 par seconde. Désactivé, l’écran les cadence. Un mode de présentation défini au lancement a la priorité. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Le nombre maximal d’étapes d’annulation que chaque document conserve. Un nombre plus bas supprime les plus anciennes quand vous cliquez sur OK. Des étapes peuvent aussi partir plus tôt si elles occupent trop de mémoire. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Montre l’illustration qui change pendant que vous faites glisser. Désactivée, des contours suivent le glissement et l’illustration change quand vous relâchez. Un repère de règle suit toujours le glissement. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Le nombre de threads de travail qui dessinent l’illustration. Avec -1, VectorCraft en utilise un de moins que les cœurs qu’il peut utiliser, 8 au plus, et avec 0 aucun. La version web n’en utilise jamais. @@ -3398,7 +3424,10 @@ digits Malayalam Malayalam VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft enregistre ce choix, mais Copier et Couper n’utilisent pas encore de format de presse-papiers vectoriel hérité. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Conserver les tracés ou Conserver l’aspect et les surimpressions pour le presse-papiers vectoriel hérité. VectorCraft enregistre le choix mais ne l’utilise pas encore. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. Conserver la mise en forme garde les styles du texte copié depuis un objet texte de VectorCraft quand il est collé dans un objet texte. Conserver le texte brut lui donne le style de l’endroit où il arrive. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Le nouveau texte prend cette langue tant que la langue de Format de document est l’anglais des États-Unis et que [Style de caractère normal] n’en définit aucune. Le texte déjà présent dans un document garde sa langue. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. Afficher tous les noirs en noir intense affiche le noir CMJN pur (encre noire seule à 100 %) en noir RVB sur la zone de travail. Afficher tous les noirs avec précision le convertit par l’espace CMJN de travail. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Reproduire tous les noirs en noir intense dessine le noir CMJN pur en noir RVB dans les exportations matricielles RVB et en niveaux de gris et avec Imprimer en tant que bitmap. Les exportations vectorielles, les JPEG, TIFF et PSD CMJN et les autres impressions ne changent pas. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Sur un écran tactile, passe à l’espace de travail tactile. Désactiver l’option ou perdre l’écran tactile ramène à l’espace de travail d’avant ce changement. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Un toucher à deux doigts sur la zone de travail annule ou, dans l’espace de travail tactile, bascule entre outils de sélection et de dessin, et un toucher à trois doigts rétablit. Aucun ne fonctionne en mode Présentation. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. Dans les paragraphes où Césure est activée, un mot de la liste n’est coupé qu’aux traits d’union saisis dedans, ou nulle part s’il n’en a pas, quelle que soit sa casse. Les mots coréens ne prennent pas de trait d’union, et les mots en langues indiennes ne sont pas coupés à l’intérieur d’un groupe de caractères. Reset all preferences to their defaults? Rétablir toutes les préférences à leur valeur par défaut ? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Les valeurs par défaut sont appliquées lorsque vous cliquez sur OK dans Préférences. Annuler y conserve vos préférences actuelles. @@ -5123,6 +5152,8 @@ liquify-list-end {0}, {1} {0} et {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` doit valoir grayscale, rgb, hsb, cmyk ou websafe @msg `view` must be wheel or box `view` doit valoir wheel ou box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` doit valoir hue, saturation, brightness, red, green ou blue +@msg `sliders` must be none, oklch or hsl `sliders` doit valoir none, oklch ou hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH nécessite sRGB comme espace de travail RGB @msg `{k}` must be [x, y] `{k}` doit être [x, y] @msg `{name}` has no options `{name}` n’a pas d’options @msg `{name}` is a built-in workspace; choose another name `{name}` est un espace de travail intégré ; choisissez un autre nom @@ -5316,6 +5347,10 @@ liquify-list-end {0}, {1} {0} et {1} @msg a guide has no curvature circle un repère n’a pas de cercle de courbure @msg the circle that matches the path there would reach past the canvas le cercle qui correspond au tracé à cet endroit dépasserait la zone de travail @msg no circle passes through these points: two are the same or all three lie on one line aucun cercle ne passe par ces points : deux sont identiques ou les trois sont alignés +@msg `at` must be "start" or "end" `at` doit valoir "start" ou "end" +@msg give exactly one of `through` and `toward` indiquez exactement un seul de `through` et `toward` +@msg no arc fits these points: two are the same or all three lie on one line aucun arc ne correspond à ces points : deux sont identiques ou les trois sont alignés +@msg give `at` only with `toward` indiquez `at` uniquement avec `toward` @msg no app to open files here aucune application pour ouvrir des fichiers ici @msg no artboard aucun plan de travail @msg no artboard {i} (0-based; the document has {_1}) aucun plan de travail {i} (numérotation à partir de 0 ; le document en a {_1}) @@ -5361,6 +5396,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg no native format aucun format natif @msg no pages aucune page @msg no pattern `{name}` aucun motif `{name}` +@msg art painted with `{name}` can't be its tile une illustration peinte avec `{name}` ne peut pas être son carreau @msg no perspective grid preset named `{name}` aucun paramètre prédéfini de grille de perspective nommé `{name}` @msg no plug-in {0} is installed aucun plug-in {0} n’est installé @msg no plug-in {id} is installed aucun plug-in {id} n’est installé @@ -6488,6 +6524,7 @@ lighting Light Lumière B5 B5 Bar Barre Barbed Barbelée +arrowhead Feather Empennage Baseline (Standard) De base (standard) Baseline Optimized De base optimisé Basic De base @@ -6616,6 +6653,7 @@ lighting Light Lumière Letterhead A4 Papier à en-tête A4 Letterhead Letter Papier à en-tête Lettre US Line Art Dessin au trait + Line Arrow Flèche filaire Linear Linéaire Logo 1000×1000 Logo 1000×1000 Low Fidelity Photo Photo basse fidélité @@ -8292,6 +8330,7 @@ breakText Glyphs Glyphes Remove Strokes Supprimer les contours Place Brush Art Placer l’illustration de la forme Replace Brush Art Remplacer l’illustration de la forme + Replace Pattern Art Remplacer l’illustration du motif Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Des contours utilisent cette forme. Appliquer la nouvelle illustration à ces contours, ou les laisser tels quels et ajouter une copie de la forme avec la nouvelle illustration ? Apply to Strokes Appliquer aux contours Leave Strokes Conserver les contours @@ -10681,6 +10720,21 @@ breakText Glyphs Glyphes @msg A joint does not close by {gap} pt. Un joint ne se ferme pas, avec un écart de {gap} pt. @msg Two panels pass through each other. Deux panneaux se traversent. @msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution + Orbit Lines Lignes orbitales + Petal Garland Guirlande de pétales + Lattice Braid Tresse en treillis + Facet Sweep Trait à facettes + Artistic Brushes Pinceaux artistiques + Paint Peinture + Flat Sweep Balayage plat + Dry Drag Traînée sèche + Loaded Stroke Trait chargé + Fan Sweep Balayage en éventail + Engraving Gravure + Fine Hatching Hachures fines + Dense Hatching Hachures denses + Tapered Hatching Hachures effilées + Broken Hatching Hachures interrompues Image Brush Pinceaux d’image Soft Bloom Floraison douce Halftone Field Champ de demi-teintes diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 7216b1a4ef..e136632ca0 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -149,6 +149,7 @@ Add Selected Artwork as One Asset પસંદ કરેલી આર્ટવર્ક એક સંપત્તિ તરીકે ઉમેરો Add Spine Point સ્પાઇન બિંદુ ઉમેરો Add Used Colors વપરાયેલા રંગ ઉમેરો + Add Selected Colors પસંદ કરેલા રંગ ઉમેરો Add as Effect ઇફેક્ટ તરીકે ઉમેરો Add space to fit ફિટ કરવા જગ્યા ઉમેરો Add to Brushes બ્રશમાં ઉમેરો @@ -282,6 +283,10 @@ Arc Lower… નીચે આર્ક… Arc Segment Tool Options આર્ક સેગમેન્ટ ટૂલ વિકલ્પો Arc Tool આર્ક ટૂલ + Three-Point Arc Tool ત્રણ-પૉઇન્ટ આર્ક ટૂલ + Three-Point Arc ત્રણ-પૉઇન્ટ આર્ક + Arc too large આર્ક ખૂબ મોટો છે + Third Point Sets Direction ત્રીજો પૉઇન્ટ દિશા નક્કી કરે છે Arc Upper… ઉપર આર્ક… Arch… કમાન… Arc… આર્ક… @@ -2035,6 +2040,12 @@ Knife નાઇફ Knockout Group નૉકઆઉટ ગ્રૂપ LZW Compression LZW કમ્પ્રેશન + OKLCH Sliders OKLCH સ્લાઇડર્સ + HSL Sliders HSL સ્લાઇડર્સ + Chroma ક્રોમા + The largest chroma sRGB holds at this lightness and hue આ લાઇટનેસ અને હ્યૂ પર sRGB સમાવી શકે તે સૌથી વધુ ક્રોમા + OKLCH needs sRGB as the working RGB space OKLCH માટે કાર્યકારી RGB સ્પેસ તરીકે sRGB જરૂરી છે + Lightness લાઇટનેસ Lab Spot Colors: Lab સ્પોટ રંગો: Landscape લેન્ડસ્કેપ Language ભાષા @@ -2902,6 +2913,11 @@ Preserve Alpha Transparency આલ્ફા પારદર્શિતા જાળવો Preserve Appearance and Overprints દેખાવ અને ઓવરપ્રિન્ટ જાળવો Preserve CMYK Numbers CMYK નંબર જાળવો + Preserve RGB Numbers RGB નંબર જાળવો + Device to Simulate: અનુકરણ કરવાનું ઉપકરણ: + Simulate Paper Color કાગળના રંગનું અનુકરણ કરો + Simulate Black Ink કાળી શાહીનું અનુકરણ કરો + Load… લોડ કરો… Preserve Editing Capabilities સંપાદન ક્ષમતાઓ જાળવો Preserve Lightness તેજ જાળવો Preserve Overprints and Spot Colors ઓવરપ્રિન્ટ અને સ્પોટ રંગ જાળવો @@ -3156,6 +3172,37 @@ Remove Effect ઇફેક્ટ દૂર કરો Remove Effects ઇફેક્ટ્સ દૂર કરો Remove Gaps ગેપ દૂર કરો +# Stroke arrowheads (Stroke panel, Dimension Tool Options and Properties › Arrow Style). + Triangle (open) ત્રિકોણ (ખુલ્લો) + Circle (open) વર્તુળ (ખુલ્લું) + Square (open) ચોરસ (ખુલ્લો) + Arrow (open) તીર (ખુલ્લું) + Barbed કાંટાળું +arrowhead Feather પીંછું + Half Arrow (left) અડધું તીર (ડાબે) + Half Arrow (right) અડધું તીર (જમણે) + Double Bar બેવડી પટ્ટી + Dot on Bar પટ્ટી પર બિંદુ + Chevron શેવરોન + Cross ક્રોસ + Plus પ્લસ + Hexagon (open) ષટ્કોણ (ખુલ્લો) + Tag ટૅગ + Tag (open) ટૅગ (ખુલ્લો) + Half Circle અર્ધવર્તુળ + Drop ટીપું + Slash સ્લૅશ + Double Slash બેવડો સ્લૅશ + Diamond (open) ડાયમંડ (ખુલ્લો) + Reverse Triangle ઊંધો ત્રિકોણ + Swallowtail અબાબીલની પૂંછડી + Bracket કૌંસ + Fork કાંટો + Leaf પાંદડું + Kite પતંગ + Triangle to Bar ત્રિકોણથી પટ્ટી + Oval અંડાકાર + Line Arrow રેખા તીર # Path Precision Tools add-on: Common Tangents. Common Tangents… સામાન્ય સ્પર્શરેખાઓ… Common Tangents સામાન્ય સ્પર્શરેખાઓ @@ -3243,6 +3290,8 @@ Reselect ફરી પસંદ કરો Reset રીસેટ કરો Reset Bar Position બાર સ્થિતિ રીસેટ કરો + Bar Actions બાર ક્રિયાઓ + Reset Bar Actions બાર ક્રિયાઓ રીસેટ કરો Reset Bounding Box બાઉન્ડિંગ બોક્સ રીસેટ કરો Rotate Bounding Box બાઉન્ડિંગ બોક્સ ફેરવો Rotate Bounding Box… બાઉન્ડિંગ બોક્સ ફેરવો… @@ -3402,9 +3451,10 @@ Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. લાઇન સેગમેન્ટના છેડાને એ રીતે સ્નેપ કરે છે કે તે નજીકના સીધા સેગમેન્ટને કાટખૂણે મળે. Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. કેનવાસ પર દરેક સ્લાઇસનો નંબર તેના ઉપરના ડાબા ખૂણે એક બૉક્સમાં બતાવે છે; બંધ હોય ત્યારે પણ સ્લાઇસની રૂપરેખાઓ દેખાય છે. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. યુઝર અને ઑબ્જેક્ટ સ્લાઇસની રૂપરેખાઓ અને તેમના નંબર બૉક્સનો રંગ; ઑટો સ્લાઇસ તેની ઝાંખી છાયા વાપરે છે. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. દસ્તાવેજ સેટઅપની ભાષા અંગ્રેજી: USA હોય ત્યાં સુધી નવા ટેક્સ્ટને આ ભાષા મળે છે; દસ્તાવેજમાં પહેલેથી રહેલું ટેક્સ્ટ પોતાની ભાષા રાખે છે. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. હાઇફનેટ કરો ચાલુ હોય તેવા ફકરાઓમાં, સૂચિમાંનો શબ્દ ફક્ત તેમાં લખેલા હાઇફન પર જ તૂટે છે, અથવા કોઈ ન હોય તો ક્યાંય નહીં, તેની ભાષા કે કેસ ગમે તે હોય. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. ડેસ્કટોપ સંસ્કરણમાં, આ ફોલ્ડરના .wasm પ્લગ-ઇન્સ શરૂઆતમાં અને અહીં નવા ફોલ્ડર સાથે ઠીક પર ક્લિક કરો ત્યારે લોડ થાય છે, સેફ મોડ સિવાય; વેબ સંસ્કરણ તેમને લોડ કરતું નથી. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. સામાન્ય દરેક પ્લગ-ઇનની પોતાની મર્યાદાઓ રાખે છે; મોટું સાથે, પ્લગ-ઇન ફિલ્ટર અથવા આદેશ તેના ઇનપુટ માટેની સૂચનાઓ ઉપરાંત ઓછામાં ઓછી 250 મિલિયન સૂચનાઓ ચલાવી શકે છે. સમય મર્યાદા એ જ રહે છે. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. પ્લગ-ઇનના ઑબ્જેક્ટ ફિલ્ટરનું દરેક રન કેટલી સૂચનાઓ વાપરી શકે; મોટું સામાન્ય કરતાં વધુ મંજૂરી આપે છે, 60 સેકન્ડની એ જ મર્યાદા સાથે. ભારે ફિલ્ટર પોતાનું બજેટ રાખે છે. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. પ્રથમ સ્ક્રેચ ડિસ્ક પસંદગી: Startup, None અથવા ફોલ્ડરનો પાથ; VectorCraft તેને સાચવે છે, પરંતુ હજી સ્ક્રેચ ડિસ્કનો ઉપયોગ કરતું નથી. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. બીજી સ્ક્રેચ ડિસ્ક પસંદગી: Startup, None અથવા ફોલ્ડરનો પાથ; VectorCraft તેને સાચવે છે, પરંતુ હજી સ્ક્રેચ ડિસ્કનો ઉપયોગ કરતું નથી. How light or dark the interface is. ઇન્ટરફેસ કેટલું આછું કે ઘેરું છે. @@ -3422,7 +3472,10 @@ The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. ઇન્ટરફેસની ભાષા; ઑટો સિસ્ટમની ભાષા વાપરે છે. તમે ભાષા પસંદ કરો કે તરત જ ડાયલોગ તે ભાષામાં બદલાય છે. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. ઍનિમેટેડ ઝૂમ ફક્ત આ ચાલુ હોય ત્યારે જ કામ કરે છે; બંધ હોય ત્યારે, ઍનિમેટેડ ઝૂમ ઝાંખું થાય છે અને ઝૂમ ઍનિમેટ થતું નથી. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. વ્હીલથી ઝૂમ સરળતાથી સરકે છે, અને ઝૂમ ટૂલ તમે બાજુમાં ખેંચો અથવા દબાવી રાખો ત્યારે ઝૂમ કરે છે; બંધ હોય ત્યારે, ઝૂમ ટૂલ તમે ખેંચો તે વિસ્તાર પર ઝૂમ કરે છે. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. આગલી શરૂઆતથી, ડેસ્કટોપ સંસ્કરણ આ પ્રકારના ગ્રાફિક્સ પ્રોસેસર દ્વારા કેનવાસ બતાવે છે; આર્ટવર્ક હંમેશાં CPU પર દોરાય છે. સ્વચાલિત Windows અને macOS પર સંકલિત પ્રોસેસરને પસંદ કરે છે. વેબ સંસ્કરણ તેનો ઉપયોગ કરતું નથી. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. આગલી શરૂઆતથી, જ્યાં ગ્રાફિક્સ ડ્રાઇવર મંજૂરી આપે ત્યાં વિન્ડો ડિસ્પ્લેના રિફ્રેશની રાહ જોયા વિના દરેક ફ્રેમ બતાવે છે, સેકન્ડ દીઠ વધુમાં વધુ 240 ફ્રેમ. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. આગલી શરૂઆતથી, ડેસ્કટોપ સંસ્કરણ આ પ્રકારના ગ્રાફિક્સ પ્રોસેસરથી દોરે છે; સ્વચાલિત ડિસ્પ્લે ચલાવતા પ્રોસેસરને પસંદ કરે છે. વેબ સંસ્કરણ તેનો ઉપયોગ કરતું નથી. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. આગલી શરૂઆતથી, વિન્ડો ડિસ્પ્લે રિફ્રેશની રાહ જોયા વિના ફ્રેમ બતાવે છે, સેકન્ડમાં વધુમાં વધુ 240; બંધ હોય ત્યારે ગતિ ડિસ્પ્લે નક્કી કરે છે. શરૂઆતમાં સેટ કરેલો પ્રેઝન્ટ મોડ પ્રાથમિકતા ધરાવે છે. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. દરેક દસ્તાવેજ રાખે તે પૂર્વવત્ પગલાંની મહત્તમ સંખ્યા; ઓછી સંખ્યા ઠીક પર ક્લિક કરો ત્યારે સૌથી જૂનાં પગલાં દૂર કરે છે. પગલાં વધુ મેમરી લે ત્યારે વહેલાં પણ દૂર થઈ શકે છે. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. તમે ખેંચો ત્યારે આર્ટ બદલાતી બતાવે છે; બંધ હોય ત્યારે, રૂપરેખાઓ ખેંચાણને અનુસરે છે અને તમે છોડો ત્યારે આર્ટ બદલાય છે. રૂલરની માર્ગદર્શિકા ખેંચતી વખતે હંમેશા ખસે છે. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. કેટલા વર્કર થ્રેડ આર્ટ દોરે છે; -1 VectorCraft વાપરી શકે તે કોરથી એક ઓછો વાપરે છે, વધુમાં વધુ 8, અને 0 એક પણ નહીં. વેબ સંસ્કરણ ક્યારેય કોઈ વાપરતું નથી. @@ -3449,6 +3502,10 @@ VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft આ પસંદગી સાચવે છે, પણ નકલ અને કાપો હજી લેગસી વેક્ટર ક્લિપબોર્ડ ફોર્મેટ વાપરતા નથી. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. લેગસી વેક્ટર ક્લિપબોર્ડ માટે પાથ જાળવો અથવા દેખાવ અને ઓવરપ્રિન્ટ જાળવો; VectorCraft પસંદગી સાચવે છે પણ હજી તેને વાપરતું નથી. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. ફોર્મેટિંગ રાખો VectorCraftના ટેક્સ્ટ ઑબ્જેક્ટમાંથી નકલ કરેલા ટેક્સ્ટને ટેક્સ્ટ ઑબ્જેક્ટમાં ચોંટાડતાં તેની શૈલીઓ રાખે છે; સાદો ટેક્સ્ટ રાખો તેને જ્યાં પડે ત્યાંની શૈલી આપે છે. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. બધા બ્લેક્સ રિચ બ્લેક તરીકે બતાવો કેનવાસ પર શુદ્ધ CMYK બ્લેક (માત્ર 100% બ્લેક શાહી)ને RGB બ્લેક તરીકે બતાવે છે; બધા બ્લેક્સ ચોક્કસ રીતે બતાવો તેને કાર્યકારી CMYK સ્પેસ દ્વારા રૂપાંતરિત કરે છે. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. બધા બ્લેકને રિચ બ્લેક તરીકે આઉટપુટ કરો RGB અને ગ્રેસ્કેલ રાસ્ટર એક્સપોર્ટમાં અને બિટમેપ તરીકે પ્રિન્ટ કરો સાથે શુદ્ધ CMYK બ્લેકને RGB બ્લેક તરીકે દોરે છે; તે વેક્ટર એક્સપોર્ટ, CMYK JPEG, TIFF અને PSD કે અન્ય પ્રિન્ટિંગ બદલતું નથી. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. ટચ સ્ક્રીન પર ટચ વર્કસ્પેસમાં બદલે છે; આ વિકલ્પ બંધ કરવાથી અથવા ટચ સ્ક્રીન ન મળે ત્યારે તે પહેલાંના વર્કસ્પેસમાં પાછું જાય છે. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. કેનવાસ પર બે આંગળીનો ટૅપ પૂર્વવત્ કરે છે, અથવા ટચ વર્કસ્પેસમાં પસંદગી અને ડ્રોઇંગ ટૂલ વચ્ચે બદલે છે, અને ત્રણ આંગળીનો ટૅપ ફરીથી કરે છે; પ્રેઝન્ટેશન મોડમાં બેમાંથી કોઈ કામ કરતું નથી. New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. દસ્તાવેજ સેટઅપની ભાષા અંગ્રેજી: USA હોય અને [Normal Character Style] કોઈ ભાષા સેટ ન કરે ત્યાં સુધી નવા ટેક્સ્ટને આ ભાષા મળે છે; દસ્તાવેજમાં પહેલેથી રહેલું ટેક્સ્ટ પોતાની ભાષા રાખે છે. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. હાઇફનેટ કરો ચાલુ હોય તેવા ફકરાઓમાં, સૂચિમાંનો શબ્દ ફક્ત તેમાં લખેલા હાઇફન પર જ તૂટે છે, અથવા કોઈ ન હોય તો ક્યાંય નહીં, તેનો કેસ ગમે તે હોય; કોરિયન શબ્દોને હાઇફન મળતો નથી, અને ભારતીય ભાષાઓના શબ્દો અક્ષર-સમૂહની અંદર તૂટતા નથી. Restored documents open unsaved: save them to keep them. પુનઃસ્થાપિત દસ્તાવેજો અસાચવેલા ખુલશે: તેમને રાખવા માટે સાચવો. @@ -3959,6 +4016,10 @@ Add Color Tool રંગ ઉમેરો સાધન Remove Color Tool રંગ દૂર કરો સાધન Remove Color રંગ દૂર કરો + Set As Base Color આધાર રંગ તરીકે સેટ કરો + Select Shade છાયા પસંદ કરો + Add New Color નવો રંગ ઉમેરો + Set Current Color As Base Color વર્તમાન રંગને આધાર રંગ તરીકે સેટ કરો Find the selected colors in the artwork પસંદ કરેલા રંગો આર્ટવર્કમાં શોધો Show handles when multiple anchors are selected બહુવિધ એન્કર પસંદ હોય ત્યારે હૅન્ડલ બતાવો Show in Folder ફોલ્ડરમાં બતાવો @@ -5061,6 +5122,7 @@ antiAlias Sharp શાર્પ Composition કમ્પોઝિશન Place Brush Art બ્રશ આર્ટ પ્લેસ કરો Replace Brush Art બ્રશ આર્ટ બદલો + Replace Pattern Art પેટર્ન આર્ટ બદલો Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? સ્ટ્રોક્સ આ બ્રશ વાપરે છે. તે સ્ટ્રોક્સ પર નવી આર્ટ લાગુ કરવી છે કે તેમને જેમ છે તેમ રાખીને નવી આર્ટવાળી બ્રશની નકલ ઉમેરવી છે? Apply to Strokes સ્ટ્રોક્સ પર લાગુ કરો Leave Strokes સ્ટ્રોક્સ જેમ છે તેમ રાખો @@ -5582,6 +5644,25 @@ swatch [Registration] [રજિસ્ટ્રેશન] Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર Standard Every-line Composer સ્ટાન્ડર્ડ એવરી-લાઇન કમ્પોઝર @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer આમાંથી એક હોવું જોઈએ: "singleLine", "everyLine", "standardSingleLine" અથવા "standardEveryLine" + Orbit Lines ભ્રમણકક્ષાની રેખાઓ + Petal Garland પાંખડીઓની માળા + Lattice Braid જાળી વેણી + Facet Sweep પાસાદાર રેખા + Artistic Brushes કલાત્મક બ્રશ + Paint રંગકામ + Flat Sweep સપાટ લસરકો + Dry Drag સૂકો ઘસારો + Loaded Stroke ઘાટો પીંછીનો ઘસારો + Fan Sweep પંખા જેવો લસરકો +@msg `at` must be "start" or "end" `at` "start" અથવા "end" હોવું જોઈએ +@msg give exactly one of `through` and `toward` `through` અને `toward` માંથી બરાબર એક આપો +@msg no arc fits these points: two are the same or all three lie on one line આ પૉઇન્ટ્સમાં કોઈ આર્ક બેસતો નથી: બે એકસરખા છે અથવા ત્રણેય એક જ રેખા પર છે +@msg give `at` only with `toward` `at` ફક્ત `toward` સાથે જ આપો + Engraving કોતરણી + Fine Hatching ઝીણી રેખાઓ + Dense Hatching ગાઢ રેખાઓ + Tapered Hatching પાતળી થતી રેખાઓ + Broken Hatching તૂટક રેખાઓ Image Brush છબી બ્રશ Soft Bloom નરમ ફૂલ Halftone Field હાફટોન ક્ષેત્ર diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index b75244fafa..f10a0cae0e 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -255,6 +255,7 @@ Add to Symbols सिंबल्स में जोड़ें Add to the Current Shortcuts वर्तमान शॉर्टकट में जोड़ें Add Used Colors उपयोग किए रंग जोड़ें + Add Selected Colors सिलेक्टेड रंग जोड़ें Additional Fonts Folder अतिरिक्त फ़ॉन्ट फ़ोल्डर Additional Plug-ins Folder अतिरिक्त प्लग-इन फ़ोल्डर Plug-in Instruction Budget प्लग-इन निर्देश बजट @@ -397,6 +398,10 @@ antiAlias Sharp शार्प Arc Lower… निचला आर्क… Arc Segment Tool Options आर्क सेगमेंट टूल ऑप्शन्स Arc Tool आर्क टूल + Three-Point Arc Tool थ्री-पॉइंट आर्क टूल + Three-Point Arc थ्री-पॉइंट आर्क + Arc too large आर्क बहुत बड़ा है + Third Point Sets Direction तीसरा पॉइंट दिशा तय करता है Arc Upper… ऊपरी आर्क… Arc… आर्क… Arch… मेहराब… @@ -811,6 +816,7 @@ antiAlias Sharp शार्प Bar बार Bar Graph Tool बार ग्राफ़ टूल Barbed कंटीले +arrowhead Feather पंख Bas Relief बास रिलीफ़ Bas Relief… बास रिलीफ़… Base Along: आधार के साथ: @@ -2995,6 +3001,11 @@ antiAlias Sharp शार्प Knife चाकू Knockout Group नॉकआउट समूह Lab Lab + OKLCH Sliders OKLCH स्लाइडर्स + HSL Sliders HSL स्लाइडर्स + Chroma क्रोमा + The largest chroma sRGB holds at this lightness and hue इस लाइटनेस और ह्यू पर sRGB में आने वाला सबसे अधिक क्रोमा + OKLCH needs sRGB as the working RGB space OKLCH के लिए वर्किंग RGB स्पेस sRGB होना चाहिए Lab Spot Colors लैब स्पॉट रंग Lab Spot Colors: लैब स्पॉट रंग: Lab Values लैब मूल्य @@ -3113,6 +3124,7 @@ antiAlias Sharp शार्प Limit: सीमा: Limited लिमिटेड Line लाइन + Line Arrow लाइन तीर line {line} लाइन {line} Line {line} लाइन {line} Line {line}: {name}: {status} लाइन {line}: {name}: {status} @@ -4165,6 +4177,11 @@ antiAlias Sharp शार्प Preserve Appearance उपस्थिति संरक्षित करें Preserve Appearance and Overprints उपस्थिति और ओवरप्रिंट को संरक्षित करें Preserve CMYK Numbers CMYK नंबर संरक्षित करें + Preserve RGB Numbers RGB नंबर संरक्षित करें + Device to Simulate: सिम्युलेट करने के लिए डिवाइस: + Simulate Paper Color पेपर का रंग सिम्युलेट करें + Simulate Black Ink काली स्याही सिम्युलेट करें + Load… लोड करें… Preserve editing capabilities संपादन क्षमताओं को संरक्षित करना Preserve Editing Capabilities संपादन क्षमताओं को संरक्षित करना Preserve Lightness प्रकाश संरक्षण @@ -4491,6 +4508,7 @@ antiAlias Sharp शार्प Remove Strokes स्ट्रोक हटाएँ Place Brush Art ब्रश आर्टवर्क रखें Replace Brush Art ब्रश आर्टवर्क बदलें + Replace Pattern Art पैटर्न आर्टवर्क बदलें Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? स्ट्रोक्स इस ब्रश का उपयोग कर रहे हैं। नया आर्टवर्क उन स्ट्रोक्स पर लागू करें, या उन्हें जैसा है वैसा छोड़कर नए आर्टवर्क वाले ब्रश की एक कॉपी जोड़ें? Apply to Strokes स्ट्रोक्स पर लागू करें Leave Strokes स्ट्रोक्स जैसे हैं वैसे छोड़ें @@ -4562,6 +4580,8 @@ antiAlias Sharp शार्प Reset all Revolve settings to their defaults. सभी रिवॉल्व सेटिंग्स डिफ़ॉल्ट पर रीसेट करें। Reset Automation स्वचालन रीसेट करें Reset Bar Position बार स्थिति रीसेट करें + Bar Actions बार क्रियाएँ + Reset Bar Actions बार क्रियाएँ रीसेट करें Reset Bounding Box बाउंडिंग बॉक्स रीसेट करें Rotate Bounding Box बाउंडिंग बॉक्स घुमाएँ Rotate Bounding Box… बाउंडिंग बॉक्स घुमाएँ… @@ -4747,9 +4767,10 @@ antiAlias Sharp शार्प Edit type set in fonts that aren't available? जो फ़ॉन्ट उपलब्ध नहीं हैं, उनमें सेट टेक्स्ट एडिट करें? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. कैनवास पर हर स्लाइस का नंबर उसके ऊपरी बाएँ कोने में एक बॉक्स में दिखाता है; बंद होने पर भी स्लाइस की आउटलाइन दिखती रहती हैं। The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. यूज़र और ऑब्जेक्ट स्लाइस की आउटलाइन और उनके नंबर बॉक्स का रंग; ऑटो स्लाइस इसकी हल्की छाया इस्तेमाल करते हैं। - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. जब तक डॉक्यूमेंट सेटअप की भाषा अंग्रेज़ी: USA है, नए टेक्स्ट को यह भाषा मिलती है; डॉक्यूमेंट में पहले से मौजूद टेक्स्ट अपनी भाषा रखता है। In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. जिन पैराग्राफ़ में हाइफ़नेशन चालू है, उनमें सूची का शब्द केवल उसमें टाइप किए गए हाइफ़न पर टूटता है, या कोई न हो तो कहीं नहीं, उसकी भाषा या केस चाहे जो हो। On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. डेस्कटॉप संस्करण में, इस फ़ोल्डर के .wasm प्लग-इन शुरू होने पर और यहाँ नया फ़ोल्डर देकर ठीक है पर क्लिक करने पर लोड होते हैं, सुरक्षित मोड को छोड़कर; वेब संस्करण उन्हें लोड नहीं करता। + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. सामान्य हर प्लग-इन की अपनी सीमाएँ रखता है; बड़ा के साथ, प्लग-इन फ़िल्टर या कमांड अपने इनपुट के निर्देशों के अलावा कम से कम 250 मिलियन निर्देश चला सकता है। समय सीमा वही रहती है। + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. प्लग-इन के ऑब्जेक्ट फ़िल्टर का हर रन कितने निर्देश इस्तेमाल कर सकता है; बड़ा सामान्य से अधिक की अनुमति देता है, 60 सेकंड की उसी सीमा के साथ। भारी फ़िल्टर अपना बजट रखते हैं। The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. पहला स्क्रैच डिस्क विकल्प: Startup, None या फ़ोल्डर पाथ; VectorCraft इसे सहेजता है, पर अभी स्क्रैच डिस्क का उपयोग नहीं करता। The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. दूसरा स्क्रैच डिस्क विकल्प: Startup, None या फ़ोल्डर पाथ; VectorCraft इसे सहेजता है, पर अभी स्क्रैच डिस्क का उपयोग नहीं करता। How light or dark the interface is. इंटरफ़ेस कितना हल्का या गहरा है। @@ -4767,7 +4788,10 @@ antiAlias Sharp शार्प The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. इंटरफ़ेस की भाषा; स्वचालित सिस्टम की भाषा इस्तेमाल करता है। आप कोई भाषा चुनते ही डायलॉग उस भाषा में बदल जाता है। Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. एनिमेटेड ज़ूम केवल तभी काम करता है जब यह चालू हो; बंद होने पर, एनिमेटेड ज़ूम धुंधला हो जाता है और ज़ूम एनिमेट नहीं होता। The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. व्हील से ज़ूम सहजता से सरकता है, और ज़ूम टूल बगल में खींचने या दबाए रखने पर ज़ूम करता है; बंद होने पर, ज़ूम टूल उस क्षेत्र पर ज़ूम करता है जिस पर आप खींचते हैं। + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. अगली शुरुआत से, डेस्कटॉप संस्करण इस प्रकार के ग्राफ़िक्स प्रोसेसर के ज़रिए कैनवास दिखाता है; आर्टवर्क हमेशा CPU पर बनता है। स्वचालित Windows और macOS पर इंटीग्रेटेड प्रोसेसर को प्राथमिकता देता है। वेब संस्करण इसका उपयोग नहीं करता। + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. अगली शुरुआत से, जहाँ ग्राफ़िक्स ड्राइवर अनुमति देता है, विंडो डिस्प्ले के रीफ़्रेश की प्रतीक्षा किए बिना हर फ़्रेम दिखाती है, अधिकतम 240 फ़्रेम प्रति सेकंड। From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. अगली शुरुआत से, डेस्कटॉप संस्करण इस प्रकार के ग्राफ़िक्स प्रोसेसर से बनाता है; स्वचालित उस प्रोसेसर को प्राथमिकता देता है जो डिस्प्ले चलाता है। वेब संस्करण इसका उपयोग नहीं करता। + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. अगली शुरुआत से, विंडो डिस्प्ले रीफ़्रेश का इंतज़ार किए बिना फ़्रेम दिखाती है, एक सेकंड में अधिकतम 240; बंद होने पर गति डिस्प्ले तय करता है। शुरुआत पर सेट किया गया प्रेज़ेंट मोड प्राथमिकता रखता है। The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. हर दस्तावेज़ अधिकतम जितने पूर्ववत चरण रखता है; कम संख्या ठीक है पर क्लिक करने पर सबसे पुराने चरण हटा देती है। ज़्यादा मेमोरी लेने पर चरण पहले भी हट सकते हैं। Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. खींचते समय आर्टवर्क को बदलते हुए दिखाता है; बंद होने पर, रूपरेखाएँ खींचने के साथ चलती हैं और छोड़ने पर आर्टवर्क बदलता है। रूलर गाइड खींचते समय हमेशा चलती है। How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. कितने वर्कर थ्रेड आर्टवर्क बनाते हैं; -1 उन कोर से एक कम उपयोग करता है जिन्हें VectorCraft उपयोग कर सकता है, अधिकतम 8, और 0 एक भी नहीं। वेब संस्करण कभी कोई उपयोग नहीं करता। @@ -4794,6 +4818,10 @@ antiAlias Sharp शार्प VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft यह विकल्प सेव करता है, लेकिन कॉपी करें और काटें अभी विरासत वेक्टर क्लिपबोर्ड फ़ॉर्मेट का उपयोग नहीं करते। Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. विरासत वेक्टर क्लिपबोर्ड के लिए “संरक्षित पाथ” (पाथ संरक्षित रखें) या “उपस्थिति और ओवरप्रिंट को संरक्षित करें”; VectorCraft विकल्प सेव करता है, पर अभी उसका उपयोग नहीं करता। Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. स्वरूपण रखना, VectorCraft के टेक्स्ट ऑब्जेक्ट से कॉपी किया टेक्स्ट टेक्स्ट ऑब्जेक्ट में पेस्ट करने पर उसकी शैलियाँ रखता है; प्लेन टेक्स्ट रखें उसे पेस्ट की जगह की शैली देता है। + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. सभी ब्लैक्स को रिच ब्लैक के रूप में प्रदर्शित करें, कैनवास पर शुद्ध CMYK ब्लैक (केवल 100% काली स्याही) को RGB ब्लैक के रूप में दिखाता है; सभी ब्लैक्स को सटीक रूप से प्रदर्शित करें उसे कार्य CMYK स्पेस के ज़रिए बदलता है। + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. सभी ब्लैक्स को रिच ब्लैक के रूप में आउटपुट करें, RGB और ग्रेस्केल रास्टर एक्सपोर्ट और बिटमैप के रूप में प्रिंट करें में शुद्ध CMYK ब्लैक को RGB ब्लैक के रूप में बनाता है; यह वेक्टर एक्सपोर्ट, CMYK JPEG, TIFF और PSD या अन्य प्रिंटिंग को नहीं बदलता। + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. टच स्क्रीन पर टच वर्कस्पेस पर बदलता है; यह विकल्प बंद करने या टच स्क्रीन न मिलने पर पिछले वर्कस्पेस पर लौट आता है। + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. कैनवास पर दो उँगलियों का टैप पूर्ववत करता है, या टच वर्कस्पेस में सिलेक्शन और ड्रॉइंग टूल के बीच बदलता है, और तीन उँगलियों का टैप फिर से करता है; प्रस्तुति मोड में दोनों काम नहीं करते। New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. जब तक डॉक्यूमेंट सेटअप की भाषा अंग्रेज़ी: USA है और [सामान्य कैरेक्टर स्टाइल] कोई भाषा सेट नहीं करती, नए टेक्स्ट को यह भाषा मिलती है; डॉक्यूमेंट में पहले से मौजूद टेक्स्ट अपनी भाषा रखता है। In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. जिन पैराग्राफ़ में हाइफ़नेशन चालू है, उनमें सूची का शब्द केवल उसमें टाइप किए गए हाइफ़न पर टूटता है, या कोई न हो तो कहीं नहीं, उसका केस चाहे जो हो; कोरियाई शब्दों में हाइफ़न नहीं लगता, और भारतीय भाषाओं के शब्द किसी अक्षर-समूह के भीतर नहीं टूटते। Reset all preferences to their defaults? सभी प्रेफ़रेंसेज़ को उनके डिफ़ॉल्ट पर रीसेट करें? @@ -5335,6 +5363,10 @@ antiAlias Sharp शार्प Add Color Tool रंग जोड़ें टूल Remove Color Tool रंग हटाएँ टूल Remove Color रंग हटाएँ + Set As Base Color आधार रंग के रूप में सेट करें + Select Shade शेड चुनें + Add New Color नया रंग जोड़ें + Set Current Color As Base Color वर्तमान रंग को आधार रंग के रूप में सेट करें Find the selected colors in the artwork चयनित रंगों को आर्टवर्क में खोजें Show Color Groups रंग समूह दिखाएँ Show Color Swatches रंग स्वॉचेस दिखाएँ @@ -7041,6 +7073,8 @@ antiAlias Sharp शार्प @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` को grayscale, rgb, hsb, cmyk या websafe होना चाहिए @msg `view` must be wheel or box `view` को wheel या box होना चाहिए @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` को hue, saturation, brightness, red, green या blue होना चाहिए +@msg `sliders` must be none, oklch or hsl `sliders` none, oklch या hsl होना चाहिए +@msg OKLCH needs sRGB as the working RGB space OKLCH के लिए वर्किंग RGB स्पेस sRGB होना चाहिए @msg `mode` must be one of {_1} `mode` को {_1} में से एक होना चाहिए @msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" या "lineEndHalf" होना चाहिए। @msg `name` is empty `name` खाली है @@ -8283,6 +8317,10 @@ liquify-list-end {0}, {1} {0} और {1} @msg a guide has no curvature circle गाइड का कोई वक्रता वृत्त नहीं होता @msg the circle that matches the path there would reach past the canvas वहाँ पाथ से मेल खाने वाला वृत्त कैनवास से बाहर चला जाएगा @msg no circle passes through these points: two are the same or all three lie on one line इन पॉइंट्स से होकर कोई वृत्त नहीं गुज़रता: दो एक जैसे हैं या तीनों एक ही रेखा पर हैं +@msg `at` must be "start" or "end" `at` को "start" या "end" होना चाहिए। +@msg give exactly one of `through` and `toward` `through` और `toward` में से ठीक एक दें +@msg no arc fits these points: two are the same or all three lie on one line इन पॉइंट्स पर कोई आर्क फ़िट नहीं होता: दो एक जैसे हैं या तीनों एक ही रेखा पर हैं +@msg give `at` only with `toward` `at` केवल `toward` के साथ दें @msg no app to open files here यहां फ़ाइलों को ओपन करने के लिए कोई ऐप नहीं है @msg no appearance item {index} कोई उपस्थिति आइटम {index} @msg no artboard कोई आर्टबोर्ड नहीं @@ -8391,6 +8429,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg no parent layer कोई अभिभावक लेयर नहीं @msg no Pathfinder operation applied yet अभी तक कोई पाथफाइंडर ऑपरेशन लागू नहीं है @msg no pattern `{name}` कोई पैटर्न `{name}` नहीं +@msg art painted with `{name}` can't be its tile `{name}` से रंगी कला उसकी टाइल नहीं हो सकती @msg no pattern named `{choice}` `{choice}` नाम का कोई पैटर्न नहीं @msg no pattern swatch `{name}` कोई पैटर्न स्वॉच `{name}` नहीं @msg no PDF preset named `{n}` कोई PDF प्रीसेट नहीं है जिसका नाम `{n}` है @@ -10324,6 +10363,21 @@ theme Appearance अपीयरेंस @msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है। @msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है। @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, हिंज: {hinges}, एरर: {errors}, वॉर्निंग: {warnings} + Orbit Lines कक्षीय रेखाएँ + Petal Garland पंखुड़ी माला + Lattice Braid जाली चोटी + Facet Sweep पहलूदार स्ट्रोक + Artistic Brushes कलात्मक ब्रश + Paint चित्रकारी + Flat Sweep सपाट फेरा + Dry Drag सूखा घिसाव + Loaded Stroke गाढ़ा ब्रश स्ट्रोक + Fan Sweep पंखे जैसा फेरा + Engraving नक्काशी + Fine Hatching बारीक रेखांकन + Dense Hatching घना रेखांकन + Tapered Hatching पतला होता रेखांकन + Broken Hatching टूटा रेखांकन Image Brush छवि ब्रश Soft Bloom कोमल खिलावट Halftone Field हाफ़टोन क्षेत्र diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 030f9a99bf..75abe00c39 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -209,6 +209,7 @@ Add to Selection Hozzáadás a kijelöléshez Add to Swatches Hozzáadás a színmintákhoz Add Used Colors Használt színek hozzáadása + Add Selected Colors Kijelölt színek hozzáadása Additional Fonts Folder További betűtípusok mappája Additional Plug-ins Folder További bővítmények mappája Plug-in Instruction Budget Bővítmények utasításkerete @@ -321,6 +322,10 @@ font-technology Variable Változó Arc Ív Arc Lower… Alsó ív… Arc Tool Ív + Three-Point Arc Tool Hárompontos ív eszköz + Three-Point Arc Hárompontos ív + Arc too large Az ív túl nagy + Third Point Sets Direction A harmadik pont adja meg az irányt Arc Upper… Felső ív… Arch… Boltív… Arc… Ív… @@ -409,6 +414,8 @@ font-technology Variable Változó Bar Vonal Bar Graph Tool Sávdiagram Barbed Szakállas +arrowhead Feather Tollazat +arrowhead Target Céltábla Baseline Alapvonal Baseline (Standard) Alapvonali (szabványos) Baseline Optimized Alapvonali, optimalizált @@ -2118,6 +2125,10 @@ file-filter Templates Sablonok Add Color Tool Szín hozzáadása eszköz Remove Color Tool Szín eltávolítása eszköz Remove Color Szín eltávolítása + Set As Base Color Beállítás alapszínként + Select Shade Árnyalat kiválasztása + Add New Color Új szín hozzáadása + Set Current Color As Base Color Aktuális szín beállítása alapszínként Find the selected colors in the artwork A kijelölt színek keresése a grafikában Harmony Sets Harmóniakészletek HDTV 1080p HDTV 1080p @@ -2510,6 +2521,11 @@ file-filter Templates Sablonok Knife Kés Knockout Group Kiütő csoport Lab Lab + OKLCH Sliders OKLCH csúszkák + HSL Sliders HSL csúszkák + Chroma Króma + The largest chroma sRGB holds at this lightness and hue A legnagyobb króma, amelyet az sRGB ezen a világosságon és színárnyalaton tartalmaz + OKLCH needs sRGB as the working RGB space Az OKLCH-hoz sRGB munka-RGB-színtér szükséges Lab Spot Colors Lab-direktszínek Lab Spot Colors: Lab-direktszínek: Lab Values Lab-értékek @@ -2609,6 +2625,7 @@ file-filter Templates Sablonok Limit: Határ: Limited Korlátozott Line Vonal + Line Arrow Vonalas nyíl Line Art Vonalas rajz Line Art and Text Resolution: Vonalas grafika és szöveg felbontása: Line Breaks Sortörések @@ -3430,6 +3447,11 @@ diagnostics ui felület Preserve Appearance Megjelenés megőrzése Preserve Appearance and Overprints Megjelenés és felülnyomások megtartása Preserve CMYK Numbers CMYK-értékek megtartása + Preserve RGB Numbers RGB-értékek megtartása + Device to Simulate: Szimulálandó eszköz: + Simulate Paper Color Papírszín szimulálása + Simulate Black Ink Fekete festék szimulálása + Load… Betöltés… Preserve editing capabilities Szerkeszthetőség megtartása Preserve Editing Capabilities Szerkeszthetőség megtartása Preserve Lightness Világosság megtartása @@ -3771,6 +3793,8 @@ mark-style Japanese Japán Reset all Revolve settings to their defaults. A tengely körüli forgatás minden beállítását visszaállítja az alapértékre. Reset Automation Automation visszaállítása Reset Bar Position Sáv helyének visszaállítása + Bar Actions Sáv műveletei + Reset Bar Actions Sáv műveleteinek visszaállítása Reset Bounding Box Befoglaló keret visszaállítása Rotate Bounding Box Befoglaló keret elforgatása Rotate Bounding Box… Befoglaló keret elforgatása… @@ -3952,9 +3976,10 @@ mark-style Japanese Japán Edit type set in fonts that aren't available? Szerkeszti a nem elérhető betűtípusokkal szedett szöveget? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. A vásznon minden szelet számát egy keretben mutatja a szelet bal felső sarkában; kikapcsolva a szeletek körvonalai továbbra is látszanak. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. A felhasználói és objektumszeletek körvonalainak és számkereteinek színe; az automatikus szeletek ennek egy halványabb árnyalatát használják. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Az új szöveg ezt a nyelvet kapja, amíg a Dokumentumbeállítás nyelve Angol: amerikai; a dokumentumban már meglévő szöveg megtartja a saját nyelvét. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. Azokban a bekezdésekben, ahol az Elválasztás be van kapcsolva, a felsorolt szó csak a beleírt kötőjeleknél válik el, vagy sehol, ha nincs benne, nyelvétől és kis- vagy nagybetűitől függetlenül. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. Az asztali változatban a mappa .wasm bővítményei indításkor töltődnek be, és amikor itt új mappával az OK gombra kattint, kivéve csökkentett módban; a webes változat nem tölti be őket. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. A Normál megtartja minden bővítmény saját korlátait; a Nagy beállítással egy bővítményszűrő vagy -parancs legalább 250 millió utasítást futtathat a bemenetéhez tartozókon felül. Az időkorlát nem változik. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Hány utasítást használhat egy bővítmény objektumszűrőjének egy-egy futása; a Nagy többet enged, mint a Normál, ugyanazzal a 60 másodperces korláttal. A nehéz szűrők megtartják saját keretüket. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Az első munkalemez-választás: Startup, None vagy egy mappa elérési útja; a VectorCraft tárolja, de munkalemezeket még nem használ. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. A második munkalemez-választás: Startup, None vagy egy mappa elérési útja; a VectorCraft tárolja, de munkalemezeket még nem használ. How light or dark the interface is. Milyen világos vagy sötét a felület. @@ -3972,7 +3997,10 @@ mark-style Japanese Japán The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. A felület nyelve; az Automatikus a rendszer nyelvét használja. A párbeszédablak azonnal nyelvet vált, amint választ egyet. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Az Animált nagyítás csak akkor működik, ha ez be van kapcsolva; kikapcsolva az Animált nagyítás halvány, és a nagyítás nem animált. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. A görgős nagyítás simán úszik be, a Nagyító pedig akkor nagyít, amikor oldalra húz vagy lenyomva tartja; kikapcsolva a Nagyító arra a területre nagyít, amelyen áthúz. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. A következő indítástól az asztali változat ilyen típusú grafikus processzoron keresztül jeleníti meg a vásznat; a grafikát minden esetben a CPU rajzolja. Az Automatikus Windowson és macOS-en az integráltat részesíti előnyben. A webes változat nem használja. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. A következő indítástól az ablak minden képkockát a kijelző frissítésének kivárása nélkül jelenít meg, ahol a grafikus illesztőprogram engedi, legfeljebb másodpercenként 240 képkockát. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. A következő indítástól az asztali változat ilyen típusú grafikus processzorral rajzol; az Automatikus a kijelzőt meghajtót részesíti előnyben. A webes változat nem használja. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. A következő indítástól az ablak a képkockákat a kijelző frissítésére várás nélkül jeleníti meg, legfeljebb másodpercenként 240-et; kikapcsolva a kijelző diktálja az ütemet. Az indításkor megadott megjelenítési mód felülírja. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. A dokumentumonként megőrzött visszavonási lépések legnagyobb száma; kisebb szám az OK gombra kattintáskor törli a legrégebbi lépéseket. A lépések korábban is törlődhetnek, ha túl sok memóriát foglalnak. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Húzás közben mutatja a grafika változását; kikapcsolva körvonalak követik a húzást, és a grafika elengedéskor változik. A vonalzó segédvonala húzás közben mindig mozog. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Hány munkaszál rajzolja a grafikát; a -1 eggyel kevesebbet használ, mint ahány magot a VectorCraft használhat, legfeljebb 8-at, a 0 egyet sem. A webes változat soha nem használ egyet sem. @@ -3999,6 +4027,10 @@ mark-style Japanese Japán VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. A VectorCraft menti ezt a választást, de a Másolás és a Kivágás még nem használ régi vektoros vágólapformátumot. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Útvonalak megtartása vagy Megjelenés és felülnyomások megtartása a régi vektoros vágólaphoz; a VectorCraft menti a választást, de még nem használja. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. A Formázás megtartása megőrzi a VectorCraft szövegobjektumából másolt szöveg stílusait, amikor szövegobjektumba illesztik; a Csak a szöveg megtartása a beillesztés helyének stílusát adja neki. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. A Minden fekete megjelenítése mélyfeketeként a tiszta CMYK feketét (csak fekete festék 100%-on) RGB feketeként mutatja a vásznon; a Minden fekete pontos megjelenítése a munka-CMYK színtéren keresztül alakítja át. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. A Minden fekete kimenete mélyfeketeként a tiszta CMYK feketét RGB feketeként rajzolja az RGB és szürkeárnyalatos raszteres exportokban és a Nyomtatás bitképként beállítással; nem változtatja meg a vektoros exportokat, a CMYK JPEG, TIFF és PSD fájlokat és a többi nyomtatást. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Bekapcsolva érintőképernyőn az érintéses munkaterületre vált; kikapcsolásakor, vagy ha az érintőképernyő már nem érhető el, visszavált az előző munkaterületre. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Bekapcsolva a kétujjas koppintás a vásznon visszavon, az érintéses munkaterületen pedig a kijelölő és a rajzoló eszközök között vált, a háromujjas koppintás újra végrehajt; bemutató módban egyik sem működik. New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Az új szöveg ezt a nyelvet kapja, amíg a Dokumentumbeállítás nyelve Angol: amerikai, és a [Normál karakterstílus] nem állít be nyelvet; a dokumentumban már meglévő szöveg megtartja a saját nyelvét. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. Azokban a bekezdésekben, ahol az Elválasztás be van kapcsolva, a felsorolt szó csak a beleírt kötőjeleknél válik el, vagy sehol, ha nincs benne, kis- vagy nagybetűitől függetlenül; a koreai szavak nem kapnak kötőjelet, az indiai nyelvű szavak pedig nem válnak el egy karaktercsoporton belül. Reset all preferences to their defaults? Visszaállítja az összes beállítást az alapértékre? @@ -5500,6 +5532,8 @@ imageTrace Outline Körvonal @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`: grayscale, rgb, hsb, cmyk vagy websafe kell @msg `view` must be wheel or box `view`: wheel vagy box kell @msg `channel` must be hue, saturation, brightness, red, green or blue `channel`: hue, saturation, brightness, red, green vagy blue kell +@msg `sliders` must be none, oklch or hsl A `sliders` értéke none, oklch vagy hsl lehet +@msg OKLCH needs sRGB as the working RGB space Az OKLCH-hoz sRGB munka-RGB-színtér szükséges @msg `{k}` must be [x, y] `{k}`: [x, y] kell @msg `{name}` has no options ennek nincsenek beállításai: `{name}` @msg `{name}` is a built-in workspace; choose another name beépített munkaterület: `{name}`; válassz másik nevet @@ -6041,6 +6075,10 @@ liquify-list-end {0}, {1} {0} és {1} @msg a guide has no curvature circle a segédvonalnak nincs görbületi köre @msg the circle that matches the path there would reach past the canvas az útvonalhoz ott illeszkedő kör túlnyúlna a vásznon @msg no circle passes through these points: two are the same or all three lie on one line ezeken a pontokon nem halad át kör: kettő egybeesik, vagy mindhárom egy egyenesen van +@msg `at` must be "start" or "end" `at`: "start" vagy "end" kell +@msg give exactly one of `through` and `toward` pontosan egyet adjon meg a `through` és a `toward` közül +@msg no arc fits these points: two are the same or all three lie on one line ezekre a pontokra nem illeszkedik ív: kettő egybeesik, vagy mindhárom egy egyenesen van +@msg give `at` only with `toward` az `at` csak a `toward` mellett adható meg @msg no app to open files here itt nincs fájlmegnyitó alkalmazás @msg no artboard nincs rajztábla @msg no artboard {i} (0-based; the document has {_1}) nincs ilyen sorszámú rajztábla: {i} (0-tól számozva; a dokumentumban ennyi van: {_1}) @@ -6092,6 +6130,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg no native format nincs natív formátum @msg no pages nincsenek oldalak @msg no pattern `{name}` nincs ilyen mintázat: `{name}` +@msg art painted with `{name}` can't be its tile a(z) `{name}` mintázattal festett grafika nem lehet annak csempéje @msg no perspective grid preset named `{name}` nincs ilyen nevű perspektivikusrács-előbeállítás: `{name}` @msg no plug-in {0} is installed nincs telepítve ilyen bővítmény: {0} @msg no plug-in {id} is installed nincs telepítve ilyen bővítmény: {id} @@ -8281,6 +8320,7 @@ breakText Glyphs Glifák Remove Strokes Körvonalak eltávolítása Place Brush Art Ecsetgrafika elhelyezése Replace Brush Art Ecsetgrafika cseréje + Replace Pattern Art Mintázatgrafika cseréje Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Körvonalak használják ezt az ecsetet. Alkalmazod az új grafikát ezekre a körvonalakra, vagy változatlanul hagyod őket, és hozzáadod az ecset egy másolatát az új grafikával? Apply to Strokes Alkalmazás a körvonalakra Leave Strokes Körvonalak megtartása @@ -10706,6 +10746,21 @@ breakText Glyphs Glifák @msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez. @msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, zsanérok: {hinges}, hibák: {errors}, figyelmeztetések: {warnings} + Orbit Lines Pályavonalak + Petal Garland Sziromfüzér + Lattice Braid Rácsfonat + Facet Sweep Fazettás vonás + Artistic Brushes Művészi ecsetek + Paint Festék + Flat Sweep Lapos húzás + Dry Drag Száraz húzás + Loaded Stroke Telített ecsetvonás + Fan Sweep Legyezővonás + Engraving Metszet + Fine Hatching Finom vonalkázás + Dense Hatching Sűrű vonalkázás + Tapered Hatching Elvékonyodó vonalkázás + Broken Hatching Szaggatott vonalkázás Image Brush Képecsetek Soft Bloom Lágy virágzás Halftone Field Féltónusmező diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index ee6b52b823..898f7b39ae 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1384,6 +1384,8 @@ Contextual Task Bar Bilah tugas kontekstual Pin Bar Position Sematkan posisi bilah Reset Bar Position Atur ulang posisi bilah + Bar Actions Tindakan bilah + Reset Bar Actions Atur ulang tindakan bilah Tools Alat Toolbars Bilah alat Advanced Lanjutan @@ -2061,6 +2063,10 @@ lighting Light Cahaya Add Anchor Point Tool Alat tambah titik jangkar Anchor Point Tool Alat titik jangkar Arc Tool Alat busur + Three-Point Arc Tool Alat busur tiga titik + Three-Point Arc Busur tiga titik + Arc too large Busur terlalu besar + Third Point Sets Direction Titik ketiga menentukan arah Area Graph Tool Alat grafik area Area Type Tool Alat teks area Artboard Tool Alat artboard @@ -3504,6 +3510,11 @@ digits Malayalam Malayalam Place the pages with the placement again Tempatkan halaman lagi dengan penempatan tersebut Placement: Penempatan: Preserve CMYK Numbers Pertahankan angka CMYK + Preserve RGB Numbers Pertahankan angka RGB + Device to Simulate: Perangkat yang disimulasikan: + Simulate Paper Color Simulasikan warna kertas + Simulate Black Ink Simulasikan tinta hitam + Load… Muat… Previous page Halaman sebelumnya Print Layers: Lapisan cetak: Print Preset: Preset cetak: @@ -3581,6 +3592,10 @@ digits Malayalam Malayalam Add Color Tool Alat Tambah Warna Remove Color Tool Alat Hapus Warna Remove Color Hapus Warna + Set As Base Color Atur sebagai Warna Dasar + Select Shade Pilih Corak + Add New Color Tambah Warna Baru + Set Current Color As Base Color Atur Warna Saat Ini sebagai Warna Dasar Find the selected colors in the artwork Temukan warna yang dipilih di karya seni Harmony Rules Aturan harmoni Keep this row's colors (exclude) Pertahankan warna baris ini (kecualikan) @@ -4758,6 +4773,7 @@ theme Appearance Tampilan Add to Graphic Styles Tambahkan ke gaya grafis Graphic Style Library Pustaka gaya grafis Add Used Colors Tambahkan warna yang digunakan + Add Selected Colors Tambahkan warna terpilih Delete Swatch Hapus sampel Duplicate Swatch Duplikatkan sampel Merge Swatches Gabungkan sampel @@ -4955,6 +4971,11 @@ axis Both Keduanya Image Gambar Ink Tinta Lab Lab + OKLCH Sliders Penggeser OKLCH + HSL Sliders Penggeser HSL + Chroma Kroma + The largest chroma sRGB holds at this lightness and hue Kroma terbesar yang dapat dimuat sRGB pada kecerahan dan rona ini + OKLCH needs sRGB as the working RGB space OKLCH memerlukan sRGB sebagai ruang RGB kerja Medium Sedang Name Nama None Nihil @@ -5165,9 +5186,11 @@ font-technology Variable Variabel Edit type set in fonts that aren't available? Edit teks dengan font yang tidak tersedia? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Menampilkan nomor setiap irisan dalam kotak di sudut kiri atasnya di kanvas; saat nonaktif, garis tepi irisan tetap ditampilkan. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Warna garis tepi irisan pengguna dan objek serta kotak nomornya; irisan otomatis memakai nuansa yang lebih redup dari warna ini. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Teks baru mendapat bahasa ini selama bahasa di Pengaturan dokumen adalah Inggris: USA; teks yang sudah ada di dokumen mempertahankan bahasanya sendiri. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Teks baru mendapat bahasa ini selama bahasa di Pengaturan dokumen adalah Inggris: USA dan [Gaya karakter normal] tidak menetapkan bahasa; teks yang sudah ada di dokumen mempertahankan bahasanya sendiri. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. Di paragraf dengan Pemenggalan kata aktif, kata dalam daftar hanya dipenggal pada tanda hubung yang diketik di dalamnya, atau tidak di mana pun jika tidak ada, apa pun bahasa atau huruf besar-kecilnya. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. Di versi desktop, plug-in .wasm di folder ini dimuat saat memulai dan saat Anda mengeklik OK dengan folder baru di sini, kecuali dalam Mode aman; versi web tidak memuatnya. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normal mempertahankan batas setiap plug-in sendiri; dengan Besar, filter atau perintah plug-in dapat menjalankan setidaknya 250 juta instruksi selain instruksi untuk masukannya. Batas waktu tetap sama. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Berapa banyak instruksi yang boleh dipakai setiap jalannya filter objek dari plug-in; Besar mengizinkan lebih banyak daripada Normal dengan batas 60 detik yang sama. Filter berat mempertahankan anggarannya sendiri. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Pilihan disk scratch pertama: Startup, None, atau jalur folder; VectorCraft menyimpannya, tetapi belum menggunakan disk scratch. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Pilihan disk scratch kedua: Startup, None, atau jalur folder; VectorCraft menyimpannya, tetapi belum menggunakan disk scratch. How light or dark the interface is. Seberapa terang atau gelap antarmuka. @@ -5185,7 +5208,10 @@ font-technology Variable Variabel The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Bahasa antarmuka; Otomatis menggunakan bahasa sistem. Dialog berganti bahasa begitu Anda memilih salah satunya. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Zoom animasi hanya berfungsi selama ini aktif; jika nonaktif, Zoom animasi diredupkan dan zoom tidak dianimasikan. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Zoom dengan roda meluncur halus, dan Alat zoom memperbesar saat Anda menyeret ke samping atau menahannya; jika nonaktif, Alat zoom memperbesar ke area yang Anda seret. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Mulai dari peluncuran berikutnya, versi desktop menampilkan kanvas melalui jenis prosesor grafis ini; karya seni selalu digambar di CPU. Otomatis mengutamakan prosesor terintegrasi di Windows dan macOS. Versi web tidak menggunakannya. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Mulai dari peluncuran berikutnya, jendela menampilkan setiap bingkai tanpa menunggu penyegaran layar jika driver grafis mengizinkan, paling banyak 240 bingkai per detik. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Mulai dari peluncuran berikutnya, versi desktop menggambar dengan jenis prosesor grafis ini; Otomatis mengutamakan yang menjalankan layar. Versi web tidak menggunakannya. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Mulai dari peluncuran berikutnya, jendela menampilkan bingkai tanpa menunggu layar menyegarkan, paling banyak 240 per detik; jika nonaktif, layar mengatur lajunya. Mode presentasi yang diatur saat peluncuran menggantikannya. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Jumlah maksimum langkah urungkan yang disimpan setiap dokumen; angka yang lebih kecil menghapus langkah terlama saat Anda mengeklik OK. Langkah juga dapat hilang lebih awal jika memakai terlalu banyak memori. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Menampilkan gambar yang berubah saat Anda menyeret; jika nonaktif, garis luar mengikuti seretan dan gambar berubah saat Anda melepas. Panduan penggaris selalu bergerak saat Anda menyeret. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Berapa banyak thread pekerja yang menggambar; -1 memakai satu lebih sedikit dari inti yang boleh dipakai VectorCraft, paling banyak 8, dan 0 tidak memakai sama sekali. Versi web tidak pernah memakainya. @@ -5212,7 +5238,10 @@ font-technology Variable Variabel VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft menyimpan pilihan ini, tetapi Salin dan Potong belum memakai format clipboard vektor lama. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Pertahankan jalur atau Pertahankan tampilan dan overprint untuk clipboard vektor lama; VectorCraft menyimpan pilihan itu tetapi belum memakainya. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. Pertahankan pemformatan menjaga gaya teks yang disalin dari objek teks VectorCraft saat ditempel ke objek teks; Pertahankan teks polos memberinya gaya di tempat teks itu ditempel. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Teks baru mendapat bahasa ini selama bahasa di Pengaturan dokumen adalah Inggris: USA dan [Gaya karakter normal] tidak menetapkan bahasa; teks yang sudah ada di dokumen mempertahankan bahasanya sendiri. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. Tampilkan semua warna hitam sebagai rich black menampilkan hitam CMYK murni (hanya tinta hitam 100%) sebagai hitam RGB di kanvas; Tampilkan semua warna hitam secara akurat mengonversinya melalui ruang CMYK kerja. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Keluarkan semua warna hitam sebagai rich black menggambar hitam CMYK murni sebagai hitam RGB dalam ekspor raster RGB dan skala abu-abu serta Cetak sebagai bitmap; opsi ini tidak mengubah ekspor vektor, JPEG, TIFF, dan PSD CMYK, atau pencetakan lain. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Pada layar sentuh, beralih ke ruang kerja sentuh; mematikan opsi ini atau hilangnya layar sentuh mengembalikan ruang kerja sebelum peralihan. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Ketukan dua jari di kanvas mengurungkan, atau di ruang kerja sentuh beralih antara alat seleksi dan alat gambar, dan ketukan tiga jari mengulangi; keduanya tidak berfungsi dalam mode presentasi. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. Di paragraf dengan Pemenggalan kata aktif, kata dalam daftar hanya dipenggal pada tanda hubung yang diketik di dalamnya, atau tidak di mana pun jika tidak ada, apa pun huruf besar-kecilnya; kata Korea tidak diberi tanda hubung, dan kata dalam bahasa India tidak dipenggal di dalam satu gugus karakter. Reset all preferences to their defaults? Atur ulang semua preferensi ke defaultnya? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Nilai default diterapkan saat Anda mengklik OK di Preferensi. Batal di sana mempertahankan preferensi Anda saat ini. @@ -6380,6 +6409,7 @@ imageTrace Outline Kontur Arrow Panah Arrow (open) Panah (terbuka) Barbed Berduri +arrowhead Feather Bulu Half Arrow (left) Setengah panah (kiri) Half Arrow (right) Setengah panah (kanan) Concave Cekung @@ -6407,6 +6437,7 @@ imageTrace Outline Kontur Kite Layang-layang Triangle to Bar Segitiga ke batang Oval Oval + Line Arrow Panah garis Complementary Komplementer Complementary 2 Komplementer 2 Split Complementary Komplementer terpisah @@ -6875,6 +6906,8 @@ mark-style Japanese Jepang @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` harus grayscale, rgb, hsb, cmyk atau websafe @msg `view` must be wheel or box `view` harus wheel atau box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` harus hue, saturation, brightness, red, green atau blue +@msg `sliders` must be none, oklch or hsl `sliders` harus none, oklch, atau hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH memerlukan sRGB sebagai ruang RGB kerja @msg the Color Picker is not open Pemilih Warna tidak terbuka @msg the screen color sampler is already open pengambil warna layar sudah terbuka @msg this system has no screen color sampler sistem ini tidak memiliki pengambil warna layar @@ -8146,6 +8179,7 @@ breakText Glyphs Glif Remove Strokes Hapus Stroke Place Brush Art Tempatkan karya seni kuas Replace Brush Art Ganti karya seni kuas + Replace Pattern Art Ganti karya seni pola Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Stroke menggunakan kuas ini. Terapkan karya seni baru ke stroke tersebut, atau biarkan apa adanya dan tambahkan salinan kuas dengan karya seni baru? Apply to Strokes Terapkan ke Stroke Leave Strokes Biarkan Stroke @@ -8561,6 +8595,25 @@ breakText Glyphs Glif @msg A joint does not close by {gap} pt. Sebuah sambungan tidak menutup sejauh {gap} pt. @msg Two panels pass through each other. Dua panel saling menembus. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" + Orbit Lines Garis Orbit + Petal Garland Rangkaian Kelopak + Lattice Braid Anyaman Kisi + Facet Sweep Sapuan Berfaset + Artistic Brushes Kuas Artistik + Paint Cat + Flat Sweep Sapuan Datar + Dry Drag Tarikan Kering + Loaded Stroke Sapuan Tebal + Fan Sweep Sapuan Kipas +@msg `at` must be "start" or "end" `at` harus "start" atau "end" +@msg give exactly one of `through` and `toward` berikan tepat satu dari `through` dan `toward` +@msg no arc fits these points: two are the same or all three lie on one line tidak ada busur yang cocok dengan titik-titik ini: dua titik sama atau ketiganya segaris +@msg give `at` only with `toward` berikan `at` hanya bersama `toward` + Engraving Ukiran + Fine Hatching Arsiran halus + Dense Hatching Arsiran rapat + Tapered Hatching Arsiran meruncing + Broken Hatching Arsiran terputus Image Brush Kuas gambar Soft Bloom Mekar lembut Halftone Field Bidang halftone diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 99c5985cac..35cda40dea 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -140,6 +140,7 @@ Add to Selection Aggiungi alla selezione Add to Swatches Aggiungi ai campioni Add Used Colors Aggiungi colori usati + Add Selected Colors Aggiungi colori selezionati Additional Plug-ins Folder Cartella plug-in aggiuntivi Plug-in Instruction Budget Budget di istruzioni dei plug-in Additional Fonts Folder Cartella font aggiuntivi @@ -239,6 +240,10 @@ font-technology Variable Variabili Arc Arco Arc Lower… Arco inferiore… Arc Tool Strumento Arco + Three-Point Arc Tool Strumento Arco per tre punti + Three-Point Arc Arco per tre punti + Arc too large Arco troppo grande + Third Point Sets Direction Il terzo punto indica la direzione Arc Upper… Arco superiore… Arch… Arcata… Arc… Arco… @@ -653,6 +658,8 @@ font-technology Variable Variabili Contextual Task Bar Barra attività contestuale Pin Bar Position Fissa posizione barra Reset Bar Position Ripristina posizione barra + Bar Actions Azioni barra + Reset Bar Actions Ripristina azioni barra Resize Ridimensiona Contrast Contrasto Control Controllo @@ -1731,6 +1738,10 @@ file-filter Templates Modelli Add Color Tool Strumento Aggiungi colore Remove Color Tool Strumento Rimuovi colore Remove Color Rimuovi colore + Set As Base Color Imposta come colore base + Select Shade Seleziona sfumatura + Add New Color Aggiungi nuovo colore + Set Current Color As Base Color Imposta il colore corrente come colore base Find the selected colors in the artwork Trova i colori selezionati nella grafica Harmony Sets Gruppi di armonia Height Altezza @@ -2069,6 +2080,11 @@ file-filter Templates Modelli Knife Coltello Knockout Group Gruppo con foratura Lab Lab + OKLCH Sliders Cursori OKLCH + HSL Sliders Cursori HSL + Chroma Croma + The largest chroma sRGB holds at this lightness and hue Il croma più alto che sRGB contiene con questa luminosità e tonalità + OKLCH needs sRGB as the working RGB space OKLCH richiede sRGB come spazio di lavoro RGB Lab Spot Colors: Colori spot Lab: Lab Values Valori Lab Landscape Orizzontale @@ -2911,6 +2927,11 @@ diagnostics ui interfaccia Preserve Alpha Transparency Mantieni trasparenza alfa Preserve Appearance and Overprints Mantieni aspetto e sovrastampe Preserve CMYK Numbers Mantieni valori CMYK + Preserve RGB Numbers Mantieni valori RGB + Device to Simulate: Dispositivo da simulare: + Simulate Paper Color Simula colore carta + Simulate Black Ink Simula inchiostro nero + Load… Carica… Preserve Editing Capabilities Mantieni possibilità di modifica Preserve editing capabilities Mantieni possibilità di modifica Preserve Lightness Mantieni luminosità @@ -3411,9 +3432,11 @@ digits Malayalam Malayalam Edit type set in fonts that aren't available? Modificare il testo in font non disponibili? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Mostra sull’area di lavoro il numero di ogni sezione in un riquadro nel suo angolo in alto a sinistra; se è disattivata, i contorni delle sezioni restano visibili. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Il colore dei contorni delle sezioni utente e oggetto e dei riquadri con il loro numero; le sezioni automatiche usano una tonalità più tenue di questo colore. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Il nuovo testo prende questa lingua finché la lingua di Imposta documento è Inglese: Stati Uniti; il testo già presente in un documento mantiene la propria lingua. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Il nuovo testo prende questa lingua finché la lingua di Imposta documento è Inglese: Stati Uniti e [Stile carattere normale] non ne imposta una; il testo già presente in un documento mantiene la propria lingua. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. Nei paragrafi con Sillaba attivo, una parola dell'elenco va a capo solo ai trattini digitati al suo interno, o in nessun punto se non ne ha, qualunque sia la sua lingua o l'uso delle maiuscole. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. Nella versione desktop, i plug-in .wasm di questa cartella vengono caricati all'avvio e quando fai clic su OK con una nuova cartella qui, tranne in modalità provvisoria; la versione web non li carica. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normale mantiene i limiti propri di ogni plug-in; con Grande, un filtro o un comando di un plug-in può eseguire almeno 250 milioni di istruzioni oltre a quelle per il suo input. Il limite di tempo resta invariato. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Quante istruzioni può usare ogni esecuzione di un filtro di oggetti di un plug-in; Grande ne consente più di Normale con lo stesso limite di 60 secondi. I filtri pesanti mantengono il proprio budget. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. La prima scelta del disco di memoria virtuale: Startup, None o il percorso di una cartella; VectorCraft la memorizza, ma non usa ancora dischi di memoria virtuale. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. La seconda scelta del disco di memoria virtuale: Startup, None o il percorso di una cartella; VectorCraft la memorizza, ma non usa ancora dischi di memoria virtuale. How light or dark the interface is. Quanto è chiara o scura l'interfaccia. @@ -3431,7 +3454,10 @@ digits Malayalam Malayalam The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. La lingua dell'interfaccia; Auto usa la lingua del sistema. La finestra di dialogo cambia lingua appena ne scegli una. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Lo Zoom animato funziona solo mentre questa opzione è attiva; se disattivata, lo Zoom animato è attenuato e lo zoom non è animato. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Lo zoom con la rotellina scorre in modo fluido, e lo Strumento Zoom ingrandisce mentre trascini di lato o lo tieni premuto; se disattivata, lo Strumento Zoom ingrandisce l'area che trascini. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Dal prossimo avvio, la versione desktop mostra la tela tramite questo tipo di processore grafico; la grafica viene sempre disegnata sulla CPU. Automatico preferisce quello integrato su Windows e macOS. La versione web non lo usa. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Dal prossimo avvio, la finestra mostra ogni fotogramma senza attendere l’aggiornamento dello schermo dove il driver grafico lo consente, al massimo 240 fotogrammi al secondo. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Dal prossimo avvio, la versione desktop disegna con questo tipo di processore grafico; Automatico preferisce quello che gestisce lo schermo. La versione web non lo usa. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Dal prossimo avvio, la finestra mostra i fotogrammi senza attendere l'aggiornamento dello schermo, al massimo 240 al secondo; disattivato, è lo schermo a scandirli. Una modalità di presentazione impostata all'avvio ha la precedenza. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Il numero massimo di passaggi di annullamento che ogni documento conserva; un numero più basso rimuove i passaggi più vecchi quando fai clic su OK. I passaggi possono sparire anche prima se occupano troppa memoria. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Mostra la grafica che cambia mentre trascini; se disattivata, i contorni seguono il trascinamento e la grafica cambia quando rilasci. Una guida del righello si muove sempre mentre trascini. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Quanti thread di lavoro disegnano la grafica; -1 ne usa uno in meno dei core che VectorCraft può usare, al massimo 8, e 0 nessuno. La versione web non ne usa mai. @@ -3458,7 +3484,10 @@ digits Malayalam Malayalam VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft salva questa scelta, ma Copia e Taglia non usano ancora un formato degli appunti vettoriali tradizionali. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Mantieni tracciati o Mantieni aspetto e sovrastampe per gli appunti vettoriali tradizionali; VectorCraft salva la scelta ma non la usa ancora. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. Mantieni formattazione conserva gli stili del testo copiato da un oggetto di testo di VectorCraft quando viene incollato in un oggetto di testo; Mantieni solo testo gli dà lo stile del punto in cui arriva. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Il nuovo testo prende questa lingua finché la lingua di Imposta documento è Inglese: Stati Uniti e [Stile carattere normale] non ne imposta una; il testo già presente in un documento mantiene la propria lingua. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. Visualizza tutti i neri come nero ricco mostra il nero CMYK puro (solo inchiostro nero al 100%) come nero RGB nell'area di lavoro; Visualizza tutti i neri con precisione lo converte attraverso lo spazio CMYK di lavoro. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Riproduci tutti i neri come nero ricco disegna il nero CMYK puro come nero RGB nelle esportazioni raster RGB e in scala di grigi e con Stampa come bitmap; non cambia le esportazioni vettoriali, i JPEG, TIFF e PSD CMYK né le altre stampe. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Su uno schermo touch passa all'area di lavoro touch; disattivando l'opzione o se lo schermo touch non è più rilevato, torna all'area di lavoro precedente. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Un tocco con due dita sull'area di lavoro annulla o, nell'area di lavoro touch, alterna tra strumenti di selezione e di disegno, e un tocco con tre dita ripete; nessuno dei due funziona in modalità presentazione. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. Nei paragrafi con Sillaba attivo, una parola dell'elenco va a capo solo ai trattini digitati al suo interno, o in nessun punto se non ne ha, qualunque sia l'uso delle maiuscole; le parole coreane non prendono trattino e le parole in lingue indiane non vanno a capo all'interno di un gruppo di caratteri. Reset all preferences to their defaults? Ripristinare tutte le preferenze ai valori predefiniti? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. I valori predefiniti vengono applicati quando fai clic su OK in Preferenze. Annulla lì mantiene le preferenze attuali. @@ -5190,6 +5219,8 @@ liquify-list-end {0}, {1} {0} e {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` deve essere grayscale, rgb, hsb, cmyk o websafe @msg `view` must be wheel or box `view` deve essere wheel o box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` deve essere hue, saturation, brightness, red, green o blue +@msg `sliders` must be none, oklch or hsl `sliders` deve essere none, oklch o hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH richiede sRGB come spazio di lavoro RGB @msg `{k}` must be [x, y] `{k}` deve essere [x, y] @msg `{name}` has no options `{name}` non ha opzioni @msg `{name}` is a built-in workspace; choose another name `{name}` è un'area di lavoro integrata; scegli un altro nome @@ -5383,6 +5414,10 @@ liquify-list-end {0}, {1} {0} e {1} @msg a guide has no curvature circle una guida non ha un cerchio di curvatura @msg the circle that matches the path there would reach past the canvas il cerchio che corrisponde al tracciato in quel punto supererebbe l'area di lavoro @msg no circle passes through these points: two are the same or all three lie on one line nessun cerchio passa per questi punti: due coincidono oppure tutti e tre sono allineati +@msg `at` must be "start" or "end" `at` deve essere "start" o "end" +@msg give exactly one of `through` and `toward` indicare esattamente uno tra `through` e `toward` +@msg no arc fits these points: two are the same or all three lie on one line nessun arco si adatta a questi punti: due coincidono oppure tutti e tre sono allineati +@msg give `at` only with `toward` indicare `at` solo insieme a `toward` @msg no app to open files here nessuna app per aprire file qui @msg no artboard nessuna tavola da disegno @msg no artboard {i} (0-based; the document has {_1}) nessuna tavola da disegno {i} (a partire da 0; il documento ne ha {_1}) @@ -5428,6 +5463,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg no native format nessun formato nativo @msg no pages nessuna pagina @msg no pattern `{name}` nessun motivo `{name}` +@msg art painted with `{name}` can't be its tile una grafica dipinta con `{name}` non può esserne la porzione @msg no perspective grid preset named `{name}` nessun preset di griglia prospettica denominato `{name}` @msg no plug-in {0} is installed nessun plug-in {0} installato @msg no plug-in {id} is installed nessun plug-in {id} installato @@ -7639,6 +7675,37 @@ anchor Points: Punti: @msg `{id}` is not a colour adjustment `{id}` non è una regolazione del colore @msg missing `effect` manca `effect` @msg `params` must be an object `params` deve essere un oggetto +# Stroke arrowheads (Stroke panel, Dimension Tool Options and Properties › Arrow Style). + Triangle (open) Triangolo (aperto) + Circle (open) Cerchio (aperto) + Square (open) Quadrato (aperto) + Arrow (open) Freccia (aperta) + Barbed Uncinata +arrowhead Feather Piuma +arrowhead Target Bersaglio + Half Arrow (left) Mezza freccia (sinistra) + Half Arrow (right) Mezza freccia (destra) + Double Bar Doppia barra + Dot on Bar Punto su barra + Chevron Gallone + Plus Più + Hexagon (open) Esagono (aperto) + Tag Etichetta + Tag (open) Etichetta (aperta) + Half Circle Semicerchio + Drop Goccia + Slash Barra obliqua + Double Slash Doppia barra obliqua + Diamond (open) Rombo (aperto) + Reverse Triangle Triangolo invertito + Swallowtail Coda di rondine + Bracket Parentesi + Fork Forcella + Leaf Foglia + Kite Aquilone + Triangle to Bar Da triangolo a barra + Oval Ovale + Line Arrow Freccia a linee # Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. Path Precision Tools Strumenti di precisione per tracciati Anchor Eraser Brush Pennello gomma punti di ancoraggio @@ -7929,6 +7996,7 @@ breakText Glyphs Glifi Remove Strokes Rimuovi tracce Place Brush Art Inserisci grafica del pennello Replace Brush Art Sostituisci grafica del pennello + Replace Pattern Art Sostituisci grafica del motivo Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Alcune tracce usano questo pennello. Applicare la nuova grafica a queste tracce, o lasciarle come sono e aggiungere una copia del pennello con la nuova grafica? Apply to Strokes Applica alle tracce Leave Strokes Lascia le tracce @@ -10364,6 +10432,21 @@ breakText Glyphs Glifi @msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura. @msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cerniere: {hinges}, errori: {errors}, avvisi: {warnings} + Orbit Lines Linee orbitali + Petal Garland Ghirlanda di petali + Lattice Braid Intreccio a reticolo + Facet Sweep Tratto sfaccettato + Artistic Brushes Pennelli artistici + Paint Pittura + Flat Sweep Passata piatta + Dry Drag Trascinamento secco + Loaded Stroke Tratto carico + Fan Sweep Passata a ventaglio + Engraving Incisione + Fine Hatching Tratteggio fine + Dense Hatching Tratteggio fitto + Tapered Hatching Tratteggio affusolato + Broken Hatching Tratteggio spezzato Image Brush Pennelli immagine Soft Bloom Fioritura morbida Halftone Field Campo mezzitoni diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 91301ae00c..c3efef8887 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -846,6 +846,8 @@ digits Malayalam マラヤーラム数字 Contextual Task Bar コンテキストタスクバー Pin Bar Position バーの位置を固定 Reset Bar Position バーの位置をリセット + Bar Actions バーのアクション + Reset Bar Actions バーのアクションをリセット Resize サイズを変更 Tools ツール Toolbars ツールバー @@ -1155,6 +1157,7 @@ digits Malayalam マラヤーラム数字 Add Selected Artwork as One Asset 選択したアートワークを 1 つのアセットとして追加 Add Spine Point スパインポイントを追加 Add Used Colors 使用中のカラーを追加 + Add Selected Colors 選択したカラーを追加 Add to Graphic Styles グラフィックスタイルに追加 Add to Profiles プロファイルに追加 Add to Profiles… プロファイルに追加… @@ -1235,6 +1238,10 @@ antiAlias Sharp シャープ @plural Apply to All ({n} more missing)|Apply to All ({n} more missing) すべてに適用 (ほかに {n} 個が見つかりません) Arc 円弧 Arc Tool 円弧ツール + Three-Point Arc Tool 3 点円弧ツール + Three-Point Arc 3 点円弧 + Arc too large 円弧が大きすぎます + Third Point Sets Direction 3 点目で方向を指定 Area / Path Type エリア内文字/パス上文字 Area Graph Tool 面グラフツール Area Type Tool エリア内文字ツール @@ -2115,6 +2122,10 @@ antiAlias Sharp シャープ Add Color Tool カラー追加ツール Remove Color Tool カラー削除ツール Remove Color カラーを削除 + Set As Base Color ベースカラーに設定 + Select Shade シェードを選択 + Add New Color 新規カラーを追加 + Set Current Color As Base Color 現在のカラーをベースカラーに設定 Find the selected colors in the artwork 選択したカラーをアートワーク内で検索 Height 高さ Height: 高さ: @@ -2986,6 +2997,11 @@ diagnostics ui UI Preserve Alpha Transparency アルファ透明を保持 Preserve Appearance and Overprints アピアランスとオーバープリントを保持 Preserve CMYK Numbers CMYK 値を保持 + Preserve RGB Numbers RGB 値を保持 + Device to Simulate: シミュレートするデバイス: + Simulate Paper Color 用紙の色をシミュレート + Simulate Black Ink インキの黒をシミュレート + Load… 読み込み… Preserve Editing Capabilities 編集機能を保持 Preserve Lightness 明度を保持 Preserve Overprints and Spot Colors オーバープリントと特色を保持 @@ -3384,9 +3400,10 @@ mark-style Japanese 日本式 Edit type set in fonts that aren't available? 使用できないフォントのテキストを編集しますか? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. カンバス上で、各スライスの番号をスライスの左上のボックスに表示します。オフでもスライスの輪郭は表示されます。 The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. ユーザースライスとオブジェクトスライスの輪郭、およびその番号のボックスの色です。自動スライスにはこの色の淡い色合いが使われます。 - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. ドキュメント設定の言語が英語 (米国) の間は、新しいテキストにこの言語が設定されます。ドキュメント内の既存のテキストは自身の言語を保ちます。 In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. ハイフネーションがオンの段落では、リストの単語は入力したハイフンの位置でのみ分割され、ハイフンがなければ分割されません。言語や大文字小文字は問いません。 On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. デスクトップ版では、このフォルダーの .wasm プラグインが起動時と、ここに新しいフォルダーを指定して OK をクリックしたときに読み込まれます (セーフモードを除く)。Web 版では読み込まれません。 + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. 通常では各プラグイン自身の制限が使われます。大では、プラグインのフィルターやコマンドは入力のための命令に加えて少なくとも 2 億 5000 万命令を実行できます。時間の制限は変わりません。 + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. プラグインのオブジェクトフィルターを 1 回実行するときに使える命令の数です。大では通常より多く使え、60 秒の制限は変わりません。重いフィルターは独自の予算を保ちます。 The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. 1 つ目の仮想記憶ディスクの選択です。Startup、None またはフォルダーのパスを指定します。VectorCraft は保存しますが、仮想記憶ディスクはまだ使用しません。 The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. 2 つ目の仮想記憶ディスクの選択です。Startup、None またはフォルダーのパスを指定します。VectorCraft は保存しますが、仮想記憶ディスクはまだ使用しません。 How light or dark the interface is. インターフェイスをどの程度明るく、または暗く表示するかです。 @@ -3404,7 +3421,10 @@ mark-style Japanese 日本式 The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. インターフェイスの言語です。自動ではシステムの言語を使います。言語を選ぶとすぐにダイアログの表示が切り替わります。 Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. アニメーションズームは、これがオンのときだけ働きます。オフの場合、アニメーションズームは淡色表示になり、ズームはアニメーションしません。 The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. ホイールによるズームはなめらかに動き、ズームツールは横にドラッグするか押したままにするとズームします。オフの場合、ズームツールはドラッグした範囲にズームします。 + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. 次回の起動から、デスクトップ版はこの種類のグラフィックプロセッサーを通してカンバスを表示します。アートワーク自体は常に CPU で描画されます。自動では Windows と macOS で内蔵のものが優先されます。Web 版では使われません。 + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. 次回の起動から、グラフィックドライバーが許す場合、ウィンドウはディスプレイのリフレッシュを待たずに各フレームを表示します。最大で毎秒 240 フレームです。 From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. 次回の起動から、デスクトップ版はこの種類のグラフィックプロセッサーで描画します。自動ではディスプレイを駆動しているものが優先されます。Web 版では使われません。 + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. 次回の起動から、ウィンドウはディスプレイの更新を待たずにフレームを表示します。上限は毎秒 240 フレームです。オフにすると、ディスプレイがフレームの間隔を決めます。起動時に指定した表示モードが優先されます。 The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. 各ドキュメントが保持する取り消しステップの最大数です。値を下げると、OK をクリックしたときに古いステップから削除されます。メモリを使いすぎる場合は、さらに早く削除されることがあります。 Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. ドラッグ中にアートワークが変わる様子を表示します。オフの場合、ドラッグ中はアウトラインが動き、ボタンを離すとアートワークが変わります。定規ガイドはドラッグ中も常に動きます。 How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. アートワークを描画するワーカースレッドの数です。-1 は VectorCraft が使えるコア数より 1 つ少なく (最大 8)、0 はワーカーを使いません。Web 版では常に使いません。 @@ -3431,6 +3451,10 @@ mark-style Japanese 日本式 VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft はこの選択を保存しますが、コピーと切り取りはまだ従来のベクタークリップボードの形式を使用しません。 Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. 従来のベクタークリップボードの「パスを保持」または「アピアランスとオーバープリントを保持」です。VectorCraft は選択を保存しますが、まだ使用しません。 Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. 「書式を保持」では、VectorCraft のテキストオブジェクトからコピーしたテキストをテキストオブジェクトに貼り付けるとスタイルを保持します。「テキストのみを保持」では、貼り付け先のスタイルになります。 + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. 「すべてのブラックをリッチブラックで表示」では、純粋な CMYK ブラック(ブラックインキのみ 100%)をカンバス上で RGB ブラックとして表示します。「すべてのブラックを正確に表示」では、作業用 CMYK スペースを通して変換します。 + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. 「すべてのブラックをリッチブラックで出力」では、RGB とグレースケールのラスター書き出しと「ビットマップとしてプリント」で純粋な CMYK ブラックを RGB ブラックとして描画します。ベクター書き出し、CMYK の JPEG、TIFF と PSD、その他のプリントは変わりません。 + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. タッチスクリーンではタッチワークスペースに切り替えます。オフにするか、タッチスクリーンが使えなくなると、切り替える前のワークスペースに戻ります。 + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. カンバスを 2 本指でタップすると取り消し、タッチワークスペースでは選択ツールと描画ツールを切り替えます。3 本指でタップするとやり直します。どちらもプレゼンテーションモードでは動作しません。 New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. ドキュメント設定の言語が英語 (米国) で、[標準文字スタイル] が言語を設定していない間は、新しいテキストにこの言語が設定されます。ドキュメント内の既存のテキストは自身の言語を保ちます。 In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. ハイフネーションがオンの段落では、リストの単語は入力したハイフンの位置でのみ分割され、ハイフンがなければ分割されません。大文字小文字は問いません。韓国語の単語にはハイフンが付かず、インドの言語の単語は文字のまとまりの途中では分割されません。 Reset all preferences to their defaults? すべての環境設定を初期値に戻しますか? @@ -4396,6 +4420,11 @@ file-filter Templates テンプレート Keep the pasted color as a new swatch with a numbered name. ペーストしたカラーを、番号付きの名前で新規スウォッチとして残します。 Keep: 保持: Lab Lab + OKLCH Sliders OKLCH スライダー + HSL Sliders HSL スライダー + Chroma クロマ + The largest chroma sRGB holds at this lightness and hue この明度と色相で sRGB に収まる最大のクロマ + OKLCH needs sRGB as the working RGB space OKLCH には作業用 RGB スペースとして sRGB が必要です Lab Values Lab 値 Large List View 大きいリスト表示 Large Thumbnail View 大きいサムネール表示 @@ -5148,6 +5177,10 @@ variable-list-end {0}, {1} {0}、{1} @msg a guide has no curvature circle ガイドには曲率円がありません @msg the circle that matches the path there would reach past the canvas その位置でパスに合う円はキャンバスからはみ出します @msg no circle passes through these points: two are the same or all three lie on one line これらの点を通る円はありません: 2 つの点が同じか、3 点すべてが一直線上にあります +@msg `at` must be "start" or "end" `at` には "start" または "end" を指定してください +@msg give exactly one of `through` and `toward` `through` と `toward` のどちらか一方だけを指定してください +@msg no arc fits these points: two are the same or all three lie on one line これらの点に合う円弧はありません: 2 つの点が同じか、3 点すべてが一直線上にあります +@msg give `at` only with `toward` `at` は `toward` と一緒にだけ指定してください @msg select at least two objects オブジェクトを 2 つ以上選択してください @msg exit isolation mode first 先に分離モードを終了してください @msg no saved presets 保存したプリセットはありません @@ -5194,6 +5227,7 @@ variable-list-end {0}, {1} {0}、{1} @msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} の結果が空になりました。領域を囲まない直線などのオープンパスがあります。含めるには、先にそのパスに「オブジェクト › パス › パスのアウトライン」を適用してください @msg already editing a pattern すでにパターンを編集中です @msg no pattern `{name}` パターン `{name}` が見つかりません +@msg art painted with `{name}` can't be its tile `{name}` でペイントされたアートはそのタイルにできません @msg not in pattern editing mode パターン編集モードではありません @msg finish editing the pattern first 先にパターンの編集を終了してください @msg pattern missing パターンが見つかりません @@ -5615,6 +5649,8 @@ variable-list-end {0}, {1} {0}、{1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` には grayscale、rgb、hsb、cmyk、websafe のいずれかを指定してください @msg `view` must be wheel or box `view` には wheel、box のいずれかを指定してください @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` には hue、saturation、brightness、red、green、blue のいずれかを指定してください +@msg `sliders` must be none, oklch or hsl `sliders` には none、oklch、hsl のいずれかを指定してください +@msg OKLCH needs sRGB as the working RGB space OKLCH には作業用 RGB スペースとして sRGB が必要です @msg `{key}` must be true or false `{key}` には true または false を指定してください @msg `top` and `below` can't both be true `top` と `below` を同時に true にすることはできません @msg `select` must be true or false `select` には true または false を指定してください @@ -9529,6 +9565,36 @@ anchor Points: ポイント: @msg `{id}` is not a colour adjustment `{id}` はカラー補正ではありません @msg missing `effect` `effect` が指定されていません @msg `params` must be an object `params` にはオブジェクトを指定してください +# Stroke arrowheads (Stroke panel, Dimension Tool Options and Properties › Arrow Style). + Triangle (open) 三角形 (白抜き) + Circle (open) 円 (白抜き) + Square (open) 正方形 (白抜き) + Arrow (open) 矢印 (白抜き) + Barbed かえし付き +arrowhead Feather 矢羽根 + Half Arrow (left) 片矢印 (左) + Half Arrow (right) 片矢印 (右) + Double Bar 二重バー + Dot on Bar バー上のドット + Chevron 山形 + Plus プラス + Hexagon (open) 六角形 (白抜き) + Tag タグ + Tag (open) タグ (白抜き) + Half Circle 半円 + Drop しずく + Slash スラッシュ + Double Slash 二重スラッシュ + Diamond (open) ひし形 (白抜き) + Reverse Triangle 逆三角形 + Swallowtail 燕尾 + Bracket 角かっこ + Fork フォーク + Leaf 葉 + Kite カイト + Triangle to Bar 三角形からバー + Oval 楕円 + Line Arrow 線矢印 # Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. Path Precision Tools パス精密ツール Anchor Eraser Brush アンカーポイント消去ブラシ @@ -9819,6 +9885,7 @@ breakText Glyphs 字形 Remove Strokes 線を削除 Place Brush Art ブラシのアートを配置 Replace Brush Art ブラシのアートを置き換え + Replace Pattern Art パターンのアートを置き換え Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? このブラシは線で使われています。新しいアートをそれらの線に適用しますか?それとも線をそのままにして、新しいアートを持つブラシのコピーを追加しますか? Apply to Strokes 線に適用 Leave Strokes 線を保持 @@ -10428,6 +10495,21 @@ breakText Glyphs 字形 @msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。 @msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、ヒンジ: {hinges}、エラー: {errors}、警告: {warnings} + Orbit Lines 軌道線 + Petal Garland 花びらのガーランド + Lattice Braid 格子編み + Facet Sweep 多面体のストローク + Artistic Brushes アートブラシ + Paint ペイント + Flat Sweep 平筆の一掃き + Dry Drag ドライドラッグ + Loaded Stroke 厚塗りストローク + Fan Sweep 扇形の一掃き + Engraving 彫刻 + Fine Hatching 細いハッチング + Dense Hatching 密なハッチング + Tapered Hatching 先細りハッチング + Broken Hatching 途切れたハッチング Image Brush 画像ブラシ Soft Bloom やわらかな花 Halftone Field ハーフトーンの面 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a2cd29afc8..6e3eefa54c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2920,6 +2920,8 @@ Contextual Task Bar კონტექსტური ამოცანების ზოლი Pin Bar Position ზოლის პოზიციის ჩამაგრება Reset Bar Position ზოლის პოზიციის ჩამოყრა + Bar Actions ზოლის მოქმედებები + Reset Bar Actions ზოლის მოქმედებების ჩამოყრა Tools ხელსაწყოები Toolbars ხელსაწყოთა ზოლები Advanced დამატებითი @@ -3585,6 +3587,10 @@ lighting Light სინათლე Add Anchor Point Tool საყრდენი წერტილის დამატების ხელსაწყო Anchor Point Tool საყრდენი წერტილის ხელსაწყო Arc Tool რკალის ხელსაწყო + Three-Point Arc Tool სამწერტილიანი რკალის ხელსაწყო + Three-Point Arc სამწერტილიანი რკალი + Arc too large რკალი ზედმეტად დიდია + Third Point Sets Direction მესამე წერტილი მიმართულებას განსაზღვრავს Area Graph Tool ფართობითი დიაგრამის ხელსაწყო Area Type Tool არის ტექსტის ხელსაწყო Artboard Tool სამუშაო დაფის ხელსაწყო @@ -4995,6 +5001,11 @@ digits Malayalam მალაიალამური Place the pages with the placement again გვერდების ხელახლა განთავსება განთავსების მიხედვით Placement: განთავსება: Preserve CMYK Numbers CMYK მნიშვნელობების შენარჩუნება + Preserve RGB Numbers RGB მნიშვნელობების შენარჩუნება + Device to Simulate: სიმულირებადი მოწყობილობა: + Simulate Paper Color ქაღალდის ფერის იმიტაცია + Simulate Black Ink შავი მელნის იმიტაცია + Load… ჩატვირთვა… Previous page წინა გვერდი Print Layers: შრეების ბეჭდვა: Print Preset: ბეჭდვის პრესეტი: @@ -5067,6 +5078,10 @@ digits Malayalam მალაიალამური Add Color Tool ფერის დამატების ხელსაწყო Remove Color Tool ფერის წაშლის ხელსაწყო Remove Color ფერის წაშლა + Set As Base Color საბაზო ფერად დაყენება + Select Shade ელფერის არჩევა + Add New Color ახალი ფერის დამატება + Set Current Color As Base Color მიმდინარე ფერის საბაზო ფერად დაყენება Find the selected colors in the artwork მონიშნული ფერების ძებნა ნახატში Keep this row's colors (exclude) ამ სტრიქონის ფერების შენარჩუნება (გამორიცხვა) Limit to Library: ბიბლიოთეკით შეზღუდვა: @@ -6171,6 +6186,7 @@ theme Appearance იერსახე Add to Graphic Styles გრაფიკულ სტილებში დამატება Graphic Style Library გრაფიკული სტილების ბიბლიოთეკა Add Used Colors გამოყენებული ფერების დამატება + Add Selected Colors მონიშნული ფერების დამატება Delete Swatch ფერის ნიმუშის წაშლა Duplicate Swatch ფერის ნიმუშის დუბლირება Merge Swatches ფერის ნიმუშების შერწყმა @@ -6349,6 +6365,11 @@ axis Both ორივე Image გამოსახულება Ink მელანი Lab Lab + OKLCH Sliders OKLCH სლაიდერები + HSL Sliders HSL სლაიდერები + Chroma ქრომა + The largest chroma sRGB holds at this lightness and hue უდიდესი ქრომა, რომელსაც sRGB იტევს ამ სიღიავესა და ფერის ტონზე + OKLCH needs sRGB as the working RGB space OKLCH-ს სამუშაო RGB სივრცედ sRGB სჭირდება Medium საშუალო Name სახელი None არცერთი @@ -6558,9 +6579,11 @@ font-technology Variable ცვლადი Edit type set in fonts that aren't available? დავარედაქტიროთ მიუწვდომელი შრიფტებით აწყობილი ტექსტი? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. ტილოზე თითოეული ნაჭრის ნომერს აჩვენებს ჩარჩოში მის ზედა მარცხენა კუთხეში; გამორთულისას ნაჭრების კონტურები კვლავ ჩანს. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. მომხმარებლისა და ობიექტის ნაჭრების კონტურებისა და მათი ნომრების ჩარჩოების ფერი; ავტომატური ნაჭრები ამ ფერის უფრო მკრთალ ელფერს იყენებს. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. ახალი ტექსტი იღებს ამ ენას, სანამ დოკუმენტის პარამეტრების ენაა ინგლისური: აშშ; დოკუმენტში უკვე არსებული ტექსტი ინარჩუნებს თავის ენას. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. ახალი ტექსტი იღებს ამ ენას, სანამ დოკუმენტის პარამეტრების ენაა ინგლისური: აშშ და [ჩვეულებრივი სიმბოლოს სტილი] ენას არ ადგენს; დოკუმენტში უკვე არსებული ტექსტი ინარჩუნებს თავის ენას. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. აბზაცებში, სადაც სიტყვების გადატანა ჩართულია, სიაში მოცემული სიტყვა მხოლოდ მასში აკრეფილ დეფისებთან გადაიტანება, ან არსად, თუ ისინი არ აქვს, მიუხედავად ენისა და რეგისტრისა. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. დესკტოპის ვერსიაში ამ საქაღალდის .wasm პლაგინები იტვირთება გაშვებისას და როცა აქ ახალი საქაღალდით OK-ს დააწკაპუნებთ, გარდა უსაფრთხო რეჟიმისა; ვებ-ვერსია მათ არ ტვირთავს. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. ჩვეულებრივი ინარჩუნებს თითოეული პლაგინის საკუთარ ლიმიტებს; დიდით პლაგინის ფილტრს ან ბრძანებას შეუძლია შეასრულოს მინიმუმ 250 მილიონი ინსტრუქცია მისი შეყვანისთვის საჭირო ინსტრუქციების გარდა. დროის ლიმიტი იგივე რჩება. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. რამდენი ინსტრუქციის გამოყენება შეუძლია პლაგინის ობიექტების ფილტრის თითოეულ გაშვებას; დიდი ჩვეულებრივზე მეტს უშვებს, იმავე 60-წამიანი ლიმიტით. მძიმე ფილტრები საკუთარ ბიუჯეტს ინარჩუნებენ. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. სამუშაო დისკის პირველი არჩევანი: Startup, None ან საქაღალდის მისამართი; VectorCraft მას ინახავს, მაგრამ სამუშაო დისკებს ჯერ არ იყენებს. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. სამუშაო დისკის მეორე არჩევანი: Startup, None ან საქაღალდის მისამართი; VectorCraft მას ინახავს, მაგრამ სამუშაო დისკებს ჯერ არ იყენებს. How light or dark the interface is. რამდენად ღია ან მუქია ინტერფეისი. @@ -6578,7 +6601,10 @@ font-technology Variable ცვლადი The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. ინტერფეისის ენა; ავტომატური სისტემის ენას იყენებს. დიალოგი ენას იცვლის, როგორც კი რომელიმეს აირჩევთ. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. ანიმირებული მასშტაბირება მუშაობს მხოლოდ მაშინ, როცა ეს ჩართულია; გამორთულისას ანიმირებული მასშტაბირება მკრთალია და მასშტაბირება არ ანიმირდება. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. ბორბლით მასშტაბირება რბილად სრიალებს, მასშტაბის ხელსაწყო კი ადიდებს, როცა გვერდზე გადაათრევთ ან დაჭერილს გაჩერებთ; გამორთულისას ის ადიდებს არეს, რომელზეც გადაათრევთ. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. შემდეგი გაშვებიდან დესკტოპის ვერსია ტილოს აჩვენებს ამ ტიპის გრაფიკული პროცესორით; ნამუშევარი ყოველთვის CPU-ზე იხატება. ავტომატური Windows-სა და macOS-ზე ინტეგრირებულს ანიჭებს უპირატესობას. ვებ-ვერსია მას არ იყენებს. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. შემდეგი გაშვებიდან ფანჯარა აჩვენებს თითოეულ კადრს ეკრანის განახლების მოლოდინის გარეშე, სადაც გრაფიკული დრაივერი ამის საშუალებას იძლევა, წამში არაუმეტეს 240 კადრისა. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. შემდეგი გაშვებიდან დესკტოპის ვერსია ხატავს ამ ტიპის გრაფიკული პროცესორით; ავტომატური უპირატესობას ანიჭებს ეკრანის მმართველს. ვებ-ვერსია მას არ იყენებს. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. შემდეგი გაშვებიდან ფანჯარა აჩვენებს კადრებს ეკრანის განახლების მოლოდინის გარეშე, წამში არაუმეტეს 240-ისა; გამორთულისას ტემპს ეკრანი განსაზღვრავს. უპირატესობა აქვს გაშვებისას დაყენებულ ჩვენების რეჟიმს. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. გაუქმების ნაბიჯების მაქსიმალური რაოდენობა თითო დოკუმენტში; მცირე რიცხვი OK-ზე დაწკაპუნებისას შლის უძველეს ნაბიჯებს. ნაბიჯები შეიძლება ადრეც წაიშალოს, თუ ბევრ მეხსიერებას იკავებს. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. აჩვენებს, როგორ იცვლება ნახატი გადათრევისას; გამორთულისას კონტურები მისდევს გადათრევას, ნახატი კი ხელის აშვებისას იცვლება. სახაზავის დამხმარე ხაზი გადათრევისას ყოველთვის მოძრაობს. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. რამდენი სამუშაო ნაკადი ხატავს ნახატს; -1 იყენებს ერთით ნაკლებს VectorCraft-ისთვის ხელმისაწვდომ ბირთვებზე, მაქსიმუმ 8-ს, 0 კი არცერთს. ვებ-ვერსია არასდროს იყენებს. @@ -6605,7 +6631,10 @@ font-technology Variable ცვლადი VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft ამ არჩევანს ინახავს, მაგრამ კოპირება და ამოჭრა ძველი ვექტორული ბუფერის ფორმატს ჯერ არ იყენებს. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. ტრაექტორიების შენარჩუნება ან იერსახისა და ზედდაბეჭდვების შენარჩუნება ძველი ვექტორული ბუფერისთვის; VectorCraft არჩევანს ინახავს, მაგრამ ჯერ არ იყენებს. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. ფორმატირების შენარჩუნება VectorCraft-ის ტექსტური ობიექტიდან კოპირებული ტექსტის სტილებს ინახავს ტექსტურ ობიექტში ჩასმისას; მხოლოდ ტექსტის შენარჩუნება მას ჩასმის ადგილის სტილს აძლევს. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. ახალი ტექსტი იღებს ამ ენას, სანამ დოკუმენტის პარამეტრების ენაა ინგლისური: აშშ და [ჩვეულებრივი სიმბოლოს სტილი] ენას არ ადგენს; დოკუმენტში უკვე არსებული ტექსტი ინარჩუნებს თავის ენას. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. ყველა შავის მდიდარ შავად ჩვენება სუფთა CMYK შავს (მხოლოდ შავი მელანი 100%-ზე) ტილოზე RGB შავად აჩვენებს; ყველა შავის ზუსტად ჩვენება მას სამუშაო CMYK სივრცით გარდაქმნის. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. ყველა შავის მდიდარ შავად გამოტანა სუფთა CMYK შავს RGB შავად ხატავს RGB და ნაცრისფერი გრადაციების რასტრულ ექსპორტებში და ბიტმაპად ბეჭდვისას; ის არ ცვლის ვექტორულ ექსპორტებს, CMYK JPEG-ს, TIFF-სა და PSD-ს ან სხვა ბეჭდვას. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. სენსორულ ეკრანზე გადადის სენსორულ სამუშაო სივრცეზე; პარამეტრის გამორთვისას ან სენსორული ეკრანის დაკარგვისას ბრუნდება წინა სამუშაო სივრცეზე. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. ტილოზე ორი თითით შეხება აბრუნებს მოქმედებას, სენსორულ სამუშაო სივრცეში კი მონიშვნისა და ხატვის ხელსაწყოებს შორის გადართავს; სამი თითით შეხება ხელახლა ასრულებს. პრეზენტაციის რეჟიმში არცერთი არ მუშაობს. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. გადატანის ჩართვისას სიის სიტყვა მხოლოდ აკრეფილ დეფისებთან გადაიტანება, ან არსად, თუ არ აქვს, რეგისტრის მიუხედავად; კორეულ სიტყვებს დეფისი არ ემატება, ინდური ენების სიტყვები კი სიმბოლოთა ჯგუფის შიგნით არ გადაიტანება. Reset all preferences to their defaults? დავაბრუნოთ ყველა პარამეტრი ნაგულისხმევ მნიშვნელობებზე? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. ნაგულისხმევი მნიშვნელობები გამოიყენება, როცა პარამეტრებში OK-ს დააჭერთ. იქ გაუქმება ინარჩუნებს თქვენს მიმდინარე პარამეტრებს. @@ -7124,6 +7153,10 @@ font-technology Variable ცვლადი @msg a guide has no curvature circle დამხმარე ხაზს სიმრუდის წრე არ აქვს @msg the circle that matches the path there would reach past the canvas წრეწირი, რომელიც იქ ტრაექტორიას შეესაბამება, ტილოს გასცდებოდა @msg no circle passes through these points: two are the same or all three lie on one line ამ წერტილებზე წრეწირი არ გადის: ორი ერთნაირია ან სამივე ერთ წრფეზე მდებარეობს +@msg `at` must be "start" or "end" `at` უნდა იყოს "start" ან "end" +@msg give exactly one of `through` and `toward` მიუთითეთ ზუსტად ერთი: `through` ან `toward` +@msg no arc fits these points: two are the same or all three lie on one line ამ წერტილებს რკალი არ ერგება: ორი ერთნაირია ან სამივე ერთ წრფეზე მდებარეობს +@msg give `at` only with `toward` `at` მიუთითეთ მხოლოდ `toward`-თან ერთად @msg no app to open files here აქ ფაილების გასახსნელი აპი არ არის @msg no artboard სამუშაო დაფა არ არის @msg no artboard {i} (0-based; the document has {_1}) სამუშაო დაფა {i} არ არსებობს (0-დან ითვლება; დოკუმენტს აქვს {_1}) @@ -7169,6 +7202,7 @@ font-technology Variable ცვლადი @msg no native format საკუთარი ფორმატი არ არის @msg no pages გვერდები არ არის @msg no pattern `{name}` პატერნი `{name}` არ არის +@msg art painted with `{name}` can't be its tile `{name}`-ით შეღებილი ნახატი მისი ფილა ვერ იქნება @msg no perspective grid preset named `{name}` პერსპექტივის ბადის პრესეტი სახელით `{name}` არ არის @msg no plug-in {0} is installed პლაგინი {0} დაინსტალირებული არ არის @msg no plug-in {id} is installed პლაგინი {id} დაინსტალირებული არ არის @@ -7871,6 +7905,7 @@ font-technology Variable ცვლადი Arrow ისარი Arrow (open) ისარი (ღია) Barbed წვეტიანი +arrowhead Feather ბუმბული Half Arrow (left) ნახევარი ისარი (მარცხენა) Half Arrow (right) ნახევარი ისარი (მარჯვენა) Concave ჩაზნექილი @@ -7898,6 +7933,7 @@ font-technology Variable ცვლადი Kite ფრანი Triangle to Bar სამკუთხედიდან ზოლამდე Oval ოვალი + Line Arrow ხაზოვანი ისარი Complementary დამატებითი Complementary 2 დამატებითი 2 Split Complementary გაყოფილი დამატებითი @@ -8747,6 +8783,8 @@ liquify-list-end {0}, {1} {0} და {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` უნდა იყოს grayscale, rgb, hsb, cmyk ან websafe @msg `view` must be wheel or box `view` უნდა იყოს wheel ან box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` უნდა იყოს hue, saturation, brightness, red, green ან blue +@msg `sliders` must be none, oklch or hsl `sliders` უნდა იყოს none, oklch ან hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH-ს სამუშაო RGB სივრცედ sRGB სჭირდება @msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), not a PDF: File › Open and File › Place read it as EPS ეს PostScript ფაილია (ძველ ფორმატში ან PDF-თან თავსებადობის გარეშე შენახული .ai, ან EPS ფაილი) და არა PDF: ფაილი › გახსნა და ფაილი › განთავსება მას EPS-ად კითხულობს # Upstream sync 2026-10-16 (3): Intertwine, symbol registration, gradient span, data sets, Batch. Intertwine გადახლართვა @@ -10470,6 +10508,7 @@ breakText Glyphs გლიფები Remove Strokes კონტურების მოხსნა Place Brush Art ფუნჯის ნახატის განთავსება Replace Brush Art ფუნჯის ნახატის ჩანაცვლება + Replace Pattern Art პატერნის ნახატის ჩანაცვლება Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? კონტურები იყენებს ამ ფუნჯს. გამოყენებულ იქნას ახალი ნახატი ამ კონტურებზე, თუ დარჩეს ისინი როგორც არის და დაემატოს ფუნჯის ასლი ახალი ნახატით? Apply to Strokes კონტურებზე გამოყენება Leave Strokes კონტურების დატოვება @@ -11004,6 +11043,21 @@ font-script Japanese იაპონური @msg A joint does not close by {gap} pt. შეერთება არ იხურება {gap} pt-ით. @msg Two panels pass through each other. ორი პანელი ერთმანეთში გადის. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine" + Orbit Lines ორბიტული ხაზები + Petal Garland ფურცლების გირლანდა + Lattice Braid ბადის ნაწნავი + Facet Sweep წახნაგოვანი მონასმი + Artistic Brushes მხატვრული ფუნჯები + Paint საღებავი + Flat Sweep ბრტყელი მოსმა + Dry Drag მშრალი მოსმა + Loaded Stroke სქელი მონასმი + Fan Sweep მარაოსებრი მოსმა + Engraving გრავიურა + Fine Hatching წვრილი შტრიხები + Dense Hatching მჭიდრო შტრიხები + Tapered Hatching შევიწროებული შტრიხები + Broken Hatching წყვეტილი შტრიხები Image Brush გამოსახულების ფუნჯები Soft Bloom რბილი ყვავილი Halftone Field ნახევარტონური ველი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 8643f68384..65cc2ef2a9 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -839,6 +839,8 @@ digits Malayalam 말라얄람어 Contextual Task Bar 상황별 작업 표시줄 Pin Bar Position 표시줄 위치 고정 Reset Bar Position 표시줄 위치 재설정 + Bar Actions 표시줄 동작 + Reset Bar Actions 표시줄 동작 재설정 Resize 크기 조절 Tools 도구 Toolbars 도구 모음 @@ -1145,6 +1147,7 @@ digits Malayalam 말라얄람어 Add Selected Artwork as One Asset 선택한 아트워크를 하나의 에셋으로 추가 Add Spine Point 스파인 포인트 추가 Add Used Colors 사용한 색상 추가 + Add Selected Colors 선택한 색상 추가 Add to Graphic Styles 그래픽 스타일에 추가 Add to Profiles 프로필에 추가 Add to Profiles… 프로필에 추가… @@ -1225,6 +1228,10 @@ antiAlias Sharp 날카롭게 @plural Apply to All ({n} more missing)|Apply to All ({n} more missing) 모두에 적용(누락 {n}개 더 있음) Arc 호 Arc Tool 호 도구 + Three-Point Arc Tool 3점 호 도구 + Three-Point Arc 3점 호 + Arc too large 호가 너무 큽니다 + Third Point Sets Direction 세 번째 점으로 방향 지정 Area / Path Type 영역/패스 문자 Area Graph Tool 영역 그래프 도구 Area Type Tool 영역 문자 도구 @@ -2105,6 +2112,10 @@ antiAlias Sharp 날카롭게 Add Color Tool 색상 추가 도구 Remove Color Tool 색상 제거 도구 Remove Color 색상 제거 + Set As Base Color 기본 색상으로 설정 + Select Shade 음영 선택 + Add New Color 새 색상 추가 + Set Current Color As Base Color 현재 색상을 기본 색상으로 설정 Find the selected colors in the artwork 선택한 색상을 아트웍에서 찾기 Height 높이 Height: 높이: @@ -2976,6 +2987,11 @@ diagnostics ui UI Preserve Alpha Transparency 알파 투명도 보존 Preserve Appearance and Overprints 모양 및 오버프린트 보존 Preserve CMYK Numbers CMYK 수치 보존 + Preserve RGB Numbers RGB 수치 보존 + Device to Simulate: 시뮬레이션할 장치: + Simulate Paper Color 용지 색상 시뮬레이션 + Simulate Black Ink 검정 잉크 시뮬레이션 + Load… 불러오기… Preserve Editing Capabilities 편집 기능 보존 Preserve Lightness 명도 보존 Preserve Overprints and Spot Colors 오버프린트 및 별색 보존 @@ -3373,9 +3389,11 @@ mark-style Japanese 일본식 Edit type set in fonts that aren't available? 사용할 수 없는 글꼴로 설정된 문자를 편집하시겠습니까? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. 캔버스에서 각 슬라이스의 번호를 왼쪽 위의 상자에 표시합니다. 끄더라도 슬라이스 윤곽선은 계속 표시됩니다. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. 사용자 슬라이스와 개체 슬라이스의 윤곽선 및 번호 상자의 색상입니다. 자동 슬라이스에는 이 색상의 더 흐린 색조가 사용됩니다. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. 문서 설정의 언어가 영어: 미국인 동안 새 텍스트는 이 언어를 받습니다. 문서에 이미 있는 텍스트는 자체 언어를 유지합니다. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. 문서 설정의 언어가 영어: 미국이고 [기본 문자 스타일]이 언어를 지정하지 않는 동안 새 텍스트는 이 언어를 받습니다. 문서에 이미 있는 텍스트는 자체 언어를 유지합니다. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. 하이픈 넣기가 켜진 단락에서는 목록의 단어가 입력한 하이픈 위치에서만 나뉘며, 하이픈이 없으면 나뉘지 않습니다. 언어나 대소문자는 상관없습니다. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. 데스크톱 버전에서는 이 폴더의 .wasm 플러그인이 시작할 때와 여기에 새 폴더를 지정하고 확인을 클릭할 때 로드됩니다(안전 모드 제외). 웹 버전은 로드하지 않습니다. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. 표준은 각 플러그인 자체의 제한을 유지합니다. 크게에서는 플러그인 필터나 명령이 입력에 필요한 명령어 외에 최소 2억 5천만 개의 명령어를 실행할 수 있습니다. 시간 제한은 그대로입니다. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. 플러그인의 개체 필터를 한 번 실행할 때 쓸 수 있는 명령어 수입니다. 크게는 표준보다 많이 허용하며 60초 제한은 같습니다. 무거운 필터는 자체 예산을 유지합니다. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. 첫 번째 스크래치 디스크 선택: Startup, None 또는 폴더 경로. VectorCraft는 이 값을 저장하지만 아직 스크래치 디스크를 사용하지 않습니다. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. 두 번째 스크래치 디스크 선택: Startup, None 또는 폴더 경로. VectorCraft는 이 값을 저장하지만 아직 스크래치 디스크를 사용하지 않습니다. How light or dark the interface is. 인터페이스를 얼마나 밝게 또는 어둡게 표시할지입니다. @@ -3393,7 +3411,10 @@ mark-style Japanese 일본식 The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. 인터페이스의 언어입니다. 자동은 시스템 언어를 사용합니다. 언어를 고르면 대화 상자가 바로 그 언어로 바뀝니다. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. 애니메이션 확대/축소는 이 옵션이 켜져 있을 때만 작동합니다. 끄면 애니메이션 확대/축소가 흐리게 표시되고 확대/축소에 애니메이션이 없습니다. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. 휠로 확대/축소하면 부드럽게 움직이고, 확대/축소 도구는 옆으로 드래그하거나 누르고 있으면 확대/축소합니다. 끄면 확대/축소 도구는 드래그한 영역으로 확대합니다. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. 다음 시작부터 데스크톱 버전은 이 종류의 그래픽 프로세서를 통해 캔버스를 표시합니다. 아트워크는 항상 CPU에서 그려집니다. 자동은 Windows와 macOS에서 내장 프로세서를 우선합니다. 웹 버전은 사용하지 않습니다. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. 다음 시작부터 그래픽 드라이버가 허용하는 경우 창은 디스플레이 새로 고침을 기다리지 않고 각 프레임을 표시하며, 초당 최대 240프레임입니다. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. 다음 시작부터 데스크톱 버전은 이 종류의 그래픽 프로세서로 그립니다. 자동은 디스플레이를 구동하는 프로세서를 우선합니다. 웹 버전은 사용하지 않습니다. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. 다음 시작부터 창은 디스플레이 새로 고침을 기다리지 않고 프레임을 표시하며, 초당 최대 240프레임입니다. 끄면 디스플레이가 프레임 속도를 정합니다. 시작할 때 지정한 표시 모드가 우선합니다. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. 각 문서가 보관하는 실행 취소 단계의 최대 수입니다. 낮추면 확인을 클릭할 때 가장 오래된 단계가 삭제됩니다. 메모리를 너무 많이 쓰면 단계가 더 일찍 삭제될 수도 있습니다. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. 드래그하는 동안 아트가 바뀌는 모습을 보여 줍니다. 끄면 윤곽선이 드래그를 따라가고 놓을 때 아트가 바뀝니다. 눈금자 안내선은 드래그하는 동안 항상 움직입니다. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. 아트를 그리는 작업자 스레드 수입니다. -1은 VectorCraft가 쓸 수 있는 코어보다 하나 적게(최대 8개) 쓰고, 0은 하나도 쓰지 않습니다. 웹 버전은 항상 쓰지 않습니다. @@ -3420,7 +3441,10 @@ mark-style Japanese 일본식 VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft는 이 선택을 저장하지만 복사와 잘라내기는 아직 레거시 벡터 클립보드 형식을 사용하지 않습니다. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. 레거시 벡터 클립보드의 패스 보존 또는 모양 및 오버프린트 보존입니다. VectorCraft는 선택을 저장하지만 아직 사용하지 않습니다. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. 서식 유지는 VectorCraft 텍스트 개체에서 복사한 텍스트를 텍스트 개체에 붙여넣을 때 스타일을 유지하고, 일반 텍스트 유지는 붙여넣은 위치의 스타일을 적용합니다. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. 문서 설정의 언어가 영어: 미국이고 [기본 문자 스타일]이 언어를 지정하지 않는 동안 새 텍스트는 이 언어를 받습니다. 문서에 이미 있는 텍스트는 자체 언어를 유지합니다. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. 모든 검정을 리치 블랙으로 표시는 순수 CMYK 검정(검정 잉크만 100%)을 캔버스에서 RGB 검정으로 표시하고, 모든 검정 정확히 표시는 작업용 CMYK 공간을 통해 변환합니다. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. 모든 검정을 리치 블랙으로 출력은 RGB 및 그레이스케일 래스터 내보내기와 비트맵으로 인쇄에서 순수 CMYK 검정을 RGB 검정으로 그리며, 벡터 내보내기, CMYK JPEG, TIFF 및 PSD, 기타 인쇄는 바꾸지 않습니다. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. 터치 스크린에서는 터치 작업 영역으로 전환합니다. 이 설정을 끄거나 터치 스크린이 사라지면 전환하기 전의 작업 영역으로 돌아갑니다. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. 캔버스를 두 손가락으로 탭하면 실행 취소하거나 터치 작업 영역에서 선택 도구와 그리기 도구를 전환하고, 세 손가락으로 탭하면 다시 실행합니다. 프레젠테이션 모드에서는 둘 다 작동하지 않습니다. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. 하이픈 넣기가 켜진 단락에서는 목록의 단어가 입력한 하이픈 위치에서만 나뉘며, 하이픈이 없으면 나뉘지 않습니다. 대소문자는 상관없습니다. 한국어 단어에는 하이픈이 붙지 않으며, 인도 언어의 단어는 문자 묶음 안에서 나뉘지 않습니다. Reset all preferences to their defaults? 모든 환경 설정을 기본값으로 재설정하시겠습니까? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. 기본값은 환경 설정에서 확인을 클릭하면 적용됩니다. 그곳에서 취소를 누르면 현재 환경 설정이 유지됩니다. @@ -4386,6 +4410,11 @@ file-filter Templates 템플릿 Keep the pasted color as a new swatch with a numbered name. 붙여넣은 색상을 번호가 붙은 이름의 새 견본으로 보관합니다. Keep: 유지: Lab Lab + OKLCH Sliders OKLCH 슬라이더 + HSL Sliders HSL 슬라이더 + Chroma 크로마 + The largest chroma sRGB holds at this lightness and hue 이 명도와 색조에서 sRGB가 담을 수 있는 최대 크로마 + OKLCH needs sRGB as the working RGB space OKLCH를 사용하려면 작업 RGB 공간이 sRGB여야 합니다 Lab Values Lab 값 Large List View 큰 목록 보기 Large Thumbnail View 큰 축소판 보기 @@ -5077,6 +5106,10 @@ variable-list-end {0}, {1} {0} 및 {1} @msg a guide has no curvature circle 안내선에는 곡률원이 없습니다 @msg the circle that matches the path there would reach past the canvas 그 위치에서 패스에 맞는 원이 캔버스를 벗어납니다 @msg no circle passes through these points: two are the same or all three lie on one line 이 점들을 지나는 원이 없습니다: 두 점이 같거나 세 점이 모두 한 직선 위에 있습니다 +@msg `at` must be "start" or "end" `at`은(는) "start" 또는 "end"여야 합니다 +@msg give exactly one of `through` and `toward` `through`와 `toward` 중 정확히 하나만 지정하세요 +@msg no arc fits these points: two are the same or all three lie on one line 이 점들에 맞는 호가 없습니다: 두 점이 같거나 세 점이 모두 한 직선 위에 있습니다 +@msg give `at` only with `toward` `at`은(는) `toward`와 함께만 지정하세요 @msg select at least two objects 개체를 두 개 이상 선택하세요 @msg exit isolation mode first 먼저 격리 모드를 종료하세요 @msg no saved presets 저장된 프리셋이 없습니다 @@ -5123,6 +5156,7 @@ variable-list-end {0}, {1} {0} 및 {1} @msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label}의 결과가 비어 있습니다. 선이나 기타 열린 패스가 영역을 둘러싸지 않습니다. 포함하려면 먼저 개체 › 패스 › 선 윤곽선화를 적용하세요 @msg already editing a pattern 이미 패턴을 편집 중입니다 @msg no pattern `{name}` `{name}` 패턴이 없습니다 +@msg art painted with `{name}` can't be its tile `{name}` 패턴으로 칠한 아트웍은 그 타일이 될 수 없습니다 @msg not in pattern editing mode 패턴 편집 모드가 아닙니다 @msg finish editing the pattern first 먼저 패턴 편집을 마치세요 @msg pattern missing 패턴이 없습니다 @@ -5544,6 +5578,8 @@ variable-list-end {0}, {1} {0} 및 {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`은(는) grayscale, rgb, hsb, cmyk, websafe 중 하나여야 합니다 @msg `view` must be wheel or box `view`은(는) wheel, box 중 하나여야 합니다 @msg `channel` must be hue, saturation, brightness, red, green or blue `channel`은(는) hue, saturation, brightness, red, green, blue 중 하나여야 합니다 +@msg `sliders` must be none, oklch or hsl `sliders`는 none, oklch 또는 hsl이어야 합니다 +@msg OKLCH needs sRGB as the working RGB space OKLCH를 사용하려면 작업 RGB 공간이 sRGB여야 합니다 @msg `{key}` must be true or false `{key}`은(는) true 또는 false여야 합니다 @msg `top` and `below` can't both be true `top`과 `below`를 동시에 true로 지정할 수 없습니다 @msg `select` must be true or false `select`은(는) true 또는 false여야 합니다 @@ -7611,6 +7647,37 @@ anchor Points: 포인트: @msg `{id}` is not a colour adjustment `{id}`은(는) 색상 조정이 아닙니다 @msg missing `effect` `effect`이 없습니다 @msg `params` must be an object `params`는 개체여야 합니다 +# Stroke arrowheads (Stroke panel, Dimension Tool Options and Properties › Arrow Style). + Triangle (open) 삼각형 (윤곽) + Circle (open) 원 (윤곽) + Square (open) 사각 (윤곽) + Arrow (open) 화살표 (윤곽) + Barbed 미늘 +arrowhead Feather 깃털 +arrowhead Target 과녁 + Half Arrow (left) 반쪽 화살표 (왼쪽) + Half Arrow (right) 반쪽 화살표 (오른쪽) + Double Bar 이중 막대 + Dot on Bar 막대 위 점 + Chevron 갈매기형 + Plus 더하기 + Hexagon (open) 육각형 (윤곽) + Tag 태그 + Tag (open) 태그 (윤곽) + Half Circle 반원 + Drop 물방울 + Slash 슬래시 + Double Slash 이중 슬래시 + Diamond (open) 다이아몬드 (윤곽) + Reverse Triangle 역삼각형 + Swallowtail 제비 꼬리 + Bracket 대괄호 + Fork 포크 + Leaf 잎 + Kite 연 + Triangle to Bar 삼각형에서 막대 + Oval 타원 + Line Arrow 선 화살표 # Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. Path Precision Tools 패스 정밀 도구 Anchor Eraser Brush 앵커 포인트 지우개 브러시 @@ -7901,6 +7968,7 @@ breakText Glyphs 글리프 Remove Strokes 선 제거 Place Brush Art 브러시 아트 배치 Replace Brush Art 브러시 아트 바꾸기 + Replace Pattern Art 패턴 아트 바꾸기 Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? 선에서 이 브러시를 사용합니다. 새 아트를 해당 선에 적용하시겠습니까, 아니면 선을 그대로 두고 새 아트로 브러시 사본을 추가하시겠습니까? Apply to Strokes 선에 적용 Leave Strokes 선 유지 @@ -10327,6 +10395,21 @@ breakText Glyphs 글리프 @msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다. @msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 힌지: {hinges}, 오류: {errors}, 경고: {warnings} + Orbit Lines 궤도 선 + Petal Garland 꽃잎 화환 + Lattice Braid 격자 땋기 + Facet Sweep 면 분할 붓질 + Artistic Brushes 예술 브러시 + Paint 페인트 + Flat Sweep 평평한 붓질 + Dry Drag 마른 붓질 + Loaded Stroke 두터운 붓질 + Fan Sweep 부채꼴 붓질 + Engraving 판화 + Fine Hatching 가는 해칭 + Dense Hatching 촘촘한 해칭 + Tapered Hatching 가늘어지는 해칭 + Broken Hatching 끊긴 해칭 Image Brush 이미지 브러시 Soft Bloom 부드러운 꽃 Halftone Field 하프톤 필드 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 2dd8afceee..d0a2d9d8b9 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1376,6 +1376,8 @@ liquify-list-end {0}, {1} {0} en {1} Contextual Task Bar Contextuele taakbalk Pin Bar Position Balkpositie vastzetten Reset Bar Position Balkpositie herstellen + Bar Actions Balkacties + Reset Bar Actions Balkacties herstellen Tools Gereedschappen Toolbars Werkbalken Advanced Geavanceerd @@ -2053,6 +2055,10 @@ lighting Light Licht Add Anchor Point Tool Ankerpunt toevoegen Anchor Point Tool Ankerpunt-gereedschap Arc Tool Boog-gereedschap + Three-Point Arc Tool Driepuntsboog-gereedschap + Three-Point Arc Driepuntsboog + Arc too large Boog te groot + Third Point Sets Direction Derde punt geeft de richting aan Area Graph Tool Vlakdiagram-gereedschap Area Type Tool Vlaktype-gereedschap Artboard Tool Tekengebied-gereedschap @@ -3503,6 +3509,11 @@ digits Malayalam Malayalam Place the pages with the placement again Plaats de pagina's opnieuw met de plaatsing Placement: Plaatsing: Preserve CMYK Numbers CMYK-waarden behouden + Preserve RGB Numbers RGB-waarden behouden + Device to Simulate: Te simuleren apparaat: + Simulate Paper Color Papierkleur simuleren + Simulate Black Ink Zwarte inkt simuleren + Load… Laden… Previous page Vorige pagina Print Layers: Lagen afdrukken: Print Preset: Afdrukvoorinstelling: @@ -3580,6 +3591,10 @@ digits Malayalam Malayalam Add Color Tool Gereedschap Kleur toevoegen Remove Color Tool Gereedschap Kleur verwijderen Remove Color Kleur verwijderen + Set As Base Color Instellen als basiskleur + Select Shade Schakering selecteren + Add New Color Nieuwe kleur toevoegen + Set Current Color As Base Color Huidige kleur instellen als basiskleur Find the selected colors in the artwork De geselecteerde kleuren zoeken in de artwork Harmony Rules Harmonieregels Keep this row's colors (exclude) De kleuren van deze rij behouden (uitsluiten) @@ -4763,6 +4778,7 @@ theme Appearance Vormgeving Add to Graphic Styles Aan grafische stijlen toevoegen Graphic Style Library Bibliotheek met grafische stijlen Add Used Colors Gebruikte kleuren toevoegen + Add Selected Colors Geselecteerde kleuren toevoegen Delete Swatch Kleurstaal verwijderen Duplicate Swatch Kleurstaal dupliceren Merge Swatches Kleurstalen samenvoegen @@ -4960,6 +4976,11 @@ axis Both Beide Image Afbeelding Ink Inkt Lab Lab + OKLCH Sliders OKLCH-schuifregelaars + HSL Sliders HSL-schuifregelaars + Chroma Chroma + The largest chroma sRGB holds at this lightness and hue De grootste chroma die sRGB bij deze helderheid en tint bevat + OKLCH needs sRGB as the working RGB space OKLCH vereist sRGB als werk-RGB-ruimte Medium Gemiddeld Name Naam None Geen @@ -5170,9 +5191,11 @@ font-technology Variable Variabel Edit type set in fonts that aren't available? Tekst in lettertypen bewerken die niet beschikbaar zijn? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Toont op het canvas het nummer van elke slice in een vakje linksboven in de slice; staat dit uit, dan blijven de omtrekken van de slices zichtbaar. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. De kleur van de omtrekken van gebruikers- en objectslices en van hun nummervakjes; automatische slices gebruiken een vagere tint ervan. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Nieuwe tekst krijgt deze taal zolang de taal in Documentinstellingen Engels: VS is; tekst die al in een document staat, behoudt zijn eigen taal. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Nieuwe tekst krijgt deze taal zolang de taal in Documentinstellingen Engels: VS is en [Normale tekenstijl] geen taal instelt; tekst die al in een document staat, behoudt zijn eigen taal. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. In alinea's met Afbreken aan wordt een opgesomd woord alleen afgebroken bij de koppeltekens die erin getypt zijn, of nergens als het er geen heeft, ongeacht taal of hoofdletters. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. In de desktopversie worden de .wasm-plug-ins in deze map geladen bij het starten en wanneer u hier met een nieuwe map op OK klikt, behalve in de veilige modus; de webversie laadt ze niet. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normaal behoudt de eigen limieten van elke plug-in; met Groot mag een filter of opdracht van een plug-in ten minste 250 miljoen instructies uitvoeren naast die voor de invoer. De tijdslimiet blijft gelijk. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Hoeveel instructies elke uitvoering van een objectfilter uit een plug-in mag gebruiken; Groot staat er meer toe dan Normaal, met dezelfde limiet van 60 seconden. Zware filters houden hun eigen budget. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. De eerste keuze voor de scratchschijf: Startup, None of een mappad; VectorCraft slaat deze op, maar gebruikt nog geen scratchschijven. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. De tweede keuze voor de scratchschijf: Startup, None of een mappad; VectorCraft slaat deze op, maar gebruikt nog geen scratchschijven. How light or dark the interface is. Hoe licht of donker de gebruikersinterface is. @@ -5190,7 +5213,10 @@ font-technology Variable Variabel The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. De taal van de gebruikersinterface; Automatisch gebruikt de taal van het systeem. Het dialoogvenster wisselt van taal zodra u er een kiest. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Geanimeerd zoomen werkt alleen zolang dit aan staat; uit is Geanimeerd zoomen gedimd en wordt zoomen niet geanimeerd. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Zoomen met het wieltje glijdt soepel, en het Zoom-gereedschap zoomt terwijl u opzij sleept of het ingedrukt houdt; uit zoomt het Zoom-gereedschap in op het gebied waarover u sleept. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Vanaf de volgende start toont de desktopversie het canvas via dit soort grafische processor; de illustratie wordt hoe dan ook op de CPU getekend. Automatisch kiest op Windows en macOS bij voorkeur de geïntegreerde. De webversie gebruikt het niet. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Vanaf de volgende start toont het venster elk beeld zonder op de verversing van het beeldscherm te wachten, waar het grafische stuurprogramma dat toestaat, met hoogstens 240 beelden per seconde. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Vanaf de volgende start tekent de desktopversie met dit soort grafische processor; Automatisch kiest bij voorkeur de processor die het beeldscherm aanstuurt. De webversie gebruikt het niet. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Vanaf de volgende start toont het venster beelden zonder op de verversing van het beeldscherm te wachten, hoogstens 240 per seconde; uit bepaalt het beeldscherm het tempo. Een presentatiemodus die bij het starten is ingesteld, gaat voor. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Het grootste aantal ongedaanmaakstappen dat elk document bewaart; een lager getal verwijdert de oudste stappen wanneer u op OK klikt. Stappen kunnen ook eerder verdwijnen als ze te veel geheugen gebruiken. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Toont tijdens het slepen hoe de illustratie verandert; uit volgen contouren het slepen en verandert de illustratie wanneer u loslaat. Een hulplijn van de liniaal beweegt altijd mee tijdens het slepen. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Hoeveel werkthreads de illustratie tekenen; -1 gebruikt er één minder dan de kernen die VectorCraft mag gebruiken, hoogstens 8, en 0 geen. De webversie gebruikt er nooit een. @@ -5217,7 +5243,10 @@ font-technology Variable Variabel VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft slaat deze keuze op, maar Kopiëren en Knippen gebruiken nog geen indeling van het verouderde vectorklembord. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Paden behouden of Vormgeving en overprint behouden voor het verouderde vectorklembord; VectorCraft slaat de keuze op, maar gebruikt die nog niet. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. Opmaak behouden behoudt de stijlen van tekst uit een tekstobject in VectorCraft wanneer die in een tekstobject wordt geplakt; Platte tekst behouden geeft die de stijl van de plek waar hij terechtkomt. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Nieuwe tekst krijgt deze taal zolang de taal in Documentinstellingen Engels: VS is en [Normale tekenstijl] geen taal instelt; tekst die al in een document staat, behoudt zijn eigen taal. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. Alle zwarttinten weergeven als rijk zwart toont zuiver CMYK-zwart (alleen zwarte inkt op 100%) op het canvas als RGB-zwart; Alle zwarttinten nauwkeurig weergeven zet het om via de werk-CMYK-kleurruimte. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Alle zwarttinten uitvoeren als rijk zwart tekent zuiver CMYK-zwart als RGB-zwart in RGB- en grijswaarden-rasterexports en met Afdrukken als bitmap; het verandert niets aan vectorexports, CMYK-JPEG, -TIFF en -PSD of ander afdrukken. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Op een aanraakscherm wordt naar de Touch-werkruimte gewisseld; uitschakelen of het wegvallen van het aanraakscherm zet de werkruimte van daarvoor terug. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Tikken met twee vingers op het canvas maakt ongedaan of wisselt in de Touch-werkruimte tussen selectie- en tekengereedschap, en tikken met drie vingers voert opnieuw uit; geen van beide werkt in de presentatiemodus. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. In alinea's met Afbreken aan wordt een opgesomd woord alleen afgebroken bij de koppeltekens die erin getypt zijn, of nergens als het er geen heeft, ongeacht hoofdletters; Koreaanse woorden krijgen geen afbreekstreepje, en woorden in Indiase talen worden niet binnen een tekengroep afgebroken. Reset all preferences to their defaults? Alle voorkeuren terugzetten naar de standaardwaarden? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. De standaardwaarden worden toegepast wanneer u in Voorkeuren op OK klikt. Annuleren daar behoudt uw huidige voorkeuren. @@ -5741,6 +5770,10 @@ imageTrace Outline Contour @msg a guide has no curvature circle een hulplijn heeft geen krommingscirkel @msg the circle that matches the path there would reach past the canvas de cirkel die daar bij het pad past, zou voorbij het canvas reiken @msg no circle passes through these points: two are the same or all three lie on one line er gaat geen cirkel door deze punten: twee zijn gelijk of alle drie liggen op één lijn +@msg `at` must be "start" or "end" `at` moet "start" of "end" zijn +@msg give exactly one of `through` and `toward` geef precies één van `through` en `toward` +@msg no arc fits these points: two are the same or all three lie on one line er past geen boog bij deze punten: twee zijn gelijk of alle drie liggen op één lijn +@msg give `at` only with `toward` geef `at` alleen samen met `toward` @msg no app to open files here hier is geen app om bestanden mee te openen @msg no artboard geen tekengebied @msg no artboard {i} (0-based; the document has {_1}) geen tekengebied {i} (vanaf 0; het document heeft er {_1}) @@ -5784,6 +5817,7 @@ imageTrace Outline Contour @msg no native format geen eigen indeling @msg no pages geen pagina's @msg no pattern `{name}` geen patroon `{name}` +@msg art painted with `{name}` can't be its tile illustratie die met `{name}` is geverfd, kan niet de tegel ervan zijn @msg no perspective grid preset named `{name}` geen perspectiefrastervoorinstelling met de naam `{name}` @msg no plug-in {0} is installed er is geen plug-in {0} geïnstalleerd @msg no plug-in {id} is installed er is geen plug-in {id} geïnstalleerd @@ -8290,6 +8324,7 @@ imageTrace Outline Contour Arrow Pijl Arrow (open) Pijl (open) Barbed Weerhaak +arrowhead Feather Veer Half Arrow (left) Halve pijl (links) Half Arrow (right) Halve pijl (rechts) Concave Concaaf @@ -8317,6 +8352,7 @@ imageTrace Outline Contour Kite Vlieger Triangle to Bar Driehoek naar balk Oval Ovaal + Line Arrow Lijnpijl Complementary Complementair Complementary 2 Complementair 2 Split Complementary Gesplitst complementair @@ -8863,6 +8899,8 @@ mark-style Japanese Japans @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` moet grayscale, rgb, hsb, cmyk of websafe zijn @msg `view` must be wheel or box `view` moet wheel of box zijn @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` moet hue, saturation, brightness, red, green of blue zijn +@msg `sliders` must be none, oklch or hsl `sliders` moet none, oklch of hsl zijn +@msg OKLCH needs sRGB as the working RGB space OKLCH vereist sRGB als werk-RGB-ruimte @msg the Color Picker is not open de kleurenkiezer is niet open @msg the screen color sampler is already open de schermkleurkiezer is al open @msg this system has no screen color sampler dit systeem heeft geen schermkleurkiezer @@ -10190,6 +10228,7 @@ breakText Glyphs Glyphs Remove Strokes Contouren verwijderen Place Brush Art Penseelillustratie plaatsen Replace Brush Art Penseelillustratie vervangen + Replace Pattern Art Patroonillustratie vervangen Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Contouren gebruiken dit penseel. De nieuwe illustratie op deze contouren toepassen, of ze laten zoals ze zijn en een kopie van het penseel met de nieuwe illustratie toevoegen? Apply to Strokes Op contouren toepassen Leave Strokes Contouren behouden @@ -10757,6 +10796,21 @@ breakText Glyphs Glyphs @msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden. @msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, scharnieren: {hinges}, fouten: {errors}, waarschuwingen: {warnings} + Orbit Lines Baanlijnen + Petal Garland Bloemblaadjesslinger + Lattice Braid Rastervlecht + Facet Sweep Gefacetteerde streek + Artistic Brushes Artistieke penselen + Paint Verf + Flat Sweep Vlakke streek + Dry Drag Droge sleep + Loaded Stroke Dikke verfstreek + Fan Sweep Waaierstreek + Engraving Gravure + Fine Hatching Fijne arcering + Dense Hatching Dichte arcering + Tapered Hatching Taps toelopende arcering + Broken Hatching Onderbroken arcering Image Brush Afbeeldingspenselen Soft Bloom Zachte bloei Halftone Field Halftoonveld diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 5a7e411934..b1c52b9c56 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -758,6 +758,8 @@ Contextual Task Bar Kontekstowy pasek zadań Pin Bar Position Przypnij położenie paska Reset Bar Position Resetuj położenie paska + Bar Actions Akcje paska + Reset Bar Actions Resetuj akcje paska Resize Zmień rozmiar Tools Narzędzia Toolbars Paski narzędzi @@ -1457,6 +1459,10 @@ lighting Light Światło Add Anchor Point Tool Narzędzie Dodaj punkt kontrolny Anchor Point Tool Narzędzie Punkt kontrolny Arc Tool Narzędzie Łuk + Three-Point Arc Tool Narzędzie Łuk przez trzy punkty + Three-Point Arc Łuk przez trzy punkty + Arc too large Łuk jest za duży + Third Point Sets Direction Trzeci punkt wyznacza kierunek Area Graph Tool Narzędzie Wykres warstwowy Area Type Tool Narzędzie Tekst akapitowy Artboard Tool Narzędzie Obszar kompozycji @@ -3021,6 +3027,11 @@ digits Malayalam Malajalam Place the pages with the placement again Ponownie rozmieść strony według położenia Placement: Położenie: Preserve CMYK Numbers Zachowaj wartości CMYK + Preserve RGB Numbers Zachowaj wartości RGB + Device to Simulate: Symulowane urządzenie: + Simulate Paper Color Symuluj kolor papieru + Simulate Black Ink Symuluj czarną farbę + Load… Wczytaj… Previous page Poprzednia strona Print Layers: Drukuj warstwy: Print Preset: Ustawienie drukowania: @@ -3095,6 +3106,10 @@ digits Malayalam Malajalam Add Color Tool Narzędzie Dodaj kolor Remove Color Tool Narzędzie Usuń kolor Remove Color Usuń kolor + Set As Base Color Ustaw jako kolor bazowy + Select Shade Wybierz odcień + Add New Color Dodaj nowy kolor + Set Current Color As Base Color Ustaw bieżący kolor jako bazowy Find the selected colors in the artwork Znajdź zaznaczone kolory w kompozycji Keep this row's colors (exclude) Zachowaj kolory tego wiersza (wyklucz) Limit to Library: Ogranicz do biblioteki: @@ -4299,6 +4314,7 @@ theme Appearance Wygląd Add to Graphic Styles Dodaj do stylów graficznych Graphic Style Library Biblioteka stylów graficznych Add Used Colors Dodaj użyte kolory + Add Selected Colors Dodaj zaznaczone kolory Delete Swatch Usuń próbkę Duplicate Swatch Powiel próbkę Merge Swatches Scal próbki @@ -4487,6 +4503,11 @@ axis Both Obie Image Obraz Ink Farba Lab Lab + OKLCH Sliders Suwaki OKLCH + HSL Sliders Suwaki HSL + Chroma Chroma + The largest chroma sRGB holds at this lightness and hue Największa chroma, jaką sRGB mieści przy tej jasności i barwie + OKLCH needs sRGB as the working RGB space OKLCH wymaga sRGB jako roboczej przestrzeni RGB Medium Średni Name Nazwa None Brak @@ -4702,6 +4723,8 @@ font-technology Variable Zmienne New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Nowy tekst otrzymuje ten język, dopóki językiem w Ustawieniach dokumentu jest Angielski: USA; tekst, który już jest w dokumencie, zachowuje swój język. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. W akapitach z włączoną opcją Dziel wyrazy wyraz z listy jest dzielony tylko w miejscach wpisanych w nim łączników albo wcale, jeśli ich nie ma, bez względu na język i wielkość liter. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. W wersji na komputer wtyczki .wasm z tego folderu są wczytywane przy uruchomieniu i po kliknięciu OK z nowym folderem tutaj, z wyjątkiem trybu awaryjnego; wersja internetowa ich nie wczytuje. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normalny zachowuje własne limity każdej wtyczki; przy ustawieniu Duże filtr lub polecenie wtyczki może wykonać co najmniej 250 milionów instrukcji oprócz tych na swoje dane wejściowe. Limit czasu pozostaje bez zmian. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Ile instrukcji może zużyć każde uruchomienie filtra obiektów z wtyczki; Duże pozwala na więcej niż Normalny przy tym samym limicie 60 sekund. Ciężkie filtry zachowują własny budżet. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Pierwszy wybór dysku roboczego: Startup, None lub ścieżka folderu; VectorCraft go zapisuje, ale jeszcze nie używa dysków roboczych. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Drugi wybór dysku roboczego: Startup, None lub ścieżka folderu; VectorCraft go zapisuje, ale jeszcze nie używa dysków roboczych. How light or dark the interface is. Jak jasny lub ciemny jest interfejs. @@ -4720,13 +4743,16 @@ font-technology Variable Zmienne Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Animowane powiększanie działa tylko wtedy, gdy to jest włączone; po wyłączeniu Animowane powiększanie jest wyszarzone, a powiększanie nie jest animowane. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Powiększanie kółkiem przebiega płynnie, a Narzędzie Lupka powiększa, gdy przeciągasz w bok lub je przytrzymujesz; po wyłączeniu Narzędzie Lupka powiększa obszar, przez który przeciągniesz. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Od następnego uruchomienia wersja na komputer rysuje tym rodzajem procesora graficznego; Automatycznie wybiera najpierw ten, który obsługuje ekran. Wersja internetowa go nie używa. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Od następnego uruchomienia wersja na komputer wyświetla obszar roboczy przez ten rodzaj procesora graficznego; kompozycja jest zawsze rysowana na CPU. Automatycznie w systemach Windows i macOS wybiera najpierw zintegrowany. Wersja internetowa go nie używa. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Od następnego uruchomienia okno wyświetla każdą klatkę bez czekania na odświeżenie ekranu, jeśli pozwala na to sterownik grafiki, najwyżej 240 klatek na sekundę. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Od następnego uruchomienia okno pokazuje klatki bez czekania na odświeżenie ekranu, najwyżej 240 na sekundę; po wyłączeniu tempo wyznacza ekran. Tryb prezentacji ustawiony przy uruchomieniu ma pierwszeństwo. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Największa liczba kroków cofania, które zachowuje każdy dokument; mniejsza liczba usuwa najstarsze kroki po kliknięciu OK. Kroki mogą też zniknąć wcześniej, gdy zajmują zbyt dużo pamięci. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Pokazuje zmiany kompozycji podczas przeciągania; po wyłączeniu kontury podążają za przeciąganiem, a kompozycja zmienia się po puszczeniu. Linia pomocnicza z linijki zawsze porusza się podczas przeciągania. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Ile wątków roboczych rysuje kompozycję; -1 używa o jeden mniej niż rdzeni, których VectorCraft może używać, najwyżej 8, a 0 żadnego. Wersja internetowa nigdy żadnego nie używa. From the next start on a Wayland desktop, X11 (XWayland) opens the window through XWayland; the other choices do so only when a pen is attached. Od następnego uruchomienia na pulpicie Wayland X11 (XWayland) otwiera okno przez XWayland; inne wybory robią to tylko wtedy, gdy podłączone jest pióro. + Converts the artwork and artboards on the canvas to the display's color profile where the system does not already do so; off, the canvas is drawn in sRGB. Konwertuje kompozycję i obszary kompozycji na płótnie do profilu kolorów ekranu tam, gdzie system tego jeszcze nie robi; po wyłączeniu płótno jest rysowane w sRGB. From the next start, the desktop version shows frames without waiting for the display's refresh, at most 240 a second; off, the display paces them. Od następnego uruchomienia wersja na komputer wyświetla klatki bez czekania na odświeżenie ekranu, najwyżej 240 na sekundę; po wyłączeniu tempo wyznacza ekran. The larger budget raises each object filter run's base instructions fivefold and keeps the same allowance per input byte; heavy filters, live effects, exporters and importers keep their own limits. Większy budżet pięciokrotnie zwiększa podstawową liczbę instrukcji każdego uruchomienia filtra obiektów i zachowuje ten sam dodatek na bajt danych wejściowych; ciężkie filtry, efekty na żywo, eksportery i importery zachowują własne limity. - Converts the artwork and artboards on the canvas to the display's color profile where the system does not already do so; off, the canvas is drawn in sRGB. Konwertuje kompozycję i obszary kompozycji na płótnie do profilu kolorów ekranu tam, gdzie system tego jeszcze nie robi; po wyłączeniu płótno jest rysowane w sRGB. On the desktop, a save to a file is written in the background while you keep editing; off, you wait until it is written. W wersji na komputer zapis do pliku odbywa się w tle, gdy dalej edytujesz; po wyłączeniu czekasz, aż zostanie zapisany. On the desktop, exports to files and packages are written in the background while you keep editing, except 3D exports; off, you wait for them. W wersji na komputer eksporty do plików i pakiety są zapisywane w tle, gdy dalej edytujesz, z wyjątkiem eksportów 3D; po wyłączeniu na nie czekasz. Every few minutes, keeps a recovery copy of each document with unsaved changes made since its last copy; off, no timed copies are made. Co kilka minut zachowuje kopię odzyskiwania każdego dokumentu z niezapisanymi zmianami od jego ostatniej kopii; po wyłączeniu kopie okresowe nie powstają. @@ -4746,6 +4772,10 @@ font-technology Variable Zmienne VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft zapisuje ten wybór, ale Kopiuj i Wytnij nie używają jeszcze formatu starszego schowka wektorowego. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Zachowaj ścieżki lub Zachowaj wygląd i nadruki dla starszego schowka wektorowego; VectorCraft zapisuje wybór, ale jeszcze go nie używa. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. Zachowaj formatowanie zachowuje style tekstu skopiowanego z obiektu tekstowego VectorCraft po wklejeniu do obiektu tekstowego; Zachowaj zwykły tekst nadaje mu styl miejsca, w które trafia. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. Wyświetlaj wszystkie czernie jako czerń głęboką pokazuje czystą czerń CMYK (sam czarny atrament w 100%) na obszarze roboczym jako czerń RGB; Wyświetlaj wszystkie czernie dokładnie przekształca ją przez roboczą przestrzeń CMYK. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Wyprowadzaj wszystkie czernie jako czerń głęboką rysuje czystą czerń CMYK jako czerń RGB w rastrowych eksportach RGB i w skali szarości oraz przy Drukuj jako bitmapę; nie zmienia eksportów wektorowych, plików JPEG, TIFF i PSD CMYK ani innego drukowania. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Na ekranie dotykowym przełącza na dotykowy obszar roboczy; wyłączenie opcji lub utrata ekranu dotykowego przywraca obszar roboczy sprzed przełączenia. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Stuknięcie dwoma palcami w obszar roboczy cofa, a w dotykowym obszarze roboczym przełącza między narzędziami zaznaczania i rysowania; stuknięcie trzema palcami ponawia. Żadne nie działa w trybie prezentacji. New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Nowy tekst otrzymuje ten język, dopóki językiem w Ustawieniach dokumentu jest Angielski: USA, a [Normalny styl znakowy] nie ustawia języka; tekst, który już jest w dokumencie, zachowuje swój język. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. W akapitach z włączoną opcją Dziel wyrazy wyraz z listy jest dzielony tylko w miejscach wpisanych w nim łączników albo wcale, jeśli ich nie ma, bez względu na wielkość liter; wyrazy koreańskie nie dostają łącznika, a wyrazy w językach indyjskich nie są dzielone wewnątrz grupy znaków. Reset all preferences to their defaults? Przywrócić domyślne wartości wszystkich preferencji? @@ -5293,6 +5323,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` musi mieć wartość grayscale, rgb, hsb, cmyk lub websafe @msg `view` must be wheel or box `view` musi mieć wartość wheel lub box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` musi mieć wartość hue, saturation, brightness, red, green lub blue +@msg `sliders` must be none, oklch or hsl `sliders` musi mieć wartość none, oklch lub hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH wymaga sRGB jako roboczej przestrzeni RGB @msg `{k}` must be [x, y] `{k}` musi mieć postać [x, y] @msg `{name}` has no options `{name}` nie ma opcji @msg `{name}` is a built-in workspace; choose another name `{name}` to wbudowany obszar roboczy; wybierz inną nazwę @@ -5486,6 +5518,10 @@ liquify-list-end {0}, {1} {0} i {1} @msg a guide has no curvature circle linia pomocnicza nie ma okręgu krzywizny @msg the circle that matches the path there would reach past the canvas okrąg pasujący w tym miejscu do ścieżki wykroczyłby poza płótno @msg no circle passes through these points: two are the same or all three lie on one line przez te punkty nie przechodzi żaden okrąg: dwa są takie same albo wszystkie trzy leżą na jednej prostej +@msg `at` must be "start" or "end" `at` musi mieć wartość "start" lub "end" +@msg give exactly one of `through` and `toward` podaj dokładnie jeden z parametrów `through` i `toward` +@msg no arc fits these points: two are the same or all three lie on one line żaden łuk nie pasuje do tych punktów: dwa są takie same albo wszystkie trzy leżą na jednej prostej +@msg give `at` only with `toward` podaj `at` tylko razem z `toward` @msg no app to open files here brak aplikacji do otwierania plików @msg no artboard brak obszaru kompozycji @msg no artboard {i} (0-based; the document has {_1}) brak obszaru kompozycji {i} (numeracja od 0; dokument ma {_1}) @@ -5531,6 +5567,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg no native format brak formatu natywnego @msg no pages brak stron @msg no pattern `{name}` brak wzorka `{name}` +@msg art painted with `{name}` can't be its tile kompozycja malowana wzorkiem `{name}` nie może być jego kafelkiem @msg no perspective grid preset named `{name}` brak ustawienia siatki perspektywy o nazwie `{name}` @msg no plug-in {0} is installed wtyczka {0} nie jest zainstalowana @msg no plug-in {id} is installed wtyczka {id} nie jest zainstalowana @@ -6353,6 +6390,7 @@ variable-list-end {0}, {1} {0} i {1} Arrow Strzałka Arrow (open) Strzałka (otwarta) Barbed Zadziorowata +arrowhead Feather Pióro Half Arrow (left) Pół strzałki (lewa) Half Arrow (right) Pół strzałki (prawa) Concave Wklęsła @@ -6380,6 +6418,7 @@ variable-list-end {0}, {1} {0} i {1} Kite Latawiec Triangle to Bar Trójkąt z kreską Oval Owal + Line Arrow Strzałka liniowa Complementary Dopełniające Complementary 2 Dopełniające 2 Split Complementary Rozdzielone dopełniające @@ -8153,6 +8192,7 @@ breakText Glyphs Glify Remove Strokes Usuń obrysy Place Brush Art Umieść kompozycję pędzla Replace Brush Art Zastąp kompozycję pędzla + Replace Pattern Art Zastąp kompozycję wzorka Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Obrysy używają tego pędzla. Zastosować nową kompozycję do tych obrysów, czy pozostawić je bez zmian i dodać kopię pędzla z nową kompozycją? Apply to Strokes Zastosuj do obrysów Leave Strokes Pozostaw obrysy @@ -10581,6 +10621,21 @@ breakText Glyphs Glify @msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania. @msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, zawiasy: {hinges}, błędy: {errors}, ostrzeżenia: {warnings} + Orbit Lines Linie orbitalne + Petal Garland Girlanda płatków + Lattice Braid Plecionka kratowa + Facet Sweep Fasetowane pociągnięcie + Artistic Brushes Pędzle artystyczne + Paint Farba + Flat Sweep Płaskie pociągnięcie + Dry Drag Suche przeciągnięcie + Loaded Stroke Grube pociągnięcie + Fan Sweep Wachlarzowy ślad + Engraving Grawerowanie + Fine Hatching Drobne kreskowanie + Dense Hatching Gęste kreskowanie + Tapered Hatching Zwężane kreskowanie + Broken Hatching Przerywane kreskowanie Image Brush Pędzle obrazkowe Soft Bloom Miękki kwiat Halftone Field Pole półtonów diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index bf6404ec44..076c81d90f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -141,6 +141,7 @@ Add Selected Artwork as One Asset Adicionar Arte Selecionada como Um Ativo Add Spine Point Adicionar Ponto de Coluna Add Used Colors Adicionar Cores Usadas + Add Selected Colors Adicionar Cores Selecionadas Add to Graphic Styles Adicionar aos Estilos Gráficos Add to Profiles Adicionar aos Perfis Add to Profiles… Adicionar aos Perfis… @@ -232,6 +233,10 @@ antiAlias Sharp Nítido Arc Arco Arc Lower… Arco Inferior… Arc Tool Ferramenta Arco + Three-Point Arc Tool Ferramenta Arco por três pontos + Three-Point Arc Arco por três pontos + Arc too large Arco grande demais + Third Point Sets Direction O terceiro ponto indica a direção Arc Upper… Arco Superior… Arch… Abóbada… Arc… Arco… @@ -596,6 +601,8 @@ antiAlias Sharp Nítido Contextual Task Bar Barra de Tarefas Contextual Pin Bar Position Fixar Posição da Barra Reset Bar Position Redefinir Posição da Barra + Bar Actions Ações da Barra + Reset Bar Actions Redefinir Ações da Barra Resize Redimensionar Control Controle Convert Converter @@ -1481,6 +1488,10 @@ antiAlias Sharp Nítido Add Color Tool Ferramenta Adicionar cor Remove Color Tool Ferramenta Remover cor Remove Color Remover cor + Set As Base Color Definir como cor base + Select Shade Selecionar tonalidade + Add New Color Adicionar nova cor + Set Current Color As Base Color Definir cor atual como cor base Find the selected colors in the artwork Localizar as cores selecionadas na arte Harmony Sets Conjuntos de Harmonia Height Altura @@ -2369,6 +2380,11 @@ antiAlias Sharp Nítido Preserve Alpha Transparency Preservar Transparência Alfa Preserve Appearance and Overprints Preservar Aparência e Sobreimpressões Preserve CMYK Numbers Preservar Números CMYK + Preserve RGB Numbers Preservar Números RGB + Device to Simulate: Dispositivo a Simular: + Simulate Paper Color Simular Cor do Papel + Simulate Black Ink Simular Tinta Preta + Load… Carregar… Preserve Editing Capabilities Preservar Capacidades de Edição Preserve Lightness Preservar Luminosidade Preserve Overprints and Spot Colors Preservar Sobreimpressões e Cores Spot @@ -2827,9 +2843,11 @@ digits Malayalam Malaiala Edit type set in fonts that aren't available? Editar o texto em fontes que não estão disponíveis? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Mostra na tela o número de cada fatia em uma caixa no canto superior esquerdo dela; quando desativado, os contornos das fatias continuam visíveis. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. A cor dos contornos das fatias de usuário e de objeto e das caixas com seus números; as fatias automáticas usam um tom mais apagado dessa cor. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. O texto novo recebe este idioma enquanto o idioma da Configuração do Documento for Inglês: EUA; o texto que já está em um documento mantém o próprio idioma. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. O texto novo recebe este idioma enquanto o idioma da Configuração do Documento for Inglês: EUA e o [Estilo de Caractere Normal] não definir nenhum; o texto que já está em um documento mantém o próprio idioma. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. Em parágrafos com Hifenizar ativado, uma palavra da lista é dividida apenas nos hifens digitados nela, ou em nenhum ponto se não tiver nenhum, qualquer que seja o idioma ou o uso de maiúsculas. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. Na versão para desktop, os plug-ins .wasm desta pasta são carregados ao iniciar e quando você clica em OK com uma nova pasta aqui, exceto no Modo de Segurança; a versão web não os carrega. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normal mantém os limites próprios de cada plug-in; com Grande, um filtro ou comando de plug-in pode executar pelo menos 250 milhões de instruções além das de sua entrada. O limite de tempo continua o mesmo. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Quantas instruções cada execução de um filtro de objetos de um plug-in pode usar; Grande permite mais que Normal com o mesmo limite de 60 segundos. Filtros pesados mantêm seu próprio orçamento. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. A primeira opção de disco de cópia: Startup, None ou o caminho de uma pasta; o VectorCraft a armazena, mas ainda não usa discos de cópia. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. A segunda opção de disco de cópia: Startup, None ou o caminho de uma pasta; o VectorCraft a armazena, mas ainda não usa discos de cópia. How light or dark the interface is. O quanto a interface é clara ou escura. @@ -2847,7 +2865,10 @@ digits Malayalam Malaiala The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. O idioma da interface; Automático usa o idioma do sistema. A caixa de diálogo troca de idioma assim que você escolhe um. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. O Zoom Animado só funciona enquanto isto está ativado; desativado, o Zoom Animado fica esmaecido e o zoom não é animado. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. O zoom com a roda desliza suavemente, e a Ferramenta Zoom amplia enquanto você arrasta para o lado ou a mantém pressionada; desativado, a Ferramenta Zoom amplia a área que você arrasta. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. A partir da próxima inicialização, a versão para desktop mostra a área de desenho por meio deste tipo de processador gráfico; a arte é sempre desenhada na CPU. Automático prefere o integrado no Windows e no macOS. A versão web não o usa. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. A partir da próxima inicialização, a janela mostra cada quadro sem esperar a atualização da tela quando o driver gráfico permite, no máximo 240 quadros por segundo. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. A partir da próxima inicialização, a versão para desktop desenha com este tipo de processador gráfico; Automático prefere o que controla a tela. A versão web não o usa. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. A partir da próxima inicialização, a janela mostra os quadros sem esperar a tela atualizar, no máximo 240 por segundo; desativado, a tela dita o ritmo. Um modo de apresentação definido na inicialização tem prioridade. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. O número máximo de etapas de desfazer que cada documento guarda; um número menor remove as etapas mais antigas quando você clica em OK. Etapas também podem sair antes quando usam memória demais. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Mostra a arte mudando enquanto você arrasta; desativado, contornos seguem o arraste e a arte muda quando você solta. Uma guia de régua sempre se move enquanto você arrasta. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Quantas threads de trabalho desenham a arte; -1 usa uma a menos que os núcleos que o VectorCraft pode usar, no máximo 8, e 0 nenhuma. A versão web nunca usa nenhuma. @@ -2874,7 +2895,10 @@ digits Malayalam Malaiala VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. O VectorCraft salva esta escolha, mas Copiar e Recortar ainda não usam um formato de área de transferência vetorial legada. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Preservar Caminhos ou Preservar Aparência e Sobreimpressões para a área de transferência vetorial legada; o VectorCraft salva a escolha, mas ainda não a usa. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. Manter Formatação mantém os estilos do texto copiado de um objeto de texto do VectorCraft ao colá-lo em um objeto de texto; Manter Texto Simples dá a ele o estilo do local onde é colado. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. O texto novo recebe este idioma enquanto o idioma da Configuração do Documento for Inglês: EUA e o [Estilo de Caractere Normal] não definir nenhum; o texto que já está em um documento mantém o próprio idioma. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. Exibir Todos os Pretos como Preto Rico mostra o preto CMYK puro (apenas tinta preta a 100%) como preto RGB na tela; Exibir Todos os Pretos com Precisão o converte pelo espaço CMYK de trabalho. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Gerar Todos os Pretos como Preto Rico desenha o preto CMYK puro como preto RGB nas exportações raster RGB e em escala de cinza e com Imprimir como Bitmap; não altera exportações vetoriais, JPEG, TIFF e PSD CMYK nem outras impressões. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Em uma tela sensível ao toque, muda para o espaço de trabalho de toque; desativar a opção ou perder a tela sensível ao toque volta ao espaço de trabalho anterior. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Um toque com dois dedos na tela de desenho desfaz ou, no espaço de trabalho de toque, alterna entre ferramentas de seleção e de desenho, e um toque com três dedos refaz; nenhum funciona no Modo de Apresentação. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. Em parágrafos com Hifenizar ativado, uma palavra da lista é dividida apenas nos hifens digitados nela, ou em nenhum ponto se não tiver nenhum, qualquer que seja o uso de maiúsculas; palavras coreanas não recebem hífen, e palavras em línguas indianas não são divididas dentro de um grupo de caracteres. Reset all preferences to their defaults? Redefinir todas as preferências para o padrão? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Os padrões são aplicados quando você clica em OK em Preferências. Cancelar ali mantém suas preferências atuais. @@ -4631,6 +4655,10 @@ axis Both Ambos @msg a guide has no curvature circle uma guia não tem círculo de curvatura @msg the circle that matches the path there would reach past the canvas o círculo que corresponde ao caminho nesse ponto ultrapassaria a tela @msg no circle passes through these points: two are the same or all three lie on one line nenhum círculo passa por esses pontos: dois são iguais ou os três estão na mesma reta +@msg `at` must be "start" or "end" `at` deve ser "start" ou "end" +@msg give exactly one of `through` and `toward` informe exatamente um entre `through` e `toward` +@msg no arc fits these points: two are the same or all three lie on one line nenhum arco se ajusta a esses pontos: dois são iguais ou os três estão na mesma reta +@msg give `at` only with `toward` informe `at` somente com `toward` @msg no app to open files here nenhum aplicativo para abrir arquivos aqui @msg no artboard nenhuma prancheta @msg no artboard {i} (0-based; the document has {_1}) nenhuma prancheta {i} (base 0; o documento tem {_1}) @@ -4676,6 +4704,7 @@ axis Both Ambos @msg no native format sem formato nativo @msg no pages sem páginas @msg no pattern `{name}` nenhum padrão `{name}` +@msg art painted with `{name}` can't be its tile uma arte pintada com `{name}` não pode ser o ladrilho dele @msg no perspective grid preset named `{name}` nenhuma predefinição de grade de perspectiva chamada `{name}` @msg no plug-in {0} is installed o plug-in {0} não está instalado @msg no plug-in {id} is installed o plug-in {id} não está instalado @@ -5693,6 +5722,11 @@ variable-list-end {0}, {1} {0} e {1} @plural agrees with {n} default shortcut|agrees with {n} default shortcuts coincide com {n} atalho padrão|coincide com {n} atalhos padrão @plural {n} part of the file wasn't read|{n} parts of the file weren't read {n} parte do arquivo não foi lida|{n} partes do arquivo não foram lidas Lab Lab + OKLCH Sliders Controles Deslizantes OKLCH + HSL Sliders Controles Deslizantes HSL + Chroma Croma + The largest chroma sRGB holds at this lightness and hue O maior croma que o sRGB comporta nesta luminosidade e neste tom + OKLCH needs sRGB as the working RGB space OKLCH requer sRGB como espaço de trabalho RGB Lab Values Valores Lab Large List View Exibição em Lista Grande Large Thumbnail View Exibição em Miniaturas Grandes @@ -6436,6 +6470,7 @@ effect Regular Regular Arrow Seta Arrow (open) Seta (aberta) Barbed Farpada +arrowhead Feather Pena Half Arrow (left) Meia Seta (esquerda) Half Arrow (right) Meia Seta (direita) Concave Côncava @@ -6463,6 +6498,7 @@ effect Regular Regular Kite Pipa Triangle to Bar Triângulo para Barra Oval Oval + Line Arrow Seta de Linha Complementary Complementar Complementary 2 Complementar 2 Split Complementary Complementar Dividida @@ -6902,6 +6938,8 @@ mark-style Japanese Japonesas @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` deve ser grayscale, rgb, hsb, cmyk ou websafe @msg `view` must be wheel or box `view` deve ser wheel ou box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` deve ser hue, saturation, brightness, red, green ou blue +@msg `sliders` must be none, oklch or hsl `sliders` deve ser none, oklch ou hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH requer sRGB como espaço de trabalho RGB @msg the image can't be read as a texture a imagem não pode ser lida como textura # User Interface › Accent Color @@ -8315,6 +8353,7 @@ breakText Glyphs Glifos Remove Strokes Remover Traçados Place Brush Art Colocar Arte do Pincel Replace Brush Art Substituir Arte do Pincel + Replace Pattern Art Substituir Arte do Padrão Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Traçados usam este pincel. Aplicar a nova arte a esses traçados, ou deixá-los como estão e adicionar uma cópia do pincel com a nova arte? Apply to Strokes Aplicar aos Traçados Leave Strokes Manter Traçados @@ -10790,6 +10829,21 @@ swatch Yellow Green Verde-amarelado @msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco. @msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, dobradiças: {hinges}, erros: {errors}, avisos: {warnings} + Orbit Lines Linhas orbitais + Petal Garland Guirlanda de pétalas + Lattice Braid Trança em grade + Facet Sweep Traço facetado + Artistic Brushes Pincéis artísticos + Paint Pintura + Flat Sweep Pincelada plana + Dry Drag Arrasto seco + Loaded Stroke Traço carregado + Fan Sweep Pincelada em leque + Engraving Gravura + Fine Hatching Hachuras finas + Dense Hatching Hachuras densas + Tapered Hatching Hachuras afiladas + Broken Hatching Hachuras interrompidas Image Brush Pincéis de imagem Soft Bloom Flor suave Halftone Field Campo de meios-tons diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 07abebad04..51bbe502ba 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -138,6 +138,7 @@ Add to Selection Добавить к выделению Add to Swatches Добавить в образцы Add Used Colors Добавить использованные цвета + Add Selected Colors Добавить выбранные цвета Additional Plug-ins Folder Папка дополнительных модулей Plug-in Instruction Budget Бюджет инструкций модулей Additional Fonts Folder Папка дополнительных шрифтов @@ -235,6 +236,10 @@ font-technology Variable Вариативные Arc Дуга Arc Lower… Дуга снизу… Arc Tool Инструмент «Дуга» + Three-Point Arc Tool Инструмент «Дуга по трём точкам» + Three-Point Arc Дуга по трём точкам + Arc too large Дуга слишком велика + Third Point Sets Direction Третья точка задаёт направление Arc Upper… Дуга сверху… Arch… Арка… Arc… Дуга… @@ -649,6 +654,8 @@ font-technology Variable Вариативные Contextual Task Bar Контекстная панель задач Pin Bar Position Закрепить положение панели Reset Bar Position Сбросить положение панели + Bar Actions Действия панели + Reset Bar Actions Сбросить действия панели Resize Изменить размер Contrast Контраст Control Control @@ -1717,6 +1724,10 @@ file-filter Templates Шаблоны Add Color Tool Инструмент «Добавить цвет» Remove Color Tool Инструмент «Удалить цвет» Remove Color Удалить цвет + Set As Base Color Сделать базовым цветом + Select Shade Выбрать оттенок + Add New Color Добавить новый цвет + Set Current Color As Base Color Сделать текущий цвет базовым Find the selected colors in the artwork Найти выбранные цвета в рисунке Harmony Sets Наборы гармонии Height Высота @@ -2055,6 +2066,11 @@ file-filter Templates Шаблоны Knife Нож Knockout Group Группа с вырезанием Lab Lab + OKLCH Sliders Ползунки OKLCH + HSL Sliders Ползунки HSL + Chroma Хрома + The largest chroma sRGB holds at this lightness and hue Наибольшая хрома, которую вмещает sRGB при этой светлоте и оттенке + OKLCH needs sRGB as the working RGB space Для OKLCH рабочим пространством RGB должно быть sRGB Lab Spot Colors: Плашечные цвета Lab: Lab Values Значения Lab Landscape Альбомная @@ -2130,6 +2146,7 @@ file-filter Templates Шаблоны Limit to Library: Ограничить библиотекой: Limit: Предел: Line Линия + Line Arrow Линейная стрелка Line Art and Text Resolution: Разрешение штрихового рисунка и текста: Line Breaks Разрывы строк Line Color Цвет линии @@ -2893,6 +2910,11 @@ diagnostics ui интерфейс Preserve Alpha Transparency Сохранять альфа-прозрачность Preserve Appearance and Overprints Сохранять оформление и наложения Preserve CMYK Numbers Сохранять значения CMYK + Preserve RGB Numbers Сохранять значения RGB + Device to Simulate: Имитируемое устройство: + Simulate Paper Color Имитировать цвет бумаги + Simulate Black Ink Имитировать чёрную краску + Load… Загрузить… Preserve Editing Capabilities Сохранять возможности редактирования Preserve editing capabilities Сохранять возможности редактирования Preserve Lightness Сохранять светлоту @@ -3393,9 +3415,10 @@ digits Malayalam Малаялам Edit type set in fonts that aren't available? Редактировать текст, набранный недоступными шрифтами? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Показывает на холсте номер каждого фрагмента в рамке в его левом верхнем углу; если параметр выключен, контуры фрагментов по-прежнему видны. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Цвет контуров пользовательских и объектных фрагментов и рамок с их номерами; автоматические фрагменты используют более бледный оттенок этого цвета. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Новый текст получает этот язык, пока в «Параметрах документа» выбран язык Английский: США; текст, который уже есть в документе, сохраняет свой язык. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. В абзацах с включённым параметром «Расставлять переносы» слово из списка переносится только по введённым в нём дефисам или нигде, если их нет, независимо от языка и регистра. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. В настольной версии модули .wasm из этой папки загружаются при запуске и при нажатии ОК с новой папкой здесь, кроме безопасного режима; веб-версия их не загружает. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. «Обычный» сохраняет собственные ограничения каждого модуля; с «Большой» фильтр или команда модуля может выполнить не менее 250 миллионов инструкций сверх тех, что нужны для её входных данных. Ограничение по времени не меняется. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Сколько инструкций может использовать каждый запуск фильтра объектов из модуля; «Большой» разрешает больше, чем «Обычный», при том же ограничении в 60 секунд. Тяжёлые фильтры сохраняют свой бюджет. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Первый выбор рабочего диска: Startup, None или путь к папке; VectorCraft сохраняет его, но пока не использует рабочие диски. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Второй выбор рабочего диска: Startup, None или путь к папке; VectorCraft сохраняет его, но пока не использует рабочие диски. How light or dark the interface is. Насколько светлый или тёмный интерфейс. @@ -3413,7 +3436,10 @@ digits Malayalam Малаялам The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Язык интерфейса; «Авто» использует язык системы. Диалог переключает язык, как только вы выбираете один из них. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Анимированное масштабирование работает, только пока это включено; если выключено, Анимированное масштабирование затенено и масштабирование не анимируется. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Масштабирование колесом идёт плавно, а Инструмент «Масштаб» масштабирует, пока вы тянете вбок или удерживаете его; если выключено, он масштабирует до области, по которой вы протянули. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Со следующего запуска настольная версия выводит холст через этот тип графического процессора; сама графика всегда рисуется на ЦП. «Автоматически» в Windows и macOS предпочитает встроенный. Веб-версия его не использует. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Со следующего запуска окно показывает каждый кадр, не дожидаясь обновления дисплея, если графический драйвер это позволяет, не более 240 кадров в секунду. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Со следующего запуска настольная версия рисует этим типом графического процессора; «Автоматически» предпочитает тот, что управляет дисплеем. Веб-версия его не использует. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Со следующего запуска окно показывает кадры, не дожидаясь обновления дисплея, не более 240 в секунду; если выключено, темп задаёт дисплей. Режим вывода, заданный при запуске, имеет приоритет. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Наибольшее число шагов отмены, которое хранит каждый документ; меньшее число удаляет самые старые шаги при нажатии ОК. Шаги могут уйти и раньше, если занимают слишком много памяти. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Показывает, как меняется графика, пока вы тянете; если выключено, за перетаскиванием следуют контуры, а графика меняется, когда вы отпускаете. Направляющая с линейки всегда движется при перетаскивании. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Сколько рабочих потоков рисуют графику; -1 использует на один меньше, чем ядер, доступных VectorCraft, не более 8, а 0 ни одного. Веб-версия не использует их никогда. @@ -3440,6 +3466,10 @@ digits Malayalam Малаялам VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft сохраняет этот выбор, но Копировать и Вырезать пока не используют формат устаревшего векторного буфера обмена. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Сохранять контуры или Сохранять оформление и наложения для устаревшего векторного буфера обмена; VectorCraft сохраняет выбор, но пока не использует его. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. Сохранять форматирование сохраняет стили текста, скопированного из текстового объекта VectorCraft, при вставке в текстовый объект; Сохранять простой текст даёт ему стиль места вставки. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. Отображать все чёрные как составной чёрный показывает чистый чёрный CMYK (только чёрная краска на 100 %) на холсте как чёрный RGB; Отображать все чёрные точно преобразует его через рабочее пространство CMYK. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Выводить все чёрные как составной чёрный рисует чистый чёрный CMYK как чёрный RGB в растровых экспортах RGB и в оттенках серого и при «Печатать как растровое изображение»; векторные экспорты, JPEG, TIFF и PSD в CMYK и другую печать он не меняет. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. На сенсорном экране переключает на сенсорную рабочую среду; при выключении или пропаже сенсорного экрана возвращает рабочую среду, которая была до переключения. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Касание двумя пальцами по холсту отменяет действие, а в сенсорной рабочей среде переключает между инструментами выделения и рисования; касание тремя пальцами повторяет. В режиме презентации ни одно не работает. New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Новый текст получает этот язык, пока в «Параметрах документа» выбран язык Английский: США, а [Обычный стиль символа] не задаёт язык; текст, который уже есть в документе, сохраняет свой язык. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. В абзацах с включённым параметром «Расставлять переносы» слово из списка переносится только по введённым в нём дефисам или нигде, если их нет, независимо от регистра; корейские слова не получают дефис, а слова на индийских языках не переносятся внутри группы символов. Reset all preferences to their defaults? Сбросить все настройки до значений по умолчанию? @@ -5185,6 +5215,8 @@ liquify-list-end {0}, {1} {0} и {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` должно быть grayscale, rgb, hsb, cmyk или websafe @msg `view` must be wheel or box `view` должно быть wheel или box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` должно быть hue, saturation, brightness, red, green или blue +@msg `sliders` must be none, oklch or hsl `sliders` должен быть none, oklch или hsl +@msg OKLCH needs sRGB as the working RGB space Для OKLCH рабочим пространством RGB должно быть sRGB @msg `{k}` must be [x, y] `{k}` должно быть [x, y] @msg `{name}` has no options `{name}` не имеет параметров @msg `{name}` is a built-in workspace; choose another name `{name}` — встроенная рабочая среда; выберите другое имя @@ -5378,6 +5410,10 @@ liquify-list-end {0}, {1} {0} и {1} @msg a guide has no curvature circle у направляющей нет круга кривизны @msg the circle that matches the path there would reach past the canvas окружность, соответствующая контуру в этом месте, вышла бы за пределы холста @msg no circle passes through these points: two are the same or all three lie on one line через эти точки не проходит ни одна окружность: две точки совпадают или все три лежат на одной прямой +@msg `at` must be "start" or "end" `at` должно быть "start" или "end" +@msg give exactly one of `through` and `toward` укажите ровно один из параметров `through` и `toward` +@msg no arc fits these points: two are the same or all three lie on one line ни одна дуга не подходит к этим точкам: две точки совпадают или все три лежат на одной прямой +@msg give `at` only with `toward` указывайте `at` только вместе с `toward` @msg no app to open files here здесь нет приложения для открытия файлов @msg no artboard нет монтажной области @msg no artboard {i} (0-based; the document has {_1}) нет монтажной области {i} (счёт с 0; в документе {_1}) @@ -5423,6 +5459,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg no native format нет собственного формата @msg no pages нет страниц @msg no pattern `{name}` нет узора `{name}` +@msg art painted with `{name}` can't be its tile графика, окрашенная узором `{name}`, не может быть его плиткой @msg no perspective grid preset named `{name}` нет набора сетки перспективы с именем `{name}` @msg no plug-in {0} is installed модуль {0} не установлен @msg no plug-in {id} is installed модуль {id} не установлен @@ -7593,6 +7630,8 @@ axis Y Axis Ось Y Auto Size Авторазмер Bar Черта Barbed С зазубриной +arrowhead Feather Перо +arrowhead Target Мишень Baseline (Standard) Базовый (стандартный) Baseline Optimized Базовый оптимизированный Bicubic Бикубическая @@ -8286,6 +8325,7 @@ breakText Glyphs Глифы Remove Strokes Убрать обводки Place Brush Art Поместить рисунок кисти Replace Brush Art Заменить рисунок кисти + Replace Pattern Art Заменить рисунок узора Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Обводки используют эту кисть. Применить новый рисунок к этим обводкам или оставить их как есть и добавить копию кисти с новым рисунком? Apply to Strokes Применить к обводкам Leave Strokes Оставить обводки @@ -10773,6 +10813,21 @@ shape Open Открытый @msg Two panels pass through each other. Две панели проходят друг сквозь друга. @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" + Orbit Lines Орбитальные линии + Petal Garland Гирлянда лепестков + Lattice Braid Решётчатое плетение + Facet Sweep Гранёный мазок + Artistic Brushes Художественные кисти + Paint Краска + Flat Sweep Плоский мазок + Dry Drag Сухой протяг + Loaded Stroke Густой мазок + Fan Sweep Веерный мазок + Engraving Гравировка + Fine Hatching Тонкая штриховка + Dense Hatching Плотная штриховка + Tapered Hatching Сужающаяся штриховка + Broken Hatching Прерывистая штриховка Image Brush Кисти изображений Soft Bloom Мягкое цветение Halftone Field Полутоновое поле diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 4f01ce176a..b9bc161542 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -128,6 +128,7 @@ Add to Selection Lägg till i markering Add to Swatches Lägg till i färgrutor Add Used Colors Lägg till använda färger + Add Selected Colors Lägg till markerade färger Additional Plug-ins Folder Mapp för ytterligare plugins Plug-in Instruction Budget Instruktionsbudget för plugins Additional Fonts Folder Mapp för ytterligare typsnitt @@ -226,6 +227,10 @@ font-technology Variable Variabla Arc Båge Arc Lower… Nedre båge… Arc Tool Bågverktyg + Three-Point Arc Tool Verktyg för trepunktsbåge + Three-Point Arc Trepunktsbåge + Arc too large Bågen är för stor + Third Point Sets Direction Tredje punkten anger riktningen Arc Upper… Övre båge… Arch… Valv… Arc… Båge… @@ -634,6 +639,8 @@ font-technology Variable Variabla Contextual Task Bar Kontextuellt aktivitetsfält Pin Bar Position Fäst fältets position Reset Bar Position Återställ fältets position + Bar Actions Fältets åtgärder + Reset Bar Actions Återställ fältets åtgärder Resize Ändra storlek Contrast Kontrast Control Kontroll @@ -1654,6 +1661,10 @@ font-technology Variable Variabla Add Color Tool Verktyget Lägg till färg Remove Color Tool Verktyget Ta bort färg Remove Color Ta bort färg + Set As Base Color Ange som grundfärg + Select Shade Välj nyans + Add New Color Lägg till ny färg + Set Current Color As Base Color Ange aktuell färg som grundfärg Find the selected colors in the artwork Hitta de markerade färgerna i teckningen Harmony Sets Harmoniuppsättningar Height Höjd @@ -1971,6 +1982,11 @@ font-technology Variable Variabla Knife Kniv Knockout Group Utsparningsgrupp Lab Lab + OKLCH Sliders OKLCH-reglage + HSL Sliders HSL-reglage + Chroma Kroma + The largest chroma sRGB holds at this lightness and hue Den största kroma som sRGB rymmer vid denna ljushet och nyans + OKLCH needs sRGB as the working RGB space OKLCH kräver sRGB som RGB-arbetsfärgrymd Lab Spot Colors: Lab-dekorfärger: Lab Values Lab-värden Landscape Liggande @@ -2032,6 +2048,7 @@ font-technology Variable Variabla Limit to Library: Begränsa till bibliotek: Limit: Gränsvärde: Line Linje + Line Arrow Linjepil Line Art and Text Resolution: Upplösning för streckteckning och text: Line Breaks Radbrytningar Line Color Linjefärg @@ -2786,6 +2803,11 @@ font-technology Variable Variabla Preserve Alpha Transparency Bevara alfatransparens Preserve Appearance and Overprints Bevara utseende och övertryck Preserve CMYK Numbers Bevara CMYK-värden + Preserve RGB Numbers Bevara RGB-värden + Device to Simulate: Enhet att simulera: + Simulate Paper Color Simulera pappersfärg + Simulate Black Ink Simulera svart bläck + Load… Läs in… Preserve Editing Capabilities Bevara redigeringsmöjligheter Preserve editing capabilities Bevara redigeringsmöjligheter Preserve Lightness Bevara ljushet @@ -3282,9 +3304,11 @@ digits Malayalam Malayalam Edit type set in fonts that aren't available? Redigera text i typsnitt som inte är tillgängliga? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Visar varje skivas nummer i en ruta i dess övre vänstra hörn på arbetsytan; när det är avstängt visas skivornas konturer fortfarande. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Färgen på konturerna för användar- och objektskivor och på deras nummerrutor; automatiska skivor använder en blekare nyans av den. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Ny text får det här språket så länge språket i Dokumentinställningar är Engelska: USA; text som redan finns i ett dokument behåller sitt eget språk. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Ny text får det här språket så länge språket i Dokumentinställningar är Engelska: USA och [Normal teckenstil] inte anger något språk; text som redan finns i ett dokument behåller sitt eget språk. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. I stycken med Avstava på avstavas ett listat ord bara vid bindestrecken som skrivits in i det, eller inte alls om det saknar sådana, oavsett språk och skiftläge. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. I skrivbordsversionen läses .wasm-plugins i den här mappen in vid start och när du klickar på OK med en ny mapp här, utom i felsäkert läge; webbversionen läser inte in dem. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normal behåller varje plugins egna gränser; med Stor får ett pluginfilter eller ett pluginkommando köra minst 250 miljoner instruktioner utöver dem för sin indata. Tidsgränsen förblir densamma. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Hur många instruktioner varje körning av ett objektfilter från ett plugin får använda; Stor tillåter fler än Normal med samma gräns på 60 sekunder. Tunga filter behåller sin egen budget. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Det första valet av arbetsdisk: Startup, None eller en mappsökväg; VectorCraft sparar det men använder ännu inte arbetsdiskar. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Det andra valet av arbetsdisk: Startup, None eller en mappsökväg; VectorCraft sparar det men använder ännu inte arbetsdiskar. How light or dark the interface is. Hur ljust eller mörkt gränssnittet är. @@ -3302,7 +3326,10 @@ digits Malayalam Malayalam The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Gränssnittets språk; Auto använder systemets språk. Dialogrutan byter språk så fort du väljer ett. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Animerad zoom fungerar bara medan detta är på; avstängt är Animerad zoom nedtonad och zoomningen animeras inte. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Zoom med hjulet glider in mjukt, och Zoomverktyget zoomar medan du drar åt sidan eller håller det nedtryckt; avstängt zoomar Zoomverktyget till området du drar över. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Från nästa start visar skrivbordsversionen arbetsytan genom den här typen av grafikprocessor; teckningen ritas alltid på processorn (CPU). Automatisk föredrar den integrerade på Windows och macOS. Webbversionen använder den inte. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Från nästa start visar fönstret varje bildruta utan att vänta på skärmens uppdatering där grafikdrivrutinen tillåter det, högst 240 bildrutor per sekund. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Från nästa start ritar skrivbordsversionen med den här typen av grafikprocessor; Automatisk föredrar den som driver skärmen. Webbversionen använder den inte. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Från nästa start visar fönstret bildrutor utan att vänta på att skärmen uppdateras, högst 240 per sekund; avstängt styr skärmen takten. Ett presentationsläge som anges vid start går före. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Det högsta antalet ångra-steg som varje dokument behåller; ett lägre tal tar bort de äldsta stegen när du klickar på OK. Steg kan också försvinna tidigare när de använder för mycket minne. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Visar hur bilden ändras medan du drar; avstängt följer konturer dragningen och bilden ändras när du släpper. En stödlinje från linjalen flyttas alltid medan du drar. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Hur många arbetstrådar som ritar bilden; -1 använder en färre än de kärnor VectorCraft får använda, högst 8, och 0 ingen. Webbversionen använder aldrig någon. @@ -3329,7 +3356,10 @@ digits Malayalam Malayalam VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft sparar det här valet, men Kopiera och Klipp ut använder ännu inget format för äldre vektorurklipp. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Bevara banor eller Bevara utseende och övertryck för äldre vektorurklipp; VectorCraft sparar valet men använder det inte ännu. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. Behåll formatering behåller formaten för text som kopierats från ett textobjekt i VectorCraft när den klistras in i ett textobjekt; Behåll oformaterad text ger den formatet där den hamnar. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Ny text får det här språket så länge språket i Dokumentinställningar är Engelska: USA och [Normal teckenstil] inte anger något språk; text som redan finns i ett dokument behåller sitt eget språk. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. Visa alla svarta som djupsvart visar ren CMYK-svart (bara svart färg på 100 %) som RGB-svart på arbetsytan; Visa alla svarta korrekt konverterar den genom arbets-CMYK-färgrymden. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Återge all svart som djupsvart ritar ren CMYK-svart som RGB-svart i RGB- och gråskale-rasterexporter och med Skriv ut som bitmapp; den ändrar inte vektorexporter, CMYK-JPEG, -TIFF och -PSD eller annan utskrift. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. På en pekskärm växlar detta till arbetslayouten för pekskärm; när inställningen stängs av eller pekskärmen försvinner återgår den till arbetslayouten från före bytet. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Ett tryck med två fingrar på arbetsytan ångrar eller växlar i arbetslayouten för pekskärm mellan markerings- och ritverktyg, och ett tryck med tre fingrar gör om; inget av dem fungerar i presentationsläge. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. I stycken med Avstava på avstavas ett listat ord bara vid bindestrecken som skrivits in i det, eller inte alls om det saknar sådana, oavsett skiftläge; koreanska ord får inget avstavningstecken, och ord på indiska språk avstavas inte inuti en teckengrupp. Reset all preferences to their defaults? Återställa alla inställningar till standard? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Standardvärdena verkställs när du klickar på OK i Inställningar. Avbryt där behåller dina nuvarande inställningar. @@ -5243,6 +5273,10 @@ liquify-list-end {0}, {1} {0} och {1} @msg a guide has no curvature circle en stödlinje har ingen krökningscirkel @msg the circle that matches the path there would reach past the canvas cirkeln som matchar banan där skulle nå utanför arbetsytan @msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går genom de här punkterna: två är samma punkt eller så ligger alla tre på en linje +@msg `at` must be "start" or "end" `at` måste vara "start" eller "end" +@msg give exactly one of `through` and `toward` ange exakt en av `through` och `toward` +@msg no arc fits these points: two are the same or all three lie on one line ingen båge passar de här punkterna: två är samma punkt eller så ligger alla tre på en linje +@msg give `at` only with `toward` ange `at` endast tillsammans med `toward` @msg no app to open files here det finns ingen app för att öppna filer här @msg no artboard ingen rityta @msg no artboard {i} (0-based; the document has {_1}) ingen rityta {i} (räknat från 0; dokumentet har {_1}) @@ -5288,6 +5322,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg no native format inget eget format @msg no pages inga sidor @msg no pattern `{name}` inget mönster `{name}` +@msg art painted with `{name}` can't be its tile grafik målad med `{name}` kan inte vara dess ruta @msg no perspective grid preset named `{name}` ingen förinställning för perspektivrutnät med namnet `{name}` @msg no plug-in {0} is installed inget plugin {0} är installerat @msg no plug-in {id} is installed inget plugin {id} är installerat @@ -6401,6 +6436,7 @@ lighting Light Ljus B5 B5 Bar Lodstreck Barbed Hullingförsedd +arrowhead Feather Fjäder Baseline (Standard) Baseline (standard) Baseline Optimized Baseline optimerad Basic Grundläggande @@ -6942,6 +6978,8 @@ theme Appearance Utseende @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` måste vara grayscale, rgb, hsb, cmyk eller websafe @msg `view` must be wheel or box `view` måste vara wheel eller box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` måste vara hue, saturation, brightness, red, green eller blue +@msg `sliders` must be none, oklch or hsl `sliders` måste vara none, oklch eller hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH kräver sRGB som RGB-arbetsfärgrymd @msg `{key}` must be an array of these names: {_1} `{key}` måste vara en lista med dessa namn: {_1} @msg choose a destination folder välj en målmapp @msg choose a source folder välj en källmapp @@ -8331,6 +8369,7 @@ breakText Glyphs Glyfer Remove Strokes Ta bort konturer Place Brush Art Placera penselgrafik Replace Brush Art Ersätt penselgrafik + Replace Pattern Art Ersätt mönstergrafik Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Konturer använder den här penseln. Använd den nya grafiken på konturerna, eller låt dem vara som de är och lägg till en kopia av penseln med den nya grafiken? Apply to Strokes Använd på konturer Leave Strokes Behåll konturer @@ -10811,6 +10850,21 @@ digits Hindi Hindi @msg A joint does not close by {gap} pt. En fog sluter inte med {gap} pt. @msg Two panels pass through each other. Två paneler går igenom varandra. @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen + Orbit Lines Banlinjer + Petal Garland Kronbladsgirlang + Lattice Braid Gallerfläta + Facet Sweep Fasetterat drag + Artistic Brushes Konstnärliga penslar + Paint Färg + Flat Sweep Platt penseldrag + Dry Drag Torrt drag + Loaded Stroke Fylligt penseldrag + Fan Sweep Solfjädersdrag + Engraving Gravyr + Fine Hatching Fin skraffering + Dense Hatching Tät skraffering + Tapered Hatching Avsmalnande skraffering + Broken Hatching Bruten skraffering Image Brush Bildpenslar Soft Bloom Mjuk blomning Halftone Field Halvtonsfält diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 01ebaca9fc..2c3d0efc4b 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -570,6 +570,27 @@ fn objects_on_path_detach_strings_are_in_complete_catalogs() { } } +/// View › Proof Setup › Customize's labels. +#[test] +fn proof_setup_dialog_labels_are_in_complete_catalogs() { + let labels = [ + "Proof Setup", + "Device to Simulate:", + "Preserve CMYK Numbers", + "Preserve RGB Numbers", + "Rendering intent:", + "Simulate Paper Color", + "Simulate Black Ink", + "Save…", + "Load…", + ]; + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in labels { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } +} + /// The PSD Import Options dialog's labels, and the warnings and errors of opening and placing a /// PSD or PSB file with its layers and slices: each complete catalog translates every one, keeping /// its numbers, and translates a reason given inside one. @@ -770,6 +791,21 @@ fn built_in_library_style_names_are_in_complete_catalogs() { assert!(bad.is_empty(), "{}", bad.join("\n")); } +/// The Stroke panel and the Dimension tool's Arrow Style list the built-in arrowheads by name, so +/// each name has a row in each complete catalog: an `arrowhead` row, or a plain one. Feather needs +/// its `arrowhead` row, since its plain row may name the Feather effect. +#[test] +fn built_in_arrowhead_names_are_in_complete_catalogs() { + use vectorcraft_doc::Arrowhead; + let names = distinct(Arrowhead::ALL.iter().map(|h| h.label().to_string()).collect()); + assert_eq!(names.len(), 41, "{names:?}"); + // Spanish's plain Target row names a destination; its arrowhead row names the shape. + let es = crate::i18n::Lang::from_code("es").expect("es registered"); + assert_eq!(crate::i18n::tr_ctx(es, "arrowhead", "Target"), "Diana"); + let bad = lacking(&names, |c, n| c.contextual("arrowhead", n).is_some() || (n != "Feather" && c.plain(n).is_some())); + assert!(bad.is_empty(), "{}", bad.join("\n")); +} + /// A built-in symbol library's panel lists its symbols in the UI language, so every symbol of /// every built-in library has a row in each complete catalog. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 91804fa069..978d520cee 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -125,6 +125,7 @@ Add to Selection Seçime Ekle Add to Swatches Renk Örneklerine Ekle Add Used Colors Kullanılan Renkleri Ekle + Add Selected Colors Seçilen Renkleri Ekle Additional Plug-ins Folder Ek Eklentiler Klasörü Plug-in Instruction Budget Eklenti Talimat Bütçesi Additional Fonts Folder Ek Yazı Tipleri Klasörü @@ -222,6 +223,10 @@ font-technology Variable Değişken Arc Yay Arc Lower… Ark Alt… Arc Tool Yay Aracı + Three-Point Arc Tool Üç Noktalı Yay Aracı + Three-Point Arc Üç Noktalı Yay + Arc too large Yay çok büyük + Third Point Sets Direction Üçüncü Nokta Yönü Belirler Arc Upper… Ark Üst… Arch… Kemer… Arc… Yay… @@ -631,6 +636,8 @@ font-technology Variable Değişken Contextual Task Bar Bağlamsal Görev Çubuğu Pin Bar Position Pim Çubuğu Konumu Reset Bar Position Çubuk Konumunu Sıfırla + Bar Actions Çubuk Eylemleri + Reset Bar Actions Çubuk Eylemlerini Sıfırla Contrast Kontrast Control Kontrol Convert Dönüştür @@ -1617,6 +1624,10 @@ font-technology Variable Değişken Add Color Tool Renk Ekle aracı Remove Color Tool Renk Kaldır aracı Remove Color Rengi kaldır + Set As Base Color Temel renk olarak ayarla + Select Shade Ton seç + Add New Color Yeni renk ekle + Set Current Color As Base Color Geçerli rengi temel renk olarak ayarla Find the selected colors in the artwork Seçili renkleri resimde bul Harmony Sets Armoni Setleri Height Yükseklik @@ -1850,6 +1861,11 @@ font-technology Variable Değişken Knife Bıçak Knockout Group Nakavt Grubu Lab Laboratuvar + OKLCH Sliders OKLCH Kaydırıcıları + HSL Sliders HSL Kaydırıcıları + Chroma Kroma + The largest chroma sRGB holds at this lightness and hue sRGB'nin bu açıklık ve renk tonunda alabileceği en yüksek kroma + OKLCH needs sRGB as the working RGB space OKLCH, çalışma RGB alanı olarak sRGB gerektirir Lab Spot Colors: Laboratuvar Spot Renkleri: Lab Values Laboratuvar Değerleri Landscape Manzara @@ -1925,6 +1941,7 @@ font-technology Variable Değişken Limit to Library: Kütüphaneyle Sınırlama: Limit: Sınır: Line Hat + Line Arrow Çizgi Ok Line Art and Text Resolution: Çizgi Sanatı ve Metin Çözünürlüğü: Line Breaks Satır Sonları Line Color Çizgi Rengi @@ -2635,6 +2652,11 @@ shape Open Açık Preserve Alpha Transparency Alfa Şeffaflığını Koruyun Preserve Appearance and Overprints Görünümü ve Üst Baskıları Koru Preserve CMYK Numbers CMYK Numaralarını Koru + Preserve RGB Numbers RGB Numaralarını Koru + Device to Simulate: Simüle Edilecek Aygıt: + Simulate Paper Color Kağıt Rengini Simüle Et + Simulate Black Ink Siyah Mürekkebi Simüle Et + Load… Yükle… Preserve Editing Capabilities Düzenleme Yeteneklerini Koruyun Preserve editing capabilities Düzenleme yeteneklerini koruyun Preserve Lightness Hafifliği Koruyun @@ -3127,9 +3149,11 @@ digits Malayalam Malayalam Edit type set in fonts that aren't available? Mevcut olmayan yazı tiplerindeki metin düzenlensin mi? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Tuvalde her dilimin numarasını sol üst köşesindeki bir kutuda gösterir; kapalıyken dilimlerin dış çizgileri görünmeye devam eder. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Kullanıcı ve nesne dilimlerinin dış çizgilerinin ve numara kutularının rengi; otomatik dilimler bu rengin daha soluk bir tonunu kullanır. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Belge Kurulumu'nun dili İngilizce: ABD olduğu sürece yeni metin bu dili alır; bir belgede zaten bulunan metin kendi dilini korur. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Belge Kurulumu'nun dili İngilizce: ABD olduğu ve [Normal Karakter Stili] bir dil belirlemediği sürece yeni metin bu dili alır; bir belgede zaten bulunan metin kendi dilini korur. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. Tireleme açık paragraflarda listedeki bir sözcük yalnızca içine yazılan tirelerden bölünür, tire yoksa hiç bölünmez; dili ve büyük/küçük harf durumu fark etmez. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. Masaüstü sürümünde bu klasördeki .wasm eklentileri başlangıçta ve burada yeni bir klasörle Tamam'a tıkladığınızda yüklenir, Güvenli Mod hariç; web sürümü bunları yüklemez. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normal, her eklentinin kendi sınırlarını korur; Büyük ile bir eklenti filtresi veya komutu, girdisi için olanlara ek olarak en az 250 milyon talimat çalıştırabilir. Süre sınırı aynı kalır. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Bir eklentinin nesne filtresinin her çalıştırmasının kullanabileceği talimat sayısı; Büyük, aynı 60 saniyelik sınırla Normal'den fazlasına izin verir. Ağır filtreler kendi bütçelerini korur. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. İlk geçici disk seçimi: Startup, None veya bir klasör yolu; VectorCraft bunu saklar ancak henüz geçici disk kullanmaz. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. İkinci geçici disk seçimi: Startup, None veya bir klasör yolu; VectorCraft bunu saklar ancak henüz geçici disk kullanmaz. How light or dark the interface is. Arayüzün ne kadar açık veya koyu olduğu. @@ -3147,7 +3171,10 @@ digits Malayalam Malayalam The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Arayüzün dili; Otomatik, sistemin dilini kullanır. İletişim kutusu, bir dil seçer seçmez o dile geçer. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Animasyonlu Yakınlaştırma yalnızca bu açıkken çalışır; kapalıyken Animasyonlu Yakınlaştırma soluk görünür ve yakınlaştırma animasyonlu olmaz. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Tekerlekle yakınlaştırma yumuşakça kayar, Yakınlaştırma Aracı ise yana sürüklerken veya basılı tutarken yakınlaştırır; kapalıyken Yakınlaştırma Aracı sürüklediğiniz alana yakınlaştırır. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Bir sonraki başlatmadan itibaren masaüstü sürümü tuvali bu tür grafik işlemci üzerinden gösterir; çizim her durumda CPU'da yapılır. Otomatik, Windows ve macOS'ta tümleşik işlemciyi tercih eder. Web sürümü bunu kullanmaz. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Bir sonraki başlatmadan itibaren pencere, grafik sürücüsünün izin verdiği yerde ekranın yenilenmesini beklemeden her kareyi gösterir; saniyede en fazla 240 kare. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Bir sonraki başlatmadan itibaren masaüstü sürümü bu tür grafik işlemciyle çizer; Otomatik, ekranı süren işlemciyi tercih eder. Web sürümü bunu kullanmaz. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Bir sonraki başlatmadan itibaren pencere, ekranın yenilenmesini beklemeden kareleri gösterir, saniyede en fazla 240; kapalıyken hızı ekran belirler. Başlatırken ayarlanan bir sunum modu önceliklidir. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Her belgenin sakladığı en fazla geri alma adımı sayısı; daha düşük bir sayı, Tamam'a tıkladığınızda en eski adımları kaldırır. Adımlar çok fazla bellek kullanırsa daha erken de gidebilir. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Sürüklerken çizimin değişmesini gösterir; kapalıyken sürüklemeyi ana hatlar izler ve çizim bıraktığınızda değişir. Cetvel kılavuzu sürüklerken her zaman hareket eder. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Çizimi kaç çalışan iş parçacığının çizdiği; -1, VectorCraft'ın kullanabileceği çekirdeklerden bir eksiğini, en fazla 8'i kullanır, 0 ise hiçbirini. Web sürümü hiçbir zaman kullanmaz. @@ -3174,7 +3201,10 @@ digits Malayalam Malayalam VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft bu seçimi kaydeder, ancak Kopyala ve Kes henüz eski vektör panosu biçimini kullanmaz. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Eski vektör panosu için Yolları Koru veya Görünümü ve Üst Baskıları Koru; VectorCraft seçimi kaydeder ama henüz kullanmaz. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. Biçimlendirmeye Devam Et seçeneği, VectorCraft metin nesnesinden kopyalanan metin bir metin nesnesine yapıştırıldığında stillerini korur; Düz Metni Koru ona yapıştırıldığı yerin stilini verir. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Belge Kurulumu'nun dili İngilizce: ABD olduğu ve [Normal Karakter Stili] bir dil belirlemediği sürece yeni metin bu dili alır; bir belgede zaten bulunan metin kendi dilini korur. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. Tüm Siyahları Zengin Siyah Olarak Görüntüle seçeneği, saf CMYK siyahını (yalnızca %100 siyah mürekkep) tuvalde RGB siyahı olarak gösterir; Tüm Siyahları Doğru Şekilde Görüntüleyin seçeneği onu çalışma CMYK alanı üzerinden dönüştürür. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Tüm Siyahların Çıkışını Zengin Siyah Olarak Çıkarın seçeneği, RGB ve gri tonlamalı raster dışa aktarımlarda ve Bitmap olarak yazdır ile saf CMYK siyahını RGB siyahı olarak çizer; vektör dışa aktarımları, CMYK JPEG, TIFF ve PSD dosyalarını veya diğer yazdırmaları değiştirmez. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Dokunmatik ekranda dokunmatik çalışma alanına geçer; seçenek kapatıldığında veya dokunmatik ekran algılanmadığında önceki çalışma alanına döner. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Tuvale iki parmakla dokunmak geri alır veya dokunmatik çalışma alanında seçim ve çizim araçları arasında geçiş yapar, üç parmakla dokunmak yineler; Sunum Modu'nda ikisi de çalışmaz. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. Tireleme açık paragraflarda listedeki bir sözcük yalnızca içine yazılan tirelerden bölünür, tire yoksa hiç bölünmez; büyük/küçük harf durumu fark etmez, Korece sözcükler tire almaz ve Hint dillerindeki sözcükler bir karakter grubunun içinden bölünmez. Reset all preferences to their defaults? Tüm tercihler varsayılanlarına sıfırlansın mı? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Varsayılanlar, Tercihler'de Tamam'a tıkladığınızda uygulanır. Oradaki İptal, mevcut tercihlerinizi korur. @@ -4890,6 +4920,8 @@ liquify-list-end {0}, {1} {0} ve {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` grayscale, rgb, hsb, cmyk veya websafe olmalıdır @msg `view` must be wheel or box `view` wheel veya box olmalıdır @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` hue, saturation, brightness, red, green veya blue olmalıdır +@msg `sliders` must be none, oklch or hsl `sliders` none, oklch veya hsl olmalıdır +@msg OKLCH needs sRGB as the working RGB space OKLCH, çalışma RGB alanı olarak sRGB gerektirir @msg `{k}` must be [x, y] `{k}` [x, y] olmalıdır @msg `{name}` has no options `{name}`nin seçeneği yok @msg `{name}` is a built-in workspace; choose another name `{name}` yerleşik bir çalışma alanıdır; başka bir isim seç @@ -5068,6 +5100,10 @@ liquify-list-end {0}, {1} {0} ve {1} @msg a guide has no curvature circle bir kılavuzun eğrilik çemberi yoktur @msg the circle that matches the path there would reach past the canvas yolla orada eşleşen çember tuvalin dışına taşardı @msg no circle passes through these points: two are the same or all three lie on one line bu noktalardan geçen bir çember yok: ikisi aynı ya da üçü de aynı doğru üzerinde +@msg `at` must be "start" or "end" `at` "start" veya "end" olmalıdır +@msg give exactly one of `through` and `toward` `through` ve `toward` değerlerinden tam olarak birini verin +@msg no arc fits these points: two are the same or all three lie on one line bu noktalara uyan bir yay yok: ikisi aynı ya da üçü de aynı doğru üzerinde +@msg give `at` only with `toward` `at` değerini yalnızca `toward` ile birlikte verin @msg no app to open files here burada dosyaları açacak uygulama yok @msg no artboard çalışma yüzeyi yok @msg no artboard {i} (0-based; the document has {_1}) çalışma yüzeyi yok {i} (0 tabanlı; belgede {_1} var) @@ -5111,6 +5147,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg no native format yerel format yok @msg no pages sayfa yok @msg no pattern `{name}` `{name}` deseni yok +@msg art painted with `{name}` can't be its tile `{name}` ile boyanmış resim onun döşemesi olamaz @msg no perspective grid preset named `{name}` `{name}` adında perspektif ızgarası ön ayarı yok @msg no plug-in {0} is installed {0} eklentisi kurulu değil @msg no plug-in {id} is installed {id} eklentisi kurulu değil @@ -6250,6 +6287,7 @@ lighting Light Işık B5 B5 Bar Bar Barbed Dikenli +arrowhead Feather Tüy Baseline (Standard) Temel (Standart) Baseline Optimized Temel Optimize Edilmiş Basic Temel @@ -10186,6 +10224,7 @@ breakText Glyphs Glifler Remove Strokes Konturları Kaldır Place Brush Art Fırça Çizimini Yerleştir Replace Brush Art Fırça Çizimini Değiştir + Replace Pattern Art Desen Çizimini Değiştir Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Konturlar bu fırçayı kullanıyor. Yeni çizim bu konturlara uygulansın mı, yoksa konturlar olduğu gibi bırakılıp fırçanın yeni çizimli bir kopyası mı eklensin? Apply to Strokes Konturlara Uygula Leave Strokes Konturları Bırak @@ -10676,6 +10715,21 @@ breakText Glyphs Glifler @msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil. @msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, menteşeler: {hinges}, hatalar: {errors}, uyarılar: {warnings} + Orbit Lines Yörünge Çizgileri + Petal Garland Taç Yaprağı Çelengi + Lattice Braid Kafes Örgü + Facet Sweep Fasetli Darbe + Artistic Brushes Sanatsal Fırçalar + Paint Boya + Flat Sweep Düz fırça izi + Dry Drag Kuru sürükleme + Loaded Stroke Yoğun fırça izi + Fan Sweep Yelpaze izi + Engraving Gravür + Fine Hatching İnce tarama + Dense Hatching Yoğun tarama + Tapered Hatching İncelen tarama + Broken Hatching Kesikli tarama Image Brush Görsel Fırçaları Soft Bloom Yumuşak Çiçek Halftone Field Yarı Ton Alanı diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 70e2bfce66..4424e82292 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -134,6 +134,7 @@ Add to Selection Додати до виділення Add to Swatches Додати до зразків Add Used Colors Додати використані кольори + Add Selected Colors Додати вибрані кольори Additional Plug-ins Folder Папка додаткових модулів Plug-in Instruction Budget Бюджет інструкцій модулів Additional Fonts Folder Папка додаткових шрифтів @@ -233,6 +234,10 @@ font-technology Variable Варіативні Arc Дуга Arc Lower… Дуга знизу… Arc Tool Інструмент «Дуга» + Three-Point Arc Tool Інструмент «Дуга за трьома точками» + Three-Point Arc Дуга за трьома точками + Arc too large Дуга завелика + Third Point Sets Direction Третя точка задає напрямок Arc Upper… Дуга зверху… Arch… Арка… Arc… Дуга… @@ -647,6 +652,8 @@ font-technology Variable Варіативні Contextual Task Bar Контекстна панель завдань Pin Bar Position Закріпити положення панелі Reset Bar Position Скинути положення панелі + Bar Actions Дії панелі + Reset Bar Actions Скинути дії панелі Resize Змінити розмір Contrast Контраст Control Панель керування @@ -1725,6 +1732,10 @@ file-filter Templates Шаблони Add Color Tool Інструмент «Додати колір» Remove Color Tool Інструмент «Вилучити колір» Remove Color Вилучити колір + Set As Base Color Зробити базовим кольором + Select Shade Вибрати відтінок + Add New Color Додати новий колір + Set Current Color As Base Color Зробити поточний колір базовим Find the selected colors in the artwork Знайти вибрані кольори в малюнку Harmony Sets Набори гармонії Height Висота @@ -2063,6 +2074,11 @@ file-filter Templates Шаблони Knife Ніж Knockout Group Група з вирізуванням Lab Lab + OKLCH Sliders Повзунки OKLCH + HSL Sliders Повзунки HSL + Chroma Хрома + The largest chroma sRGB holds at this lightness and hue Найбільша хрома, яку вміщує sRGB за цієї світлоти й відтінку + OKLCH needs sRGB as the working RGB space Для OKLCH робочим простором RGB має бути sRGB Lab Spot Colors: Плашкові кольори Lab: Lab Values Значення Lab Landscape Альбомна @@ -2903,6 +2919,11 @@ diagnostics ui інтерфейс Preserve Alpha Transparency Зберігати альфа-прозорість Preserve Appearance and Overprints Зберігати оформлення та накладення Preserve CMYK Numbers Зберігати значення CMYK + Preserve RGB Numbers Зберігати значення RGB + Device to Simulate: Імітований пристрій: + Simulate Paper Color Імітувати колір паперу + Simulate Black Ink Імітувати чорну фарбу + Load… Завантажити… Preserve Editing Capabilities Зберігати можливості редагування Preserve editing capabilities Зберігати можливості редагування Preserve Lightness Зберігати світлоту @@ -3403,9 +3424,10 @@ digits Malayalam Малаялам Edit type set in fonts that aren't available? Редагувати текст, набраний недоступними шрифтами? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Показує на полотні номер кожного фрагмента в рамці в його лівому верхньому куті; коли параметр вимкнено, контури фрагментів і далі видно. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Колір контурів користувацьких і об’єктних фрагментів та рамок з їхніми номерами; автоматичні фрагменти використовують блідіший відтінок цього кольору. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Новий текст отримує цю мову, доки в «Параметрах документа» вибрано мову Англійська: США; текст, який уже є в документі, зберігає свою мову. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. В абзацах з увімкненим параметром «Розставляти переноси» слово зі списку переноситься лише за введеними в ньому дефісами або ніде, якщо їх немає, незалежно від мови й регістру. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. У настільній версії модулі .wasm з цієї папки завантажуються під час запуску і коли ви натискаєте ОК з новою папкою тут, крім безпечного режиму; веб-версія їх не завантажує. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. «Звичайний» зберігає власні обмеження кожного модуля; з «Великий» фільтр або команда модуля може виконати щонайменше 250 мільйонів інструкцій понад ті, що потрібні для її вхідних даних. Обмеження часу не змінюється. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Скільки інструкцій може використати кожен запуск фільтра об’єктів із модуля; «Великий» дозволяє більше, ніж «Звичайний», з тим самим обмеженням у 60 секунд. Важкі фільтри зберігають власний бюджет. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Перший вибір робочого диска: Startup, None або шлях до папки; VectorCraft зберігає його, але поки не використовує робочі диски. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Другий вибір робочого диска: Startup, None або шлях до папки; VectorCraft зберігає його, але поки не використовує робочі диски. How light or dark the interface is. Наскільки світлим чи темним є інтерфейс. @@ -3423,7 +3445,10 @@ digits Malayalam Малаялам The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Мова інтерфейсу; «Авто» використовує мову системи. Діалог перемикає мову, щойно ви її виберете. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Анімоване масштабування працює, лише поки це увімкнено; якщо вимкнено, Анімоване масштабування затінене і масштабування не анімується. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Масштабування коліщатком іде плавно, а Інструмент «Масштаб» масштабує, поки ви тягнете вбік або утримуєте його; якщо вимкнено, він масштабує до області, яку ви протягнули. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. З наступного запуску настільна версія показує полотно через цей тип графічного процесора; саму графіку завжди малює центральний процесор. «Автоматично» у Windows і macOS надає перевагу вбудованому. Веб-версія його не використовує. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. З наступного запуску вікно показує кожен кадр, не чекаючи оновлення дисплея, якщо графічний драйвер це дозволяє, не більше 240 кадрів на секунду. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. З наступного запуску настільна версія малює цим типом графічного процесора; «Автоматично» надає перевагу тому, що керує дисплеєм. Веб-версія його не використовує. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. З наступного запуску вікно показує кадри, не чекаючи оновлення дисплея, не більше 240 на секунду; якщо вимкнено, темп задає дисплей. Режим виведення, заданий під час запуску, має пріоритет. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Найбільша кількість кроків скасування, яку зберігає кожен документ; менше число видаляє найстаріші кроки, коли ви натискаєте ОК. Кроки можуть зникнути й раніше, якщо займають надто багато пам’яті. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Показує, як змінюється графіка, поки ви тягнете; якщо вимкнено, за перетягуванням стежать контури, а графіка змінюється, коли ви відпускаєте. Напрямна з лінійки завжди рухається під час перетягування. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Скільки робочих потоків малюють графіку; -1 використовує на один менше, ніж ядер, доступних VectorCraft, не більше 8, а 0 жодного. Веб-версія не використовує їх ніколи. @@ -3450,6 +3475,10 @@ digits Malayalam Малаялам VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft зберігає цей вибір, але Копіювати й Вирізати поки не використовують формат застарілого векторного буфера обміну. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Зберігати контури або Зберігати оформлення та накладення для застарілого векторного буфера обміну; VectorCraft зберігає вибір, але поки не використовує його. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. Зберігати форматування зберігає стилі тексту, скопійованого з текстового об’єкта VectorCraft, під час вставлення в текстовий об’єкт; Зберігати простий текст дає йому стиль місця вставлення. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. Відображати всі чорні як складові чорні показує чистий чорний CMYK (лише чорна фарба на 100%) на полотні як чорний RGB; Відображати всі чорні точно перетворює його через робочий простір CMYK. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Виводити всі чорні як складовий чорний малює чистий чорний CMYK як чорний RGB у растрових експортах RGB і у відтінках сірого та з «Друк як растрове зображення»; він не змінює векторні експорти, JPEG, TIFF і PSD у CMYK та інший друк. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. На сенсорному екрані переходить у сенсорне робоче середовище; вимкнення параметра або зникнення сенсорного екрана повертає робоче середовище, яке було до переходу. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Дотик двома пальцями до полотна скасовує дію, а в сенсорному робочому середовищі перемикає між інструментами виділення й малювання; дотик трьома пальцями повторює. У режимі презентації жоден не працює. New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Новий текст отримує цю мову, доки в «Параметрах документа» вибрано мову Англійська: США, а [Звичайний стиль символу] не задає мову; текст, який уже є в документі, зберігає свою мову. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. В абзацах з увімкненим параметром «Розставляти переноси» слово зі списку переноситься лише за введеними в ньому дефісами або ніде, якщо їх немає, незалежно від регістру; корейські слова не отримують дефіса, а слова індійськими мовами не переносяться всередині групи символів. Reset all preferences to their defaults? Скинути всі налаштування до значень за промовчанням? @@ -5174,6 +5203,8 @@ liquify-list-end {0}, {1} {0} і {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` має бути grayscale, rgb, hsb, cmyk або websafe @msg `view` must be wheel or box `view` має бути wheel або box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` має бути hue, saturation, brightness, red, green або blue +@msg `sliders` must be none, oklch or hsl `sliders` має бути none, oklch або hsl +@msg OKLCH needs sRGB as the working RGB space Для OKLCH робочим простором RGB має бути sRGB @msg `{k}` must be [x, y] `{k}` має бути [x, y] @msg `{name}` has no options `{name}` не має параметрів @msg `{name}` is a built-in workspace; choose another name `{name}` - вбудоване робоче середовище; виберіть інше ім’я @@ -5367,6 +5398,10 @@ liquify-list-end {0}, {1} {0} і {1} @msg a guide has no curvature circle напрямна не має кола кривини @msg the circle that matches the path there would reach past the canvas коло, що відповідає контуру в цьому місці, вийшло б за межі полотна @msg no circle passes through these points: two are the same or all three lie on one line через ці точки не проходить жодне коло: дві точки збігаються або всі три лежать на одній прямій +@msg `at` must be "start" or "end" `at` має бути "start" або "end" +@msg give exactly one of `through` and `toward` вкажіть рівно один із параметрів `through` і `toward` +@msg no arc fits these points: two are the same or all three lie on one line жодна дуга не підходить до цих точок: дві точки збігаються або всі три лежать на одній прямій +@msg give `at` only with `toward` вказуйте `at` лише разом із `toward` @msg no app to open files here тут немає програми для відкриття файлів @msg no artboard немає монтажної області @msg no artboard {i} (0-based; the document has {_1}) немає монтажної області {i} (рахунок з 0; у документі {_1}) @@ -5412,6 +5447,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg no native format немає власного формату @msg no pages немає сторінок @msg no pattern `{name}` немає візерунка `{name}` +@msg art painted with `{name}` can't be its tile графіка, зафарбована візерунком `{name}`, не може бути його плиткою @msg no perspective grid preset named `{name}` немає набору сітки перспективи з ім’ям `{name}` @msg no plug-in {0} is installed модуль {0} не встановлений @msg no plug-in {id} is installed модуль {id} не встановлений @@ -7621,6 +7657,37 @@ anchor Points: Точки: @msg `{id}` is not a colour adjustment `{id}` не є корекцією кольору @msg missing `effect` відсутня `effect` @msg `params` must be an object `params` має бути об’єктом +# Stroke arrowheads (Stroke panel, Dimension Tool Options and Properties › Arrow Style). + Triangle (open) Трикутник (контурний) + Circle (open) Коло (контурне) + Square (open) Квадрат (контурний) + Arrow (open) Стрілка (контурна) + Barbed Зазубрена +arrowhead Feather Оперення +arrowhead Target Мішень + Half Arrow (left) Половина стрілки (ліворуч) + Half Arrow (right) Половина стрілки (праворуч) + Double Bar Подвійна смуга + Dot on Bar Крапка на смузі + Chevron Шеврон + Plus Плюс + Hexagon (open) Шестикутник (контурний) + Tag Ярлик + Tag (open) Ярлик (контурний) + Half Circle Півколо + Drop Крапля + Slash Скісна риска + Double Slash Подвійна скісна риска + Diamond (open) Ромб (контурний) + Reverse Triangle Обернений трикутник + Swallowtail Ластівчин хвіст + Bracket Дужка + Fork Вилка + Leaf Листок + Kite Дельтоїд + Triangle to Bar Трикутник до смуги + Oval Овал + Line Arrow Лінійна стрілка # Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. Path Precision Tools Інструменти точного редагування контурів Anchor Eraser Brush Пензель-гумка опорних точок @@ -7911,6 +7978,7 @@ breakText Glyphs Гліфи Remove Strokes Забрати обведення Place Brush Art Розмістити малюнок пензля Replace Brush Art Замінити малюнок пензля + Replace Pattern Art Замінити малюнок візерунка Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Обведення використовують цей пензель. Застосувати новий малюнок до цих обведень чи залишити їх як є і додати копію пензля з новим малюнком? Apply to Strokes Застосувати до обведень Leave Strokes Залишити обведення @@ -10340,6 +10408,21 @@ breakText Glyphs Гліфи @msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки. @msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, шарніри: {hinges}, помилки: {errors}, попередження: {warnings} + Orbit Lines Орбітальні лінії + Petal Garland Гірлянда пелюсток + Lattice Braid Ґратчасте плетіння + Facet Sweep Гранований мазок + Artistic Brushes Художні пензлі + Paint Фарба + Flat Sweep Плоский мазок + Dry Drag Сухий протяг + Loaded Stroke Густий мазок + Fan Sweep Віяловий мазок + Engraving Гравіювання + Fine Hatching Тонке штрихування + Dense Hatching Щільне штрихування + Tapered Hatching Звужене штрихування + Broken Hatching Переривчасте штрихування Image Brush Пензлі зображень Soft Bloom М’яке цвітіння Halftone Field Напівтонове поле diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 5867e9c191..36c4d88aa8 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -155,6 +155,7 @@ Add to Selection Thêm vào vùng chọn Add to Swatches Thêm vào mẫu màu Add Used Colors Thêm các màu đã dùng + Add Selected Colors Thêm các màu đã chọn Additional Fonts Folder Thư mục phông bổ sung Additional Plug-ins Folder Thư mục plug-in bổ sung Plug-in Instruction Budget Ngân sách lệnh của plug-in @@ -258,6 +259,10 @@ font-technology Variable Biến thiên Arc Cung Arc Lower… Cung dưới… Arc Tool Công cụ Cung + Three-Point Arc Tool Công cụ Cung ba điểm + Three-Point Arc Cung ba điểm + Arc too large Cung quá lớn + Third Point Sets Direction Điểm thứ ba chỉ hướng Arc Upper… Cung trên… Arch… Vòm… Arc… Cung… @@ -1968,6 +1973,10 @@ file-filter Templates Mẫu Add Color Tool Công cụ Thêm màu Remove Color Tool Công cụ Xóa màu Remove Color Xóa màu + Set As Base Color Đặt làm màu cơ sở + Select Shade Chọn sắc độ + Add New Color Thêm màu mới + Set Current Color As Base Color Đặt màu hiện tại làm màu cơ sở Find the selected colors in the artwork Tìm các màu đã chọn trong tác phẩm Harmony Sets Bộ hài hòa màu Height Chiều cao @@ -2363,6 +2372,11 @@ digits Hindi Hindi Knife Dao Knockout Group Nhóm Knockout Lab Lab + OKLCH Sliders Thanh trượt OKLCH + HSL Sliders Thanh trượt HSL + Chroma Độ tươi màu + The largest chroma sRGB holds at this lightness and hue Độ tươi màu lớn nhất mà sRGB chứa được ở độ sáng và sắc độ này + OKLCH needs sRGB as the working RGB space OKLCH cần sRGB làm không gian RGB làm việc Lab Spot Colors: Màu đặc Lab: Lab Values Giá trị Lab Landscape Ngang @@ -3230,6 +3244,11 @@ diagnostics ui giao diện Preserve Alpha Transparency Bảo lưu trong suốt kênh Alpha Preserve Appearance and Overprints Bảo lưu diện mạo và in chồng Preserve CMYK Numbers Bảo lưu giá trị CMYK + Preserve RGB Numbers Bảo lưu giá trị RGB + Device to Simulate: Thiết bị cần giả lập: + Simulate Paper Color Giả lập màu giấy + Simulate Black Ink Giả lập mực đen + Load… Tải… Preserve Editing Capabilities Bảo lưu khả năng chỉnh sửa Preserve editing capabilities Bảo lưu khả năng chỉnh sửa Preserve Lightness Bảo lưu độ sáng @@ -3552,6 +3571,8 @@ mark-style Japanese Kiểu Nhật Reset all 3D settings to their defaults. Đặt lại tất cả cài đặt 3D về mặc định. Reset all Revolve settings to their defaults. Đặt lại tất cả cài đặt Revolve về mặc định. Reset Bar Position Đặt lại vị trí thanh + Bar Actions Thao tác của thanh + Reset Bar Actions Đặt lại thao tác của thanh Reset Bounding Box Đặt lại hộp bao Rotate Bounding Box Xoay hộp bao Rotate Bounding Box… Xoay hộp bao… @@ -3727,9 +3748,10 @@ mark-style Japanese Kiểu Nhật Edit type set in fonts that aren't available? Chỉnh sửa văn bản dùng phông chữ không có sẵn? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Hiển thị trên khung vẽ số của mỗi lát cắt trong một ô ở góc trên bên trái của nó; khi tắt, đường viền của các lát cắt vẫn hiện. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Màu của đường viền lát cắt người dùng và lát cắt đối tượng cùng các ô số của chúng; lát cắt tự động dùng một sắc độ nhạt hơn của màu này. - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Văn bản mới nhận ngôn ngữ này khi ngôn ngữ trong Thiết lập tài liệu là Tiếng Anh: Mỹ; văn bản đã có trong tài liệu giữ ngôn ngữ của nó. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. Trong các đoạn bật Gạch nối, một từ trong danh sách chỉ được ngắt tại các dấu gạch nối đã gõ trong từ, hoặc không ngắt ở đâu nếu không có, bất kể ngôn ngữ hay chữ hoa thường. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. Trong phiên bản máy tính, các plug-in .wasm trong thư mục này được tải khi khởi động và khi bạn bấm OK với một thư mục mới ở đây, trừ trong Chế độ an toàn; phiên bản web không tải chúng. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Thường giữ giới hạn riêng của từng plug-in; với Lớn, một bộ lọc hoặc lệnh của plug-in có thể chạy ít nhất 250 triệu lệnh ngoài các lệnh cho dữ liệu đầu vào của nó. Giới hạn thời gian vẫn giữ nguyên. + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Số lệnh mà mỗi lần chạy bộ lọc đối tượng của plug-in được dùng; Lớn cho phép nhiều hơn Thường với cùng giới hạn 60 giây. Bộ lọc nặng giữ ngân sách riêng. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Lựa chọn đĩa tạm thứ nhất: Startup, None hoặc đường dẫn thư mục; VectorCraft lưu lựa chọn này nhưng chưa dùng đĩa tạm. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Lựa chọn đĩa tạm thứ hai: Startup, None hoặc đường dẫn thư mục; VectorCraft lưu lựa chọn này nhưng chưa dùng đĩa tạm. How light or dark the interface is. Mức sáng hoặc tối của giao diện. @@ -3747,7 +3769,10 @@ mark-style Japanese Kiểu Nhật The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Ngôn ngữ của giao diện; Tự động dùng ngôn ngữ của hệ thống. Hộp thoại đổi ngôn ngữ ngay khi bạn chọn một ngôn ngữ. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Thu phóng có hiệu ứng chỉ hoạt động khi mục này bật; khi tắt, Thu phóng có hiệu ứng bị làm mờ và việc thu phóng không có hiệu ứng. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Thu phóng bằng con lăn trượt mượt mà, và Công cụ thu phóng phóng to khi bạn kéo sang ngang hoặc giữ nó; khi tắt, Công cụ thu phóng phóng to vùng bạn kéo qua. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Từ lần khởi động tới, phiên bản máy tính hiển thị khung vẽ qua loại bộ xử lý đồ họa này; tác phẩm luôn được vẽ trên CPU. Tự động ưu tiên bộ xử lý tích hợp trên Windows và macOS. Phiên bản web không dùng nó. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Từ lần khởi động tới, cửa sổ hiển thị từng khung hình mà không chờ màn hình làm mới khi trình điều khiển đồ họa cho phép, tối đa 240 khung hình mỗi giây. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Từ lần khởi động tới, phiên bản máy tính vẽ bằng loại bộ xử lý đồ họa này; Tự động ưu tiên bộ xử lý điều khiển màn hình. Phiên bản web không dùng nó. + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Từ lần khởi động tới, cửa sổ hiển thị khung hình mà không chờ màn hình làm mới, tối đa 240 mỗi giây; khi tắt, màn hình quyết định nhịp. Chế độ trình chiếu đặt khi khởi động sẽ được ưu tiên. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Số bước hoàn tác tối đa mà mỗi tài liệu giữ; số nhỏ hơn sẽ xóa các bước cũ nhất khi bạn bấm OK. Các bước cũng có thể bị xóa sớm hơn khi chúng dùng quá nhiều bộ nhớ. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Hiển thị hình vẽ thay đổi khi bạn kéo; khi tắt, đường viền đi theo thao tác kéo và hình vẽ thay đổi khi bạn thả ra. Đường gióng của thước luôn di chuyển khi bạn kéo. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Số luồng làm việc vẽ hình vẽ; -1 dùng ít hơn một luồng so với số lõi VectorCraft được dùng, tối đa 8, và 0 không dùng luồng nào. Phiên bản web không bao giờ dùng luồng nào. @@ -3774,6 +3799,10 @@ mark-style Japanese Kiểu Nhật VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft lưu lựa chọn này, nhưng Sao chép và Cắt chưa dùng định dạng bảng tạm vector cũ. Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. Bảo lưu đường dẫn hoặc Bảo lưu diện mạo và in chồng cho bảng tạm vector cũ; VectorCraft lưu lựa chọn nhưng chưa dùng nó. Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. Giữ định dạng giữ kiểu của văn bản sao chép từ đối tượng văn bản VectorCraft khi dán vào đối tượng văn bản; Giữ văn bản thuần cho nó kiểu tại nơi được dán. + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. Hiển thị tất cả màu đen là đen phong phú hiển thị màu đen CMYK thuần (chỉ mực đen 100%) thành đen RGB trên khung vẽ; Hiển thị tất cả màu đen chính xác chuyển đổi nó qua không gian CMYK làm việc. + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Xuất tất cả màu đen là đen phong phú vẽ màu đen CMYK thuần thành đen RGB trong các bản xuất raster RGB và thang xám và với In dưới dạng bitmap; tùy chọn này không thay đổi các bản xuất vector, JPEG, TIFF và PSD CMYK hay việc in khác. + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Trên màn hình cảm ứng, chuyển sang không gian làm việc cảm ứng; tắt tùy chọn này hoặc mất màn hình cảm ứng sẽ trở về không gian làm việc trước khi chuyển. + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Chạm hai ngón trên khung vẽ sẽ hoàn tác, hoặc trong không gian làm việc cảm ứng sẽ chuyển giữa công cụ chọn và công cụ vẽ, còn chạm ba ngón sẽ làm lại; cả hai không hoạt động trong chế độ trình bày. New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Văn bản mới nhận ngôn ngữ này khi ngôn ngữ trong Thiết lập tài liệu là Tiếng Anh: Mỹ và [Kiểu ký tự thường] không đặt ngôn ngữ; văn bản đã có trong tài liệu giữ ngôn ngữ của nó. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. Trong các đoạn bật Gạch nối, một từ trong danh sách chỉ được ngắt tại các dấu gạch nối đã gõ trong từ, hoặc không ngắt ở đâu nếu không có, bất kể chữ hoa thường; từ tiếng Hàn không được thêm gạch nối, và từ trong các ngôn ngữ Ấn Độ không bị ngắt bên trong một cụm ký tự. Reset all preferences to their defaults? Đặt lại tất cả tùy chọn về mặc định? @@ -5172,6 +5201,8 @@ theme Appearance Giao diện @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` phải là grayscale, rgb, hsb, cmyk hoặc websafe @msg `view` must be wheel or box `view` phải là wheel hoặc box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` phải là hue, saturation, brightness, red, green hoặc blue +@msg `sliders` must be none, oklch or hsl `sliders` phải là none, oklch hoặc hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH cần sRGB làm không gian RGB làm việc @msg `{k}` must be [x, y] `{k}` phải là [x, y] @msg `{name}` has no options `{name}` không có tùy chọn @msg `{name}` is a built-in workspace; choose another name `{name}` là không gian làm việc tích hợp sẵn; hãy chọn tên khác @@ -5737,6 +5768,10 @@ liquify-list-end {0}, {1} {0} và {1} @msg a guide has no curvature circle đường căn không có đường tròn độ cong @msg the circle that matches the path there would reach past the canvas đường tròn khớp với đường dẫn tại đó sẽ vượt quá giới hạn vùng vẽ @msg no circle passes through these points: two are the same or all three lie on one line không có đường tròn nào đi qua các điểm này: hai điểm trùng nhau hoặc cả ba điểm thẳng hàng +@msg `at` must be "start" or "end" `at` phải là "start" hoặc "end" +@msg give exactly one of `through` and `toward` hãy cho đúng một trong hai `through` và `toward` +@msg no arc fits these points: two are the same or all three lie on one line không có cung nào khớp với các điểm này: hai điểm trùng nhau hoặc cả ba điểm thẳng hàng +@msg give `at` only with `toward` chỉ cho `at` cùng với `toward` @msg no app to open files here không có ứng dụng để mở tệp ở đây @msg no artboard không có bảng vẽ @msg no artboard {i} (0-based; the document has {_1}) không có bảng vẽ {i} (bắt đầu từ 0; tài liệu có {_1}) @@ -5791,6 +5826,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg no native format không có định dạng gốc @msg no pages không có trang @msg no pattern `{name}` không có họa tiết `{name}` +@msg art painted with `{name}` can't be its tile đối tượng được tô bằng `{name}` không thể làm ô của nó @msg no perspective grid preset named `{name}` không có thiết lập sẵn lưới phối cảnh tên `{name}` @msg no plug-in {0} is installed plug-in {0} chưa được cài đặt @msg no plug-in {id} is installed plug-in {id} chưa được cài đặt @@ -7668,6 +7704,36 @@ anchor Points: Điểm: @msg `{id}` is not a colour adjustment `{id}` không phải là điều chỉnh màu @msg missing `effect` thiếu `effect` @msg `params` must be an object `params` phải là một đối tượng +# Stroke arrowheads (Stroke panel, Dimension Tool Options and Properties › Arrow Style). + Triangle (open) Tam giác (rỗng) + Circle (open) Hình tròn (rỗng) + Square (open) Hình vuông (rỗng) + Arrow (open) Mũi tên (rỗng) + Barbed Có ngạnh +arrowhead Feather Lông vũ + Half Arrow (left) Nửa mũi tên (trái) + Half Arrow (right) Nửa mũi tên (phải) + Double Bar Thanh đôi + Dot on Bar Chấm trên thanh + Chevron Hình chữ V + Plus Dấu cộng + Hexagon (open) Lục giác (rỗng) + Tag Nhãn + Tag (open) Nhãn (rỗng) + Half Circle Nửa hình tròn + Drop Giọt nước + Slash Gạch chéo + Double Slash Gạch chéo đôi + Diamond (open) Hình thoi (rỗng) + Reverse Triangle Tam giác ngược + Swallowtail Đuôi én + Bracket Ngoặc + Fork Chạc + Leaf Chiếc lá + Kite Hình diều + Triangle to Bar Tam giác đến thanh + Oval Hình bầu dục + Line Arrow Mũi tên nét # Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. Path Precision Tools Công cụ chính xác cho đường dẫn Anchor Eraser Brush Cọ tẩy điểm neo @@ -7958,6 +8024,7 @@ breakText Glyphs Glyph Remove Strokes Gỡ nét Place Brush Art Đặt đối tượng của cọ Replace Brush Art Thay đối tượng của cọ + Replace Pattern Art Thay đối tượng của họa tiết Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? Có nét đang dùng cọ này. Áp dụng đối tượng mới cho các nét đó, hay giữ nguyên chúng và thêm một bản sao của cọ với đối tượng mới? Apply to Strokes Áp dụng cho nét Leave Strokes Giữ nguyên nét @@ -8538,6 +8605,21 @@ breakText Glyphs Glyph @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} điểm ảnh quá lớn cho Targa (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} điểm ảnh quá lớn cho PSD (tối đa {MAX_SIDE} điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer phải là "singleLine", "everyLine", "standardSingleLine" hoặc "standardEveryLine" + Orbit Lines Đường quỹ đạo + Petal Garland Vòng hoa cánh + Lattice Braid Bện lưới + Facet Sweep Nét đa diện + Artistic Brushes Cọ nghệ thuật + Paint Sơn + Flat Sweep Nét quét phẳng + Dry Drag Nét kéo khô + Loaded Stroke Nét cọ đậm + Fan Sweep Nét quét hình quạt + Engraving Khắc nét + Fine Hatching Nét gạch mảnh + Dense Hatching Nét gạch dày + Tapered Hatching Nét gạch thuôn + Broken Hatching Nét gạch đứt Image Brush Cọ hình ảnh Soft Bloom Hoa nở mềm Halftone Field Vùng bán sắc diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5d7e039455..7c3b8967c0 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -89,6 +89,7 @@ Add to Selection 添加到选区 Add to Swatches 添加到色板 Add Used Colors 添加已用颜色 + Add Selected Colors 添加所选颜色 Additional Plug-ins Folder 附加增效工具文件夹 Plug-in Instruction Budget 增效工具指令预算 Additional Fonts Folder 附加字体文件夹 @@ -183,6 +184,10 @@ antiAlias Sharp 锐利 Arc 弧形 Arc Lower… 下弧形… Arc Tool 弧形工具 + Three-Point Arc Tool 三点弧形工具 + Three-Point Arc 三点弧形 + Arc too large 弧形过大 + Third Point Sets Direction 第三点指示方向 Arc Upper… 上弧形… Arch… 拱形… Arc… 弧形… @@ -598,6 +603,8 @@ antiAlias Sharp 锐利 Contextual Task Bar 上下文任务栏 Pin Bar Position 固定任务栏位置 Reset Bar Position 重置任务栏位置 + Bar Actions 任务栏操作 + Reset Bar Actions 重置任务栏操作 Resize 调整大小 Contrast 对比 Control 控制栏 @@ -1659,6 +1666,10 @@ file-filter Templates 模板 Add Color Tool 添加颜色工具 Remove Color Tool 删除颜色工具 Remove Color 删除颜色 + Set As Base Color 设为基色 + Select Shade 选择色调 + Add New Color 添加新颜色 + Set Current Color As Base Color 将当前颜色设为基色 Find the selected colors in the artwork 在图稿中查找所选颜色 Harmony Sets 色彩调和组 Height 高度 @@ -1945,6 +1956,11 @@ file-filter Templates 模板 Knife 刻刀 Knockout Group 挖空组 Lab Lab + OKLCH Sliders OKLCH 滑块 + HSL Sliders HSL 滑块 + Chroma 色度 + The largest chroma sRGB holds at this lightness and hue sRGB 在此亮度和色相下可容纳的最大色度 + OKLCH needs sRGB as the working RGB space OKLCH 需要将 sRGB 用作 RGB 工作空间 Lab Spot Colors: Lab 专色: Lab Values Lab 值 Landscape 横向 @@ -2754,6 +2770,11 @@ diagnostics ui 界面 Preserve Alpha Transparency 保留 Alpha 透明度 Preserve Appearance and Overprints 保留外观和叠印 Preserve CMYK Numbers 保留 CMYK 数值 + Preserve RGB Numbers 保留 RGB 数值 + Device to Simulate: 要模拟的设备: + Simulate Paper Color 模拟纸张颜色 + Simulate Black Ink 模拟黑色油墨 + Load… 载入… Preserve Editing Capabilities 保留编辑功能 Preserve editing capabilities 保留编辑能力 Preserve Lightness 保留亮度 @@ -3253,9 +3274,10 @@ digits Malayalam 马拉雅拉姆数字 Edit type set in fonts that aren't available? 要编辑使用了不可用字体的文字吗? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. 在画布上于每个切片左上角的方框中显示其编号;关闭时,切片轮廓仍会显示。 The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. 用户切片和对象切片的轮廓及其编号方框的颜色;自动切片使用此颜色较淡的色调。 - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. 当文档设置的语言为英语:美国时,新文字使用此语言;文档中已有的文字保留自己的语言。 In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. 在启用自动断字的段落中,列表中的单词只在其中键入的连字符处断开,没有连字符则不断开,与语言和大小写无关。 On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. 在桌面版中,此文件夹中的 .wasm 增效工具会在启动时以及在此处指定新文件夹并单击“确定”时载入,安全模式除外;Web 版不会载入它们。 + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. “正常”保留每个增效工具自身的限制;选择“大”时,增效工具的滤镜或命令除处理其输入所需的指令外,至少可运行 2.5 亿条指令。时间限制不变。 + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. 增效工具的对象滤镜每次运行可使用的指令数;“大”比“正常”允许更多,60 秒的时间限制不变。重型滤镜保留自己的预算。 The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. 第一个暂存盘选择:Startup、None 或文件夹路径;VectorCraft 会存储它,但尚未使用暂存盘。 The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. 第二个暂存盘选择:Startup、None 或文件夹路径;VectorCraft 会存储它,但尚未使用暂存盘。 How light or dark the interface is. 界面的明暗程度。 @@ -3273,7 +3295,10 @@ digits Malayalam 马拉雅拉姆数字 The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. 界面的语言;“自动”使用系统的语言。选择一种语言后,对话框会立即切换到该语言。 Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. 只有开启此项时,动画缩放才会起作用;关闭此项后,动画缩放显示为灰色,缩放不带动画。 The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. 用滚轮缩放时会平滑过渡,缩放工具在你向侧面拖动或按住不放时进行缩放;关闭此项后,缩放工具缩放到你拖过的区域。 + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. 从下次启动起,桌面版通过这类图形处理器显示画布;图稿始终在 CPU 上绘制。“自动”在 Windows 和 macOS 上优先使用集成图形处理器。Web 版不使用此项。 + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. 从下次启动起,在图形驱动程序允许时,窗口显示每一帧而不等待显示器刷新,最多每秒 240 帧。 From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. 从下次启动起,桌面版使用这类图形处理器绘制;“自动”优先使用驱动显示器的图形处理器。Web 版不使用此项。 + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. 从下次启动起,窗口不等待显示器刷新就显示帧,每秒最多 240 帧;关闭时由显示器决定帧的节奏。启动时设置的呈现模式优先。 The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. 每个文档保留的最大撤销步骤数;调低后,单击“确定”时会删除最早的步骤。步骤占用过多内存时也可能更早被删除。 Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. 拖动时显示图稿的变化;关闭此项后,由轮廓跟随拖动,松开后图稿才改变。标尺参考线在拖动时总是跟着移动。 How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. 绘制图稿的工作线程数;-1 使用比 VectorCraft 可用核心数少一个的线程,最多 8 个,0 则不使用。Web 版始终不使用。 @@ -3300,6 +3325,10 @@ digits Malayalam 马拉雅拉姆数字 VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft 会存储此选项,但复制和剪切尚不使用旧版矢量剪贴板格式。 Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. 旧版矢量剪贴板的“保留路径”或“保留外观和叠印”;VectorCraft 会存储所选项,但尚未使用。 Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. 将从 VectorCraft 文字对象复制的文本粘贴到文字对象时,“保留格式”保留其样式,“保留纯文本”则使用粘贴位置的样式。 + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. “将所有黑色显示为复合黑”在画布上将纯 CMYK 黑色(仅 100% 黑色油墨)显示为 RGB 黑色;“准确显示所有黑色”则通过工作 CMYK 空间转换它。 + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. “将所有黑色输出为复合黑”在 RGB 和灰度栅格导出和“以位图打印”中将纯 CMYK 黑色绘制为 RGB 黑色;不改变矢量导出、CMYK JPEG、TIFF 和 PSD 以及其他打印。 + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. 在触摸屏上切换到触控工作区;关闭此选项或触摸屏不再可用时,返回切换前的工作区。 + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. 在画布上双指轻点会撤销,在触控工作区中则在选择工具和绘图工具之间切换;三指轻点会重做。两者在演示模式下均不起作用。 New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. 当文档设置的语言为英语:美国且 [正常字符样式] 未设置语言时,新文字使用此语言;文档中已有的文字保留自己的语言。 In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. 在启用自动断字的段落中,列表中的单词只在其中键入的连字符处断开,没有连字符则不断开,与大小写无关;韩语单词不加连字符,印度语言的单词不会在字符簇内部断开。 Reset all preferences to their defaults? 将所有首选项重置为默认值? @@ -4834,6 +4863,10 @@ imageTrace Outline 轮廓 @msg a guide has no curvature circle 参考线没有曲率圆 @msg the circle that matches the path there would reach past the canvas 在该处与路径曲率相符的圆会超出画布 @msg no circle passes through these points: two are the same or all three lie on one line 没有圆经过这些点:有两点相同,或三点共线 +@msg `at` must be "start" or "end" `at` 必须是 "start" 或 "end" +@msg give exactly one of `through` and `toward` `through` 和 `toward` 必须且只能指定一个 +@msg no arc fits these points: two are the same or all three lie on one line 没有弧形符合这些点:有两点相同,或三点共线 +@msg give `at` only with `toward` `at` 只能与 `toward` 一起指定 @msg select at least two objects 请至少选择两个对象 @msg exit isolation mode first 请先退出隔离模式 @msg no saved presets 没有已保存的预设 @@ -4880,6 +4913,7 @@ imageTrace Outline 轮廓 @msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} 生成了空结果:直线或其他开放路径不围成区域;要包含它,请先对其应用“对象 › 路径 › 轮廓化描边” @msg already editing a pattern 已在编辑图案 @msg no pattern `{name}` 没有图案 `{name}` +@msg art painted with `{name}` can't be its tile 使用 `{name}` 上色的图稿不能作为它的拼贴 @msg not in pattern editing mode 不在图案编辑模式中 @msg finish editing the pattern first 请先完成图案编辑 @msg pattern missing 缺少图案 @@ -5284,6 +5318,8 @@ imageTrace Outline 轮廓 @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` 必须是 grayscale、rgb、hsb、cmyk 或 websafe @msg `view` must be wheel or box `view` 必须是 wheel 或 box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` 必须是 hue、saturation、brightness、red、green 或 blue +@msg `sliders` must be none, oklch or hsl `sliders` 必须是 none、oklch 或 hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH 需要将 sRGB 用作 RGB 工作空间 @msg `{key}` must be true or false `{key}` 必须是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同时为 true @msg `select` must be true or false `select` 必须是 true 或 false @@ -7848,6 +7884,36 @@ anchor Points: 点: @msg `{id}` is not a colour adjustment `{id}` 不是颜色调整 @msg missing `effect` 缺少 `effect` @msg `params` must be an object `params` 必须是对象 +# Stroke arrowheads (Stroke panel, Dimension Tool Options and Properties › Arrow Style). + Triangle (open) 三角 (空心) + Circle (open) 圆形 (空心) + Square (open) 正方形 (空心) + Arrow (open) 箭头 (空心) + Barbed 倒钩 +arrowhead Feather 羽毛 + Half Arrow (left) 半箭头 (左) + Half Arrow (right) 半箭头 (右) + Double Bar 双条形 + Dot on Bar 条形上的圆点 + Chevron 人字形 + Plus 加号 + Hexagon (open) 六边形 (空心) + Tag 标签 + Tag (open) 标签 (空心) + Half Circle 半圆 + Drop 水滴 + Slash 斜线 + Double Slash 双斜线 + Diamond (open) 菱形 (空心) + Reverse Triangle 倒三角 + Swallowtail 燕尾 + Bracket 括号 + Fork 叉形 + Leaf 叶形 + Kite 风筝形 + Triangle to Bar 三角至条形 + Oval 椭圆 + Line Arrow 线条箭头 # Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. Path Precision Tools 路径精确工具 Anchor Eraser Brush 锚点橡皮擦画笔 @@ -8137,6 +8203,7 @@ breakText Glyphs 字形 Remove Strokes 移除描边 Place Brush Art 置入画笔图稿 Replace Brush Art 替换画笔图稿 + Replace Pattern Art 替换图案图稿 Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? 有描边使用了此画笔。要将新图稿应用到这些描边,还是保留描边不变并添加一个使用新图稿的画笔副本? Apply to Strokes 应用于描边 Leave Strokes 保留描边 @@ -10533,6 +10600,21 @@ breakText Glyphs 字形 @msg A joint does not close by {gap} pt. 有一处接缝相差 {gap} pt 未闭合。 @msg Two panels pass through each other. 两个面板相互穿插。 @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素对 PSD 而言过大 (每边最多 {MAX_SIDE} 像素):请降低分辨率 + Orbit Lines 轨道线 + Petal Garland 花瓣花环 + Lattice Braid 格纹编织 + Facet Sweep 切面笔触 + Artistic Brushes 艺术画笔 + Paint 绘画 + Flat Sweep 平刷 + Dry Drag 干拖 + Loaded Stroke 厚涂笔触 + Fan Sweep 扇形笔触 + Engraving 雕刻 + Fine Hatching 细线排线 + Dense Hatching 密集排线 + Tapered Hatching 渐细排线 + Broken Hatching 断续排线 Image Brush 图像画笔 Soft Bloom 柔和花朵 Halftone Field 半色调区域 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 2a6a89c201..14c6b80d8e 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -98,6 +98,7 @@ Add to Selection 加入選取範圍 Add to Swatches 新增至色票 Add Used Colors 新增使用中的顏色 + Add Selected Colors 新增所選顏色 Additional Plug-ins Folder 額外的增效模組資料夾 Plug-in Instruction Budget 增效模組指令預算 Additional Fonts Folder 額外的字體資料夾 @@ -197,6 +198,10 @@ font-technology Variable 可變 Arc 弧形 Arc Lower… 下弧形… Arc Tool 弧形工具 + Three-Point Arc Tool 三點弧形工具 + Three-Point Arc 三點弧形 + Arc too large 弧形過大 + Third Point Sets Direction 第三點指示方向 Arc Upper… 上弧形… Arch… 拱形… Arc… 弧形… @@ -615,6 +620,8 @@ font-technology Variable 可變 Contextual Task Bar 快捷工作列 Pin Bar Position 釘選工作列位置 Reset Bar Position 重設工作列位置 + Bar Actions 工作列動作 + Reset Bar Actions 重設工作列動作 Resize 調整大小 Contrast 對比 Control 控制 @@ -1696,6 +1703,10 @@ file-filter Templates 範本 Add Color Tool 新增顏色工具 Remove Color Tool 移除顏色工具 Remove Color 移除顏色 + Set As Base Color 設為基色 + Select Shade 選取色調 + Add New Color 新增顏色 + Set Current Color As Base Color 將目前顏色設為基色 Find the selected colors in the artwork 在圖稿中尋找所選顏色 Harmony Sets 色彩調和組 Height 高度 @@ -2216,6 +2227,10 @@ file-filter Templates 範本 @msg a guide has no curvature circle 參考線沒有曲率圓 @msg the circle that matches the path there would reach past the canvas 在該處與路徑曲率相符的圓會超出畫布 @msg no circle passes through these points: two are the same or all three lie on one line 沒有圓通過這些點:有兩點相同,或三點共線 +@msg `at` must be "start" or "end" `at` 必須是 "start" 或 "end" +@msg give exactly one of `through` and `toward` `through` 與 `toward` 必須且只能指定一個 +@msg no arc fits these points: two are the same or all three lie on one line 沒有弧形符合這些點:有兩點相同,或三點共線 +@msg give `at` only with `toward` `at` 只能與 `toward` 一起指定 @msg select at least two objects 請選取至少兩個物件 @msg exit isolation mode first 請先結束隔離模式 @msg no saved presets 沒有已儲存的預設集 @@ -2262,6 +2277,7 @@ file-filter Templates 範本 @msg {label} produced an empty result: a line or other open path encloses no area; to include it, apply Object › Path › Outline Stroke to it first {label} 產生了空的結果:直線或其他開放路徑不圍成區域;若要納入,請先對其套用「物件 › 路徑 › 外框筆畫」 @msg already editing a pattern 已在編輯圖樣 @msg no pattern `{name}` 沒有圖樣 `{name}` +@msg art painted with `{name}` can't be its tile 以 `{name}` 上色的圖稿不能作為它的拼貼 @msg not in pattern editing mode 不在圖樣編輯模式中 @msg finish editing the pattern first 請先完成圖樣編輯 @msg pattern missing 找不到圖樣 @@ -2669,6 +2685,8 @@ file-filter Templates 範本 @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` 必須是 grayscale、rgb、hsb、cmyk 或 websafe @msg `view` must be wheel or box `view` 必須是 wheel 或 box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` 必須是 hue、saturation、brightness、red、green 或 blue +@msg `sliders` must be none, oklch or hsl `sliders` 必須是 none、oklch 或 hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH 需要將 sRGB 用作 RGB 工作空間 @msg `{key}` must be true or false `{key}` 必須是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同時為 true @msg `select` must be true or false `select` 必須是 true 或 false @@ -3325,6 +3343,11 @@ liquify-list-end {0}, {1} {0}和{1} Knife 美工刀 Knockout Group 去底群組 Lab Lab + OKLCH Sliders OKLCH 滑桿 + HSL Sliders HSL 滑桿 + Chroma 色度 + The largest chroma sRGB holds at this lightness and hue sRGB 在此亮度和色相下可容納的最大色度 + OKLCH needs sRGB as the working RGB space OKLCH 需要將 sRGB 用作 RGB 工作空間 Lab Spot Colors: Lab 特別色: Lab Values Lab 值 Landscape 橫向 @@ -4186,6 +4209,11 @@ diagnostics ui 介面 Preserve Alpha Transparency 保留 Alpha 透明度 Preserve Appearance and Overprints 保留外觀與疊印 Preserve CMYK Numbers 保留 CMYK 數值 + Preserve RGB Numbers 保留 RGB 數值 + Device to Simulate: 要模擬的裝置: + Simulate Paper Color 模擬紙張顏色 + Simulate Black Ink 模擬黑色油墨 + Load… 載入… Preserve Editing Capabilities 保留編輯功能 Preserve editing capabilities 保留編輯功能 Preserve Lightness 保留亮度 @@ -4689,9 +4717,10 @@ digits Malayalam 馬來亞拉姆數字 Edit type set in fonts that aren't available? 要編輯使用了無法使用之字體的文字嗎? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. 在畫布上於每個切片左上角的方框中顯示其編號;關閉時,切片輪廓仍會顯示。 The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. 使用者切片和物件切片的輪廓及其編號方框的顏色;自動切片使用此顏色較淡的色調。 - New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. 當文件設定的語言為英文:美國時,新文字使用此語言;文件中已有的文字保留自己的語言。 In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. 在開啟使用連字號的段落中,清單中的單字只在其中輸入的連字號處斷開,沒有連字號則不斷開,與語言和大小寫無關。 On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. 在桌面版中,此資料夾中的 .wasm 增效模組會在啟動時以及在此指定新資料夾並按一下「確定」時載入,安全模式除外;網頁版不會載入它們。 + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. 「正常」保留每個增效模組自身的限制;選擇「大」時,增效模組的濾鏡或命令除處理其輸入所需的指令外,至少可執行 2.5 億條指令。時間限制不變。 + How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. 增效模組的物件濾鏡每次執行可使用的指令數;「大」比「正常」允許更多,60 秒的時間限制不變。重型濾鏡保留自己的預算。 The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. 第一個暫存磁碟選擇:Startup、None 或資料夾路徑;VectorCraft 會儲存它,但尚未使用暫存磁碟。 The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. 第二個暫存磁碟選擇:Startup、None 或資料夾路徑;VectorCraft 會儲存它,但尚未使用暫存磁碟。 How light or dark the interface is. 介面的明暗程度。 @@ -4709,7 +4738,10 @@ digits Malayalam 馬來亞拉姆數字 The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. 介面的語言;「自動」使用系統的語言。選擇一種語言後,對話方塊會立即切換為該語言。 Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. 只有開啟此選項時,動畫縮放才會起作用;關閉此選項時,動畫縮放會顯示為灰色,縮放不帶動畫。 The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. 用滾輪縮放時會平滑過渡,縮放工具在你向側邊拖曳或按住不放時進行縮放;關閉此選項時,縮放工具會縮放到你拖曳過的區域。 + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. 從下次啟動起,桌面版透過這類圖形處理器顯示畫布;圖稿一律在 CPU 上繪製。「自動」在 Windows 和 macOS 上優先使用內建圖形處理器。網頁版不使用此選項。 + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. 從下次啟動起,在圖形驅動程式允許時,視窗顯示每一影格而不等待顯示器重新整理,最多每秒 240 影格。 From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. 從下次啟動起,桌面版使用這類圖形處理器繪製;「自動」優先使用驅動顯示器的圖形處理器。網頁版不使用此選項。 + From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. 從下次啟動起,視窗不等待顯示器重新整理就顯示畫面,每秒最多 240 格;關閉時由顯示器決定畫面的節奏。啟動時設定的呈現模式優先。 The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. 每份文件保留的最大復原步驟數;調低後,按一下「確定」時會刪除最早的步驟。步驟佔用過多記憶體時也可能更早被刪除。 Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. 拖曳時顯示圖稿的變化;關閉此選項時,由外框跟隨拖曳,放開後圖稿才改變。尺標參考線在拖曳時總是跟著移動。 How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. 繪製圖稿的工作執行緒數;-1 使用比 VectorCraft 可用核心數少一個的執行緒,最多 8 個,0 則不使用。網頁版始終不使用。 @@ -4736,6 +4768,10 @@ digits Malayalam 馬來亞拉姆數字 VectorCraft stores this choice, but Copy and Cut do not use a legacy vector clipboard format yet. VectorCraft 會儲存此選項,但複製和剪下尚未使用舊版向量剪貼簿格式。 Preserve Paths or Preserve Appearance and Overprints for the legacy vector clipboard; VectorCraft stores the choice but does not use it yet. 舊版向量剪貼簿的「保留路徑」或「保留外觀與疊印」;VectorCraft 會儲存所選項目,但尚未使用。 Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands. 將從 VectorCraft 文字物件複製的文字貼到文字物件時,「保留格式」保留其樣式,「保留純文字」則使用貼上位置的樣式。 + Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space. 「將所有黑色顯示為濃黑」在畫布上將純 CMYK 黑色(僅 100% 黑色油墨)顯示為 RGB 黑色;「精確顯示所有黑色」則透過工作 CMYK 色彩空間轉換。 + Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. 「以濃黑輸出所有黑色」在 RGB 和灰階點陣匯出和「以點陣圖列印」中將純 CMYK 黑色繪製為 RGB 黑色;不改變向量匯出、CMYK JPEG、TIFF 和 PSD 以及其他列印。 + On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. 在觸控螢幕上切換至觸控工作區;關閉此選項或觸控螢幕不再可用時,返回切換前的工作區。 + A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. 在畫布上雙指輕點會復原,在觸控工作區中則在選取工具和繪圖工具之間切換;三指輕點會重做。兩者在簡報模式下均無作用。 New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. 當文件設定的語言為英文:美國且 [正常字元樣式] 未設定語言時,新文字使用此語言;文件中已有的文字保留自己的語言。 In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. 在開啟使用連字號的段落中,清單中的單字只在其中輸入的連字號處斷開,沒有連字號則不斷開,與大小寫無關;韓文單字不加連字號,印度語言的單字不會在字元叢集內部斷開。 Reset all preferences to their defaults? 要將所有偏好設定重設為預設值嗎? @@ -7670,6 +7706,36 @@ anchor Points: 點: @msg `{id}` is not a colour adjustment `{id}` 不是顏色調整 @msg missing `effect` 未提供 `effect` @msg `params` must be an object `params` 必須是物件 +# Stroke arrowheads (Stroke panel, Dimension Tool Options and Properties › Arrow Style). + Triangle (open) 三角 (空心) + Circle (open) 圓形 (空心) + Square (open) 正方形 (空心) + Arrow (open) 箭頭 (空心) + Barbed 倒鉤 +arrowhead Feather 羽毛 + Half Arrow (left) 半箭頭 (左) + Half Arrow (right) 半箭頭 (右) + Double Bar 雙長條 + Dot on Bar 長條上的圓點 + Chevron 人字形 + Plus 加號 + Hexagon (open) 六邊形 (空心) + Tag 標籤 + Tag (open) 標籤 (空心) + Half Circle 半圓 + Drop 水滴 + Slash 斜線 + Double Slash 雙斜線 + Diamond (open) 菱形 (空心) + Reverse Triangle 倒三角 + Swallowtail 燕尾 + Bracket 括號 + Fork 叉形 + Leaf 葉形 + Kite 風箏形 + Triangle to Bar 三角至長條 + Oval 橢圓 + Line Arrow 線條箭頭 # Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): its tools, Anchor Inspector panel, commands and messages. Path Precision Tools 路徑精確工具 Anchor Eraser Brush 錨點橡皮擦筆刷 @@ -7960,6 +8026,7 @@ breakText Glyphs 字符 Remove Strokes 移除筆畫 Place Brush Art 置入筆刷圖稿 Replace Brush Art 取代筆刷圖稿 + Replace Pattern Art 取代圖樣圖稿 Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art? 有筆畫使用了此筆刷。要將新圖稿套用到這些筆畫,還是保留筆畫不變並加入一個使用新圖稿的筆刷複本? Apply to Strokes 套用至筆畫 Leave Strokes 保留筆畫 @@ -10348,6 +10415,21 @@ breakText Glyphs 字符 @msg A joint does not close by {gap} pt. 有一處接縫相差 {gap} pt 未閉合。 @msg Two panels pass through each other. 兩個面板相互穿插。 @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小 + Orbit Lines 軌道線 + Petal Garland 花瓣花環 + Lattice Braid 格紋編織 + Facet Sweep 切面筆觸 + Artistic Brushes 藝術筆刷 + Paint 繪畫 + Flat Sweep 平刷 + Dry Drag 乾拖 + Loaded Stroke 厚塗筆觸 + Fan Sweep 扇形筆觸 + Engraving 雕刻 + Fine Hatching 細線排線 + Dense Hatching 密集排線 + Tapered Hatching 漸細排線 + Broken Hatching 斷續排線 Image Brush 影像筆刷 Soft Bloom 柔和花朵 Halftone Field 半色調區域 diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index 575ab04ea6..c55dd9d9e8 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -45,6 +45,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-anchor-smooth", include_bytes!("../../../assets/icons/dc-anchor-smooth.svg")), ("dc-appearance", include_bytes!("../../../assets/icons/dc-appearance.svg")), ("dc-arc", include_bytes!("../../../assets/icons/dc-arc.svg")), + ("dc-arc-three-point", include_bytes!("../../../assets/icons/dc-arc-three-point.svg")), ("dc-arrow-down", include_bytes!("../../../assets/icons/dc-arrow-down.svg")), ("dc-arrow-extend", include_bytes!("../../../assets/icons/dc-arrow-extend.svg")), ("dc-arrow-tip", include_bytes!("../../../assets/icons/dc-arrow-tip.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 11ea305b2b..464ace2d59 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -39,6 +39,7 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-touch-type" => "dc-touch-type", "tool-line" => "dc-line", "tool-arc" => "dc-arc", + "tool-three-point-arc" => "dc-arc-three-point", "tool-spiral" => "tornado", "tool-rect-grid" => "dc-rect-grid", "tool-polar-grid" => "dc-polar-grid", diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 4e7071a04a..5a3ade8633 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -260,7 +260,8 @@ pub(super) fn flatten(app: &VectorcraftApp, path: Vec, shown: Vec { - if *id == crate::scripts_menu::COMMAND && !crate::scripts_menu::readable(p) { + // A listed script or saved proof setup outside an automation read root is left out. + if matches!(*id, crate::scripts_menu::COMMAND | crate::dialogs::proof_setup::LOAD) && !crate::scripts_menu::readable(p) { continue; } // The other rows keep their ids: `file.openRecent3` still opens the third file. diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 830a8d3008..7186f0707d 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -3,11 +3,21 @@ use super::{Value, VectorcraftApp, json}; /// What a menu click runs: items whose label ends with "…" and that carry default params open a /// generic parameter dialog (fields = the defaults) instead of running immediately. A script of the -/// Scripts folder runs, whatever its name ends with. +/// Scripts folder runs, whatever its name ends with, and so does a proof setup saved in the Proof +/// Setups folder. pub fn click_target(label: &str, id: &str, p: &Value) -> (String, Value) { let dialog = label.ends_with('…') && p.as_object().is_some_and(|o| !o.is_empty()) - && !matches!(id, "effect.dialog" | "window.panel" | "window.brightness" | "view.screenMode" | "plugin.dialog" | crate::scripts_menu::COMMAND); + && !matches!( + id, + "effect.dialog" + | "window.panel" + | "window.brightness" + | "view.screenMode" + | "plugin.dialog" + | crate::scripts_menu::COMMAND + | crate::dialogs::proof_setup::LOAD + ); if dialog { return ("ui.paramDialog".into(), json!({"command": id, "label": label.trim_end_matches('…'), "params": p})); } diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 0f8c92ebb4..61a4bf5872 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -141,7 +141,13 @@ pub(crate) fn shows_a_name(id: &str, label: &str) -> bool { || saved_selection_slot(id).is_some() || matches!( id, - "text.setStyle" | "plugin.dialog" | "file.openWith" | "window.toolbar.custom" | "svgFilter.apply" | crate::scripts_menu::COMMAND + "text.setStyle" + | "plugin.dialog" + | "file.openWith" + | "window.toolbar.custom" + | "svgFilter.apply" + | crate::scripts_menu::COMMAND + | crate::dialogs::proof_setup::LOAD ) || vectorcraft_engine::cmd::plugin::is_command_id(id) || (id == "window.workspace" && !crate::workspaces::is_builtin(label)) @@ -336,11 +342,14 @@ pub(crate) fn holds_plugin_commands(children: &[Item]) -> bool { /// Every English string the menus, the command palette, the panel registry, the toolbar and the /// Preferences dialog can show: what a complete language catalog has to cover. Names that are user /// data (fonts, recent files, saved views, libraries, installed plug-ins, the scripts and subfolders -/// of the Scripts folder), the point sizes and the view angles are left out. +/// of the Scripts folder, saved proof setups), the point sizes and the view angles are left out. pub fn menu_strings() -> std::collections::BTreeSet { use std::collections::BTreeSet; fn user_data(id: &str, params: &Value) -> bool { - hidden_when_disabled(id) || id.starts_with("type.recentFont") || lists_plugin(id, params) || id == crate::scripts_menu::COMMAND + hidden_when_disabled(id) + || id.starts_with("type.recentFont") + || lists_plugin(id, params) + || matches!(id, crate::scripts_menu::COMMAND | crate::dialogs::proof_setup::LOAD) } fn walk(items: &[Item], under: &str, out: &mut BTreeSet) { for it in items { diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 3be667cf8b..5ea673909c 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -652,6 +652,26 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option match (s("action").filter(|a| crate::canvas::is_task_bar_action(a)), opt_bool(p, "visible")) { + (None, _) => { + let ids = crate::canvas::TASK_BAR_ACTIONS.iter().map(|a| a.0).chain(crate::canvas::TASK_BAR_CHIPS); + Err(format!("`action` must be one of {}", ids.collect::>().join(", "))) + } + (_, Err(e)) => Err(e), + (Some(action), Ok(visible)) => { + let hidden = &mut app.ui.task_bar_hidden_actions; + let visible = visible.unwrap_or_else(|| hidden.contains(&action)); + if visible { + hidden.remove(&action); + } else { + hidden.insert(action.clone()); + } + Ok(json!({ "action": action, "visible": visible })) + } + }, + // More Options › Reset Bar Actions: every action and chip shows again. + "window.taskBar.resetActions" => Ok(json!(std::mem::take(&mut app.ui.task_bar_hidden_actions))), "window.dock" => { let ui = &mut app.ui; // The bars the last Tab hid show again, unless the toolbar or the Control bar was shown @@ -865,6 +885,10 @@ fn run_ui_part8(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option { + crate::dialogs::proof_setup::open(app); + Ok(Value::Null) + } "ui.indexedColorDialog" => { crate::dialogs::indexed_color::open(app); Ok(Value::Null) diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index b9503ccd06..a4461c4b9e 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -95,6 +95,10 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { "window.taskBar" => app.ui.task_bar, "window.pathfinder.compoundShapes" => app.ui.shape_modes_compound, "window.taskBar.pin" => app.ui.task_bar_place.pinned, + "window.taskBar.actions" => p + .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.learn" => crate::panels::learn::visible(&app.ui), "window.panel" => { let panel = p.get("panel").and_then(Value::as_str).unwrap_or(""); @@ -110,6 +114,13 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { "view.proofColors" => vectorcraft_render::proof::view().proof_colors, "view.overprintPreview" => vectorcraft_render::proof::view().overprint, "view.proofSetup" => p.get("target").and_then(Value::as_str) == Some(vectorcraft_render::proof::view().setup.target.id().as_str()), + // Customize… is checked while the proof simulates a profile it chose. + "ui.proofSetupDialog" => { + matches!( + vectorcraft_render::proof::view().setup.target, + vectorcraft_color::cms::ProofTarget::Cmyk(_) | vectorcraft_color::cms::ProofTarget::Rgb(_) + ) + } "perspective.grid.snap" => perspective_grid(app).is_some_and(|g| g.snap), "perspective.grid.lockStation" => perspective_grid(app).is_some_and(|g| g.lock_station), "file.documentColorMode" | "object.convertDocumentColorMode" => { @@ -334,7 +345,9 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { "ui.packageDialog" | "docInfo.save" => app.session.active().is_some(), "ui.batchDialog" => !app.ui.action_sets.is_empty() && app.ui.action_sets.iter().any(|s| !s.actions.is_empty()), "ui.epsOptionsDialog" | "ui.hpglOptionsDialog" => app.session.active().is_some(), - "file.saveForWeb" | "file.saveForWeb.browser" | "file.export.svg.browser" => app.session.active().is_some(), + "file.saveForWeb" => app.session.active().is_some(), + // A browser preview opens a file, and the web build has none to open. + "file.saveForWeb.browser" | "file.export.svg.browser" => app.session.active().is_some() && !crate::io::is_web(app), "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()), diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 1b3c11ae7c..5c98b30ad7 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -572,9 +572,8 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { ], ), Sep, - sub( - "Proof Setup", - vec![ + sub("Proof Setup", { + let mut v = vec![ cp("Working CMYK", "view.proofSetup", json!({"target": "workingCmyk", "proof": true})), cp("Legacy Macintosh RGB (Gamma 1.8)", "view.proofSetup", json!({"target": "legacyMacRgb", "proof": true})), cp("Internet Standard RGB (sRGB)", "view.proofSetup", json!({"target": "srgb", "proof": true})), @@ -582,9 +581,16 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { cp("Color blindness – Protanopia-type", "view.proofSetup", json!({"target": "protanopia", "proof": true})), cp("Color blindness – Deuteranopia-type", "view.proofSetup", json!({"target": "deuteranopia", "proof": true})), cp("Color blindness – Tritanopia-type", "view.proofSetup", json!({"target": "tritanopia", "proof": true})), - cp("Customize…", "window.panel", json!({"panel": "separations"})), - ], - ), + c("Customize…", "ui.proofSetupDialog"), + ]; + // The setups saved in the Proof Setups folder. + let saved = crate::dialogs::proof_setup::saved_items(); + if !saved.is_empty() { + v.push(Sep); + v.extend(saved); + } + v + }), c("Proof Colors", "view.proofColors"), Sep, c("Zoom In", "view.zoomIn"), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 7b520b7718..ef7975b9a0 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -688,6 +688,18 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "{pinned?: bool} keep the Contextual Task Bar where it is instead of following the selection (true), let it follow the selection again from where it is (false) or toggle (omitted), as the bar's More Options menu does; returns the new state", ), ("window.taskBar.reset", "Reset Bar Position", "", "{} unpin the Contextual Task Bar and put it back under the selection"), + ( + "window.taskBar.actions", + "Bar Actions", + "", + "{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}", + ), + ( + "window.taskBar.resetActions", + "Reset Bar Actions", + "", + "{} 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.dock", "Panels", @@ -838,7 +850,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "retype.find", "Find Matching Fonts", "", - "{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does, or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more that is not true or false, is an error and leaves the list as it was; returns what retype.list returns", + "{more?: bool} show the Retype panel and list the fonts whose glyphs match the selected outlined text, compared and ranked as type.retypeFonts does (up to 96 loaded fonts, those of the document's live type first): ten, as Find Matching Fonts does (more false, omitted or null: a new search), or with more: true the next five fonts the last search found (whatever is selected now; before any search, a first search), as Find more font matches does; the document does not change; a search with no path or compound path selected, or a more other than true, false or null, is an error and leaves the list as it was; returns what retype.list returns", ), ( "retype.list", @@ -1159,6 +1171,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} open Saturate for the selection (dialog `saturate`, fields `intensity` −100..100, `preview`): previews live, OK runs edit.colors.saturate as one undo step", ), + ( + "ui.proofSetupDialog", + "Customize…", + "", + "{} open View › Proof Setup › Customize (dialog `proofSetup`, fields `device` (\"workingCmyk\", \"cmyk:\" or \"rgb:\": any CMYK or RGB profile), `preserveNumbers`, `intent` (used while preserveNumbers is off), `simulatePaper` and `simulateBlack` (CMYK devices only), `preview` (on): Preview shows the proof on the canvas, OK runs view.proofSetup with these and proof: true, Cancel puts the earlier proof view back; on the desktop only, Save… writes these to a picked proof setup file with view.proofSetup.save and Load… fills them from one with view.proofSetup.read, both starting in the Proof Setups folder (Load… once a save has made it), whose setups View › Proof Setup lists below Customize…)", + ), ( "ui.indexedColorDialog", "Convert to Indexed Color…", @@ -1556,7 +1574,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, 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, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); 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, 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, harmony, harmonyRule, vision}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, 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; 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, harmony, harmonyRule, vision}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/native_menu.rs index abe15ab2a0..b1c2ae4594 100644 --- a/crates/ui-egui/src/native_menu.rs +++ b/crates/ui-egui/src/native_menu.rs @@ -622,7 +622,8 @@ pub(crate) fn state_hash(app: &VectorcraftApp, input: Option) -> u64 { } (app.system_paste, app.last_effect.is_some(), app.ui.recent_files.len(), app.ui.recent_files.first(), app.recent_fonts().len()).hash(&mut h); app.file_dialog_open().hash(&mut h); - (crate::i18n::current().code(), menus::plugin_revision(), crate::scripts_menu::revision()).hash(&mut h); + (crate::i18n::current().code(), menus::plugin_revision(), crate::scripts_menu::revision(), crate::dialogs::proof_setup::saved_revision()) + .hash(&mut h); crate::shortcut_editor::GENERATION.load(std::sync::atomic::Ordering::Relaxed).hash(&mut h); let fonts = vectorcraft_text::FontDb::global(); (fonts.generation(), fonts.installed_fonts_ready()).hash(&mut h); diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 09b43e8155..db045eeed4 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -1033,16 +1033,15 @@ const MAX_SAVED_RECENT_COMMANDS: usize = 20; /// Puts `id` first in the Recent Commands ids `list`, removing its earlier place, and keeps the /// newest [`MAX_RECENT_COMMANDS`] ids that are `known`. An id that is not `known` now (a plug-in -/// that is disabled or not loaded yet), and the palette's own toggle saved before its picks were -/// left out, keep their places among them without taking one of those places, so a plug-in's -/// command shows again when it comes back. The list never holds more than -/// [`MAX_SAVED_RECENT_COMMANDS`] ids. +/// that is disabled or not loaded yet) keeps its place among them, so it shows again when its +/// command comes back. The palette's own toggle, saved before its picks were left out, is dropped +/// so that it does not take a place. The list never holds more than [`MAX_SAVED_RECENT_COMMANDS`] ids. fn remember(list: &mut Vec, id: &str, known: impl Fn(&str) -> bool) { - list.retain(|c| c != id); + list.retain(|c| c != id && c != PALETTE_TOGGLE); list.insert(0, id.to_string()); let mut kept = 0; let end = list.iter().position(|c| { - if c != PALETTE_TOGGLE && known(c) { + if known(c) { kept += 1; } kept > MAX_RECENT_COMMANDS @@ -1400,9 +1399,9 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // The list shows as many rows as fit above the footer in the window, up to // VISIBLE_ROWS; a page is that many rows. let spacing = ui.spacing().item_spacing.y; - // Under the recent picks no footer line is drawn. - let footer_line = if empty { 0.0 } else { spacing + 6.0 + ui.text_style_height(&egui::TextStyle::Body) }; - let footer_height = footer_line + f32::from(margin) + BOTTOM_GAP; + // Under the recent picks the footer line holds only where the highlighted pick's home is, + // when no callout shows it, so the line's room is kept there too. + let footer_height = spacing + 6.0 + ui.text_style_height(&egui::TextStyle::Body) + f32::from(margin) + BOTTOM_GAP; let room = screen.bottom() - footer_height - ui.cursor().top() - spacing; let rows = ((room / ROW_HEIGHT).floor().max(1.0) as usize).min(VISIBLE_ROWS); sel = moves.apply(sel, n, rows); @@ -1512,15 +1511,17 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { Some(Pointer::Footer(text)) => hint = Some(text), None => {} } - // Under the recent picks no footer line is shown; with none, one dimmed line says what a - // search finds. - if !empty { + // 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()) { ui.add_space(6.0); ui.scope(|ui| { // The footer stays one line of text tall, as the list's height counts it. ui.spacing_mut().interact_size.y = 0.0; ui.horizontal(|ui| { - ui.label(egui::RichText::new(footer(n, total)).color(t.text_dim)); + 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()); } @@ -1989,26 +1990,22 @@ mod tests { assert_eq!(list.first().map(String::as_str), Some("paint.swap")); } - /// The palette's own toggle in a list saved before its picks were left out takes none of the - /// eight places, so eight other picks stay listed after it. + /// A palette toggle saved in a full Recent Commands list does not take one of its places: after + /// another pick the list keeps that pick and the seven newest commands before it, and the + /// toggle is dropped. #[test] - fn a_saved_palette_toggle_takes_no_recent_place() { + fn a_saved_palette_toggle_does_not_take_a_recent_place() { let entries = build(Lang::EN); let known = |c: &str| entries.iter().any(|e| e.id == c); - assert!(known(PALETTE_TOGGLE)); - let mut list: Vec = [PALETTE_TOGGLE, "paint.swap", "object.group"].map(str::to_string).into(); - let others: Vec = entries - .iter() - .filter(|e| ![PALETTE_TOGGLE, "paint.swap", "object.group"].contains(&e.id.as_str())) - .take(6) - .map(|e| e.id.clone()) - .collect(); - for id in &others { - remember(&mut list, id, known); - } + assert!(known(PALETTE_TOGGLE), "the toggle has a result"); + let others: Vec = + entries.iter().filter(|e| e.id != PALETTE_TOGGLE && e.id != "paint.swap").take(MAX_RECENT_COMMANDS).map(|e| e.id.clone()).collect(); + let mut list: Vec = std::iter::once(PALETTE_TOGGLE.to_string()).chain(others.iter().cloned()).collect(); + remember(&mut list, "paint.swap", known); + let expected: Vec = std::iter::once("paint.swap".to_string()).chain(others.iter().take(MAX_RECENT_COMMANDS - 1).cloned()).collect(); + assert_eq!(list, expected); let shown: Vec<&str> = recent(&entries, &list).iter().map(|e| e.id.as_str()).collect(); - assert_eq!(shown.len(), MAX_RECENT_COMMANDS, "{shown:?}"); - assert_eq!(shown.last(), Some(&"object.group")); + assert_eq!(shown.len(), MAX_RECENT_COMMANDS); } /// The open palette drawn over `app`, after the frame's keys go to the shortcuts as in the app, @@ -2716,7 +2713,8 @@ mod tests { assert!(open.app.ui.dialog.is_some(), "{}", open.app.ui.status); assert_eq!(open.app.ui.recent_commands, [id, "paint.swap"]); // Cancel closes the dialog without running the command. - open.app.ui.dialog = None; + crate::dialogs::cancel(&mut open.app); + assert!(open.app.ui.dialog.is_none()); open.frame(vec![]); assert_eq!(open.app.ui.recent_commands, [id, "paint.swap"]); } @@ -4809,6 +4807,21 @@ mod tests { assert!(!footer.iter().any(|l| l.contains("not shown now")), "{footer:?}"); } + /// Under the recent picks of an empty search, the footer still says where the highlighted + /// pick's home is when no callout can show it, without a count of the results. + #[test] + fn under_the_recent_picks_the_footer_names_a_home_out_of_view() { + let mut window = Window::new(); + window.app.ui.recent_commands = vec!["tool:pen".into()]; + window.app.ui.screen_mode = 3; + let nodes = window.search(""); + assert_eq!(window.highlighted(), "tool:pen"); + assert_eq!(window.callout(), None); + let footer = window.popup_labels(&nodes); + assert!(footer.contains(&"Toolbar, not shown now".to_string()), "{footer:?}"); + assert!(!footer.iter().any(|l| l.ends_with(" result") || l.ends_with(" results")), "no count: {footer:?}"); + } + /// No callout where no control in view shows the home: in Presentation Mode, with the Tools /// panel hidden, and for a command with no menu item. The footer says where it lives. #[test] diff --git a/crates/ui-egui/src/palette/search.rs b/crates/ui-egui/src/palette/search.rs index 02b8c5392b..5cfe8ef6c2 100644 --- a/crates/ui-egui/src/palette/search.rs +++ b/crates/ui-egui/src/palette/search.rs @@ -630,6 +630,12 @@ impl Index { let (offset, len) = (offset as usize, usize::from(len)); self.initials_text.get(offset..offset + len).is_some_and(|text| text.lines().any(|l| l == query)) } + + /// Does the index hold the `n` results it was built from? A catalog too large to index gets an + /// empty index ([`Index::build`]), which holds none. + fn holds(&self, n: usize) -> bool { + self.initials.len() == n + } } /// `query` trimmed, lowercased, with each run of whitespace made one space. @@ -752,10 +758,8 @@ pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str, recent: &[u32] typos.push(near); } // The index reads only the start of a longer query, so such a query matches by the substring - // rule, which reads all of it. With an empty index (a catalog too large for one, - // [`Index::build`]), a query matches by the substring rule alone, so words that are text in a - // result one by one don't match it. - let fits = query.chars().count() <= INDEX_CHARS && (entries.is_empty() || !index.initials.is_empty()); + // rule, which reads all of it, as every query does in a catalog too large to index. + let fits = query.chars().count() <= INDEX_CHARS && index.holds(n); let packed: String = query.chars().filter(|c| !c.is_whitespace()).collect(); let packed = Some(packed).filter(|p| (2..=6).contains(&p.chars().count()) && p.chars().all(char::is_alphabetic)); let mut ranked: Vec<(RankKey, u32)> = vec![]; @@ -1454,19 +1458,15 @@ mod tests { assert!(ranked(&c, "bg qxq").is_empty()); } - /// With an empty index (a catalog too large for one), a query matches by the substring rule - /// alone: words that are text in a result one by one don't match it. + /// A catalog without an index (one with more results than a posting can name) matches by the + /// substring rule alone: a query word whose parts are each text in a name, where the word + /// itself is not, finds nothing. #[test] - fn without_an_index_a_query_matches_as_one_text() { - let entries = || vec![entry("Zz Xabx Ycdy", "a.one"), entry("Zz Ab.cd", "b.two")]; - let (list, empty) = (entries(), Index::default()); - let found = |q: &str| -> Vec { - rank(&list, &empty, q, &[], &[]).iter().filter_map(|&i| list.get(i as usize)).map(|e| e.id.clone()).collect() - }; - assert_eq!(found("ab.cd"), ["b.two"]); - assert_eq!(found("xabx ycdy"), ["a.one"]); - // With the index, each word may be text in a word of the result. - assert_eq!(ranked(&synthetic(entries()), "ab.cd"), ["b.two", "a.one"]); + fn without_an_index_only_the_substring_rule_matches() { + let entries = vec![entry("Remove Background…", "a.one"), entry("Zz Group", "b.two")]; + let c = Catalog { list: entries, index: Index::default(), ranked: std::sync::Mutex::new(None) }; + assert!(ranked(&c, "mov.nd").is_empty(), "{:?}", ranked(&c, "mov.nd")); + assert_eq!(ranked(&c, "background mov"), ["a.one"]); } /// A query word that is an English stem form of a word of a group ("setting" of settings, diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 24dc900a0f..fb0ab20a30 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -429,11 +429,27 @@ fn restore_hidden_group(app: &mut VectorcraftApp, panel: &str) -> Result, panel: &str) -> Option { + dock_columns(layout) + .into_iter() + .filter(|column| column.iconic) + .flat_map(|column| &column.groups) + .find(|group| group.panels.iter().any(|p| p == panel)) + .and_then(|group| group.active_panel()) + .map(|front| front.to_string()) +} + /// Show `panel` as `window.panel` does, but leave it be when it can be seen already ([`visible`]): -/// a command that opens a panel to work in (Edit › Color Settings…) never puts it away. In -/// Presentation Mode the panel comes to the front of its group and shows when the mode ends. +/// a command that opens a panel to work in (Edit › Color Settings…) never puts it away. A flyout +/// keeps the name of the icon that opened it after another of its tabs is clicked, so a panel whose +/// flyout is open with another tab in front comes to the front of it. In Presentation Mode the +/// panel comes to the front of its group and shows when the mode ends. pub(crate) fn reveal_panel(app: &mut VectorcraftApp, panel: &str) -> Result { if visible(&app.ui, panel) { + if app.ui.docking.is_some() && flyout_tab(&layout_of(&app.ui), panel).is_some_and(|front| front != panel) { + gesture(app, Action::Activate { panel: panel.to_string() })?; + } return Ok(json!({"open": panel})); } let id = normalize(panel).ok_or_else(|| format!("unknown panel `{panel}`"))?; diff --git a/crates/ui-egui/src/panel_docking/tests.rs b/crates/ui-egui/src/panel_docking/tests.rs index 6c861c0db9..2c90c7cd54 100644 --- a/crates/ui-egui/src/panel_docking/tests.rs +++ b/crates/ui-egui/src/panel_docking/tests.rs @@ -397,6 +397,28 @@ fn a_collapsed_dock_uses_the_flyouts_active_tab_for_thumbnail_work() { assert!(!thumbnail_panel_showing(&h.app.ui, &h.ctx), "a Properties tab under the Layers icon does not need thumbnails"); } +/// Revealing a panel whose flyout is open with another tab of its group in front brings that panel +/// to the front and keeps the flyout open. +#[test] +fn reveal_brings_the_panel_to_the_front_of_its_open_flyout() { + let mut h = Harness::new(); + h.app.run("window.collapseDock", json!({"collapsed": true})).unwrap(); + h.app.ui.docking = Some(layout_of(&h.app.ui)); + h.app.run("window.panel", json!({"panel": "properties"})).unwrap(); + h.frame(vec![]); + gesture(&mut h.app, Action::Activate { panel: "layers".into() }).unwrap(); + h.frame(vec![]); + assert_eq!(h.app.ui.open_panel.as_deref(), Some("properties"), "the flyout is still named for its opening icon"); + assert_eq!(flyout_tab(&layout_of(&h.app.ui), "properties").as_deref(), Some("layers"), "Layers is in front"); + reveal_panel(&mut h.app, "properties").unwrap(); + h.frame(vec![]); + assert_eq!(h.app.ui.open_panel.as_deref(), Some("properties"), "the flyout stays open"); + assert_eq!(flyout_tab(&layout_of(&h.app.ui), "properties").as_deref(), Some("properties"), "Properties is in front"); + // Revealed again while in front, the panel stays as it is. + reveal_panel(&mut h.app, "properties").unwrap(); + assert_eq!(h.app.ui.open_panel.as_deref(), Some("properties")); +} + /// A Character field shortcut with the Character panel in front of its floating window brings /// that window forward and leaves the panel showing. #[test] diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 028652c9bb..78f10e0cf6 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -22,15 +22,25 @@ //! Setup uses, and for achromatopsia as the gray with the color's CIE L*. The chips only show the //! simulation. //! -//! The view, the channel, Show Harmony, Harmony Rule and Show Color Vision Preview are kept with -//! the preferences (`ui.colorWheel`). +//! 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 +//! space ([`cms::active`]: the profile assigned to the document, else the working RGB space of the +//! color settings) is sRGB. Panel menu › HSL Sliders shows H, S and L rows in their place that edit the color by the +//! hue, saturation and lightness of CSS Color 4's HSL +//! (). The choice is kept with the +//! preferences too. +//! +//! The view, the channel, the slider rows, Show Harmony, Harmony Rule and Show Color Vision +//! Preview are kept with the preferences (`ui.colorWheel`). -use egui::{Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, vec2}; +use egui::{Color32, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, pos2, vec2}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use vectorcraft_color::cms::{self, Cms, ProofSetup, ProofTarget}; use vectorcraft_color::harmony::Harmony; -use vectorcraft_color::{Color, Paint, hsb_to_rgb, rgb_to_hsb}; +use vectorcraft_color::oklab::{self, CHROMA_FULL}; +use vectorcraft_color::{Color, Paint, hsb_to_rgb, hsl_to_rgb, rgb_to_hsb, rgb_to_hsl}; use vectorcraft_doc::{ColorMode, NodeId}; use super::color::{Target, apply, wheel_target}; @@ -82,6 +92,8 @@ pub struct Settings { pub view: View, #[serde(serialize_with = "serialize_channel", deserialize_with = "deserialize_channel")] pub channel: Channel, + #[serde(deserialize_with = "deserialize_sliders")] + pub sliders: Sliders, /// Show Harmony: markers on the ring for the other colors of `harmony_rule`. #[serde(deserialize_with = "deserialize_flag")] pub harmony: bool, @@ -94,9 +106,50 @@ pub struct Settings { pub vision: bool, } +/// The slider rows under the wheel or the box (panel menu, `ui.colorWheel {sliders}`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum Sliders { + #[default] + None, + /// OKLCH Sliders: lightness, chroma and hue. + Oklch, + /// HSL Sliders: hue, saturation and lightness. + Hsl, +} + +impl Sliders { + pub const ALL: [Sliders; 3] = [Sliders::None, Sliders::Oklch, Sliders::Hsl]; + + /// The id `ui.colorWheel` and the preferences use. + pub fn id(self) -> &'static str { + match self { + Sliders::None => "none", + Sliders::Oklch => "oklch", + Sliders::Hsl => "hsl", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|v| v.id() == s) + } +} + +fn deserialize_sliders<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v = ::deserialize(d)?; + Ok(v.as_str().and_then(Sliders::parse).unwrap_or_default()) +} + impl Default for Settings { fn default() -> Self { - Self { view: View::default(), channel: Channel::default(), harmony: false, harmony_rule: Harmony::Complementary, vision: false } + Self { + view: View::default(), + channel: Channel::default(), + sliders: Sliders::default(), + harmony: false, + harmony_rule: Harmony::Complementary, + vision: false, + } } } @@ -146,12 +199,22 @@ pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result Result { - const KEYS: [&str; 5] = ["view", "channel", "harmony", "harmonyRule", "vision"]; + set(&mut app.ui.color_wheel, p, &cms::active())?; + Ok(json!(app.ui.color_wheel)) +} + +/// Set the keys of `ui.colorWheel` params `p` in `settings`, with the color settings `cms`; on an +/// error `settings` stay as they were. +pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), String> { + const KEYS: [&str; 6] = ["view", "channel", "sliders", "harmony", "harmonyRule", "vision"]; match p { Value::Null => {} Value::Object(o) => { @@ -161,7 +224,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result return Err(format!("the params must be an object, not {got}")), } - let mut set = app.ui.color_wheel.clone(); + let mut set = settings.clone(); match p.get("view") { None | Some(Value::Null) => {} Some(v) => set.view = v.as_str().and_then(View::parse).ok_or("`view` must be wheel or box")?, @@ -170,6 +233,16 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result {} Some(v) => set.channel = v.as_str().and_then(Channel::parse).ok_or("`channel` must be hue, saturation, brightness, red, green or blue")?, } + match p.get("sliders") { + None | Some(Value::Null) => {} + Some(v) => { + let sliders = v.as_str().and_then(Sliders::parse).ok_or("`sliders` must be none, oklch or hsl")?; + if sliders == Sliders::Oklch && !cms.rgb_is_srgb() { + return Err(OKLCH_NEEDS_SRGB.to_string()); + } + set.sliders = sliders; + } + } let key = "harmony"; match p.get(key) { None | Some(Value::Null) => {} @@ -188,12 +261,13 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result /// Panel state: the HSB picked last, its [`Owner`] and the display sRGB of the color it stored. const MEMORY: &str = "color-wheel-hsb"; +/// Panel state: the OKLCH the slider rows asked for last, the [`Owner`] of the color they stored +/// and its display sRGB. +const OKLCH_MEMORY: &str = "color-wheel-oklch"; +/// Panel state: the slider rows whose drag previews on an open interaction, until it is released. +const ROWS_LIVE: &str = "color-wheel-rows-live"; +/// The message for OKLCH Sliders while the active document's RGB space is not sRGB. +const OKLCH_NEEDS_SRGB: &str = "OKLCH needs sRGB as the working RGB space"; +/// Panel state: the HSL the slider rows asked for last, the [`Owner`] of the color they stored and +/// its display sRGB. +const HSL_MEMORY: &str = "color-wheel-hsl"; /// The height of the color vision chips and the space between them. const VISION_CHIP: f32 = 16.0; const VISION_GAP: f32 = 3.0; @@ -399,6 +499,28 @@ impl Owner { } } +/// The components remembered under `key` for the target's `color`: the display sRGB the color had +/// when they were stored, and the components. A record whose owner or display color differs from +/// what the panel shows now is dropped, so that it does not come back when the same color returns +/// later. +fn recall( + app: &VectorcraftApp, + ui: &Ui, + key: &str, + tgt: &Target, + color: Option, + cms: &Cms, +) -> Option<([f32; 3], T)> { + let (owner, shown, v) = pstate::>(ui.ctx(), key)?; + match color { + Some(c) if owner == Owner::of(app, tgt, c) && cms.display_rgb(&c) == shown => Some((shown, v)), + _ => { + set_pstate(ui.ctx(), key, None::<(Owner, [f32; 3], T)>); + None + } + } +} + /// The HSB a color shows on the wheel: that of its display sRGB through `cms`. pub(crate) fn display_hsb(cms: &Cms, c: &Color) -> [f32; 3] { rgb_to_hsb(cms.display_rgb(c)) @@ -416,7 +538,12 @@ pub(crate) fn remembered_hsb(cms: &Cms, c: &Color, shown: [f32; 3], hsb: [f32; 3 /// model with the color settings. Anything else (no color, a Gray color, a tint of a global swatch) /// becomes a process color in the document's color mode: managed CMYK when `cmyk_doc`, else RGB. pub(crate) fn stored(cms: &Cms, hsb: [f32; 3], was: Option<&Color>, cmyk_doc: bool) -> Color { - let [r, g, b] = cms.srgb_to_rgb(hsb_to_rgb(hsb)); + stored_srgb(cms, hsb_to_rgb(hsb), was, cmyk_doc) +} + +/// [`stored`] for a pick of display sRGB `srgb`. +pub(crate) fn stored_srgb(cms: &Cms, srgb: [f32; 3], was: Option<&Color>, cmyk_doc: bool) -> Color { + let [r, g, b] = cms.srgb_to_rgb(srgb); let rgb = Color::rgb(r, g, b); let cmyk = || { let [c, m, y, k] = cms.to_cmyk(&rgb, cms.settings().intent); @@ -450,14 +577,215 @@ fn replaced(app: &VectorcraftApp, tgt: &Target, behind: bool) -> Option { } } +/// The OKLCH `[l, c, h°]` the rows show for `c` through `cms` when `lch` was asked for last and `c` +/// then displayed as the sRGB `shown`: `lch` while `c` still displays as `shown` (a chroma past the +/// gamut and the hue of a gray stay), else `c`'s own. +pub(crate) fn remembered_oklch(cms: &Cms, c: &Color, shown: [f32; 3], lch: [f64; 3]) -> [f64; 3] { + if cms.display_rgb(c) == shown { lch } else { oklab::to_oklch(clipped_rgb(cms, c)) } +} + +/// The display sRGB of `c` through `cms` clipped to sRGB: the color the slider rows show and edit +/// for a color outside sRGB. +fn clipped_rgb(cms: &Cms, c: &Color) -> [f32; 3] { + cms.display_rgb(c).map(|v| v.clamp(0.0, 1.0)) +} + +/// The color a track shows at OKLCH `lch`: the color itself inside sRGB, and outside it dimmed. +/// A color outside sRGB shows at the largest chroma that fits at its L and H, the color a pick +/// there stores. With `max_chroma` (the C track, whose L and H stay fixed) that chroma is given +/// for the colors past it; without it, or in a gap below it where the ray leaves sRGB and comes +/// back, it is found for each color. +pub(crate) fn oklch_track(lch: [f64; 3], max_chroma: Option) -> Color32 { + let exact = oklab::oklch_to_srgb(lch[0], lch[1], lch[2]); + let (rgb, outside) = match max_chroma { + Some(m) if lch[1] > m => (oklab::oklch_to_srgb(lch[0], m, lch[2]), true), + Some(_) if oklab::in_srgb(exact) => (exact, false), + _ => { + let (rgb, lowered) = oklab::from_oklch(lch[0], lch[1], lch[2]); + (rgb.map(f64::from), lowered) + } + }; + let [r, g, b] = rgb.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + let c = Color32::from_rgb(r, g, b); + if outside { c.gamma_multiply(0.3) } else { c } +} + +/// Where the C track's tick sits, from 0 at its left to 1 at its right: at the largest chroma +/// `max_chroma`, of the track's 0 to 0.4. +pub(crate) fn chroma_tick(max_chroma: f64) -> f32 { + (max_chroma / CHROMA_FULL).clamp(0.0, 1.0) as f32 +} + +/// The L, C and H rows of OKLCH Sliders for the target's `color` through `cms`: lightness from 0 to +/// 100 %, chroma from 0 to 100 % of 0.4 (as CSS reads a chroma percentage) and hue from 0 to 360°. +/// Each track shows the colors its slider reaches and dims the part outside sRGB, and a tick on the +/// C track marks the largest chroma sRGB holds at the row's L and H. The rows are gray with no +/// color to edit and while the working RGB space is not sRGB. Returns the OKLCH a drag, an arrow +/// key, a screen reader or a field asks for, and its phase. +pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option, cms: &Cms) -> Option<([f64; 3], Live)> { + let t = Tokens::get(ui.ctx()); + let enabled = color.is_some() && cms.rgb_is_srgb(); + let lch = match (color, recall::<[f64; 3]>(app, ui, OKLCH_MEMORY, tgt, color, cms)) { + (Some(c), Some((shown, lch))) => remembered_oklch(cms, &c, shown, lch), + (Some(c), _) => oklab::to_oklch(clipped_rgb(cms, &c)), + (None, _) => [0.0; 3], + }; + // Each row: its letter, its screen-reader name, the end of its range and the field's suffix. + let rows = [("L", tl!("Lightness"), 100.0, "%"), ("C", tl!("Chroma"), 100.0, "%"), ("H", tl!("Hue"), 360.0, "°")]; + let shown = [lch[0] * 100.0, lch[1] / CHROMA_FULL * 100.0, lch[2]]; + // The OKLCH with row `i` set to `v` in the row's units. + let with = |i: usize, v: f64| { + let mut out = lch; + match i { + 0 => out[0] = (v / 100.0).clamp(0.0, 1.0), + 1 => out[1] = (v / 100.0 * CHROMA_FULL).clamp(0.0, CHROMA_FULL), + _ => out[2] = v.clamp(0.0, 360.0), + } + out + }; + let mut out = None; + // The L and H tracks search the gamut for each color outside sRGB, so their colors are kept + // until the other two components change. + let mut tracks = pstate::<[Option<([u64; 3], Vec)>; 3]>(ui.ctx(), OKLCH_TRACKS); + ui.add_enabled_ui(enabled, |ui| { + let field_w = 48.0; + let slider_w = (ui.available_width() - field_w - 12.0 - 3.0 * ui.spacing().item_spacing.x).max(60.0); + // The C track's L and H stay fixed, so its largest chroma is found once per frame. + let max_c = if enabled { oklab::max_chroma(lch[0], lch[2]) } else { 0.0 }; + for (i, (letter, name, max, suffix)) in rows.into_iter().enumerate() { + ui.horizontal(|ui| { + ui.add_sized(vec2(12.0, 22.0), egui::Label::new(egui::RichText::new(letter).size(12.5).color(t.text))); + let v = shown[i].clamp(0.0, max); + let at = |x: f32| with(i, f64::from(x) * max); + let mut key = lch.map(f64::to_bits); + key[i] = 0; + let colors = match &tracks[i] { + Some((k, colors)) if i != 1 && enabled && *k == key => colors.clone(), + _ if i != 1 && enabled => { + let last = (TRACK_SAMPLES - 1) as f32; + let colors: Vec = (0..TRACK_SAMPLES).map(|s| oklch_track(at(s as f32 / last), None)).collect(); + tracks[i] = Some((key, colors.clone())); + colors + } + _ => Vec::new(), + }; + let track = |x: f32| match colors.get((x.clamp(0.0, 1.0) * (TRACK_SAMPLES - 1) as f32).round() as usize) { + Some(c) => *c, + None if enabled => oklch_track(at(x), (i == 1).then_some(max_c)), + None => t.input, + }; + let value = SliderValue::field(v, 0.0..=max, suffix, 0); + let (dragged, phase, keyed) = + widgets::color_slider_stepped(ui, ("color-wheel-oklch", i), name, Some(value), (v / max) as f32, slider_w, &track); + // The tick goes on the bar of the rail as the row laid it out. + let rail = (i == 1 && enabled).then(|| ui.ctx().read_response(widgets::id_with(ui.scope_id(), ("color-wheel-oklch", i)))).flatten(); + if let Some(rail) = rail { + let bar = widgets::color_rail_bar(rail.rect); + let x = bar.left() + chroma_tick(max_c) * bar.width(); + ui.painter().line_segment([pos2(x, bar.top() - 3.0), pos2(x, bar.bottom())], Stroke::new(1.5, t.text)); + let tip = Rect::from_x_y_ranges(x - 3.0..=x + 3.0, bar.top() - 3.0..=bar.bottom()); + ui.interact(tip, ui.scope_id().with("color-wheel-oklch-tick"), egui::Sense::hover()) + .on_hover_text(tl!("The largest chroma sRGB holds at this lightness and hue")); + } + if let Some(x) = dragged { + out = Some((at(x), phase)); + } + if let Some(k) = keyed { + out = Some((with(i, k), Live::Released)); + } + if let Some(f) = widgets::plain_field_named(ui, ("color-wheel-oklch-field", i), Some(name), v, suffix, 0, field_w) { + out = Some((with(i, f), Live::Released)); + } + }); + } + }); + set_pstate(ui.ctx(), OKLCH_TRACKS, tracks); + out.filter(|_| enabled) +} + +/// Panel state: the colors of the L and H tracks of OKLCH Sliders, each with the OKLCH (its own +/// component left out) they were drawn for. +const OKLCH_TRACKS: &str = "color-wheel-oklch-tracks"; +/// How many colors along a cached track. +const TRACK_SAMPLES: usize = 128; + +/// The HSL `[h°, s, l]` the rows show for `c` through `cms` when `hsl` was asked for last and `c` +/// then displayed as the sRGB `shown`: `hsl` while `c` still displays as `shown` (the hue of a gray +/// and the saturation of black and white stay), else `c`'s own. +pub(crate) fn remembered_hsl(cms: &Cms, c: &Color, shown: [f32; 3], hsl: [f32; 3]) -> [f32; 3] { + if cms.display_rgb(c) == shown { hsl } else { rgb_to_hsl(clipped_rgb(cms, c)) } +} + +/// The color a track shows at HSL `hsl`. +fn hsl32(hsl: [f32; 3]) -> Color32 { + let [r, g, b] = hsl_to_rgb(hsl).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + Color32::from_rgb(r, g, b) +} + +/// The H, S and L rows of HSL Sliders for the target's `color` through `cms`: hue from 0 to 360°, +/// saturation and lightness from 0 to 100 %, CSS Color 4's HSL of the display sRGB. Each track +/// shows the colors its slider reaches. The rows are gray with no color to edit. Returns the HSL a +/// drag, an arrow key, a screen reader or a field asks for, and its phase. +pub(crate) fn hsl_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option, cms: &Cms) -> Option<([f32; 3], Live)> { + let t = Tokens::get(ui.ctx()); + let enabled = color.is_some(); + let hsl = match (color, recall::<[f32; 3]>(app, ui, HSL_MEMORY, tgt, color, cms)) { + (Some(c), Some((shown, hsl))) => remembered_hsl(cms, &c, shown, hsl), + (Some(c), _) => rgb_to_hsl(clipped_rgb(cms, &c)), + (None, _) => [0.0; 3], + }; + // Each row: its letter, its screen-reader name, the end of its range and the field's suffix. The + // names start with "HSL" so that they differ from the box strip's HSB Hue and Saturation. + let hsl_name = |name: &str| format!("HSL {name}"); + let rows = + [("H", hsl_name(tl!("Hue")), 360.0, "°"), ("S", hsl_name(tl!("Saturation")), 100.0, "%"), ("L", hsl_name(tl!("Lightness")), 100.0, "%")]; + let shown = [f64::from(hsl[0]), f64::from(hsl[1]) * 100.0, f64::from(hsl[2]) * 100.0]; + // The HSL with row `i` set to `v` in the row's units. + let with = |i: usize, v: f64| { + let mut out = hsl; + match i { + 0 => out[0] = v.clamp(0.0, 360.0) as f32, + 1 => out[1] = (v / 100.0).clamp(0.0, 1.0) as f32, + _ => out[2] = (v / 100.0).clamp(0.0, 1.0) as f32, + } + out + }; + let mut out = None; + ui.add_enabled_ui(enabled, |ui| { + let field_w = 48.0; + let slider_w = (ui.available_width() - field_w - 12.0 - 3.0 * ui.spacing().item_spacing.x).max(60.0); + for (i, (letter, name, max, suffix)) in rows.into_iter().enumerate() { + ui.horizontal(|ui| { + ui.add_sized(vec2(12.0, 22.0), egui::Label::new(egui::RichText::new(letter).size(12.5).color(t.text))); + let v = shown[i].clamp(0.0, max); + let at = |x: f32| with(i, f64::from(x) * max); + let track = |x: f32| if enabled { hsl32(at(x)) } else { t.input }; + let value = SliderValue::field(v, 0.0..=max, suffix, 0); + let (dragged, phase, keyed) = + widgets::color_slider_stepped(ui, ("color-wheel-hsl", i), &name, Some(value), (v / max) as f32, slider_w, &track); + if let Some(x) = dragged { + out = Some((at(x), phase)); + } + if let Some(k) = keyed { + out = Some((with(i, k), Live::Released)); + } + if let Some(f) = widgets::plain_field_named(ui, ("color-wheel-hsl-field", i), Some(&name), v, suffix, 0, field_w) { + out = Some((with(i, f), Live::Released)); + } + }); + } + }); + out.filter(|_| enabled) +} + pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let tgt = wheel_target(app, ui); let color = tgt.color(); let cms = cms::active(); // With None, a pattern or a "?" proxy the wheel shows the last solid color without markers, // and a click, an arrow key or a screen reader's action applies the picked color. - let hsb = match (color, pstate::>(ui.ctx(), MEMORY)) { - (Some(c), Some((owner, shown, hsb))) if owner == Owner::of(app, &tgt, c) => remembered_hsb(&cms, &c, shown, hsb), + let hsb = match (color, recall::<[f32; 3]>(app, ui, MEMORY, &tgt, color, &cms)) { + (Some(c), Some((shown, hsb))) => remembered_hsb(&cms, &c, shown, hsb), (c, _) => display_hsb(&cms, &c.unwrap_or(app.session.last_solid)), }; let marked = color.is_some(); @@ -512,16 +840,80 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { pick = Some(([hsb[0], x, 1.0 - y], field_phase)); } }); + let (mut picked_lch, mut picked_hsl) = (None, None); + match app.ui.color_wheel.sliders { + Sliders::None => {} + Sliders::Oklch => { + ui.add_space(4.0); + picked_lch = oklch_rows(app, ui, &tgt, color, &cms); + } + Sliders::Hsl => { + ui.add_space(4.0); + picked_hsl = hsl_rows(app, ui, &tgt, color, &cms); + } + } + // A row drag whose rows were hidden or replaced (`ui.colorWheel {sliders}`), or turned gray + // (OKLCH rows after the working RGB space stops being sRGB), reports no release: its preview is + // kept as one undo step and the interaction ends. + let live = pstate::>(ui.ctx(), ROWS_LIVE); + if live.is_some_and(|rows| rows != app.ui.color_wheel.sliders || (rows == Sliders::Oklch && !cms.rgb_is_srgb())) { + if app.session.in_interaction() + && let Err(e) = app.session.commit_interaction() + { + app.status(e.to_string()); + } + app.sync_views(); + set_pstate(ui.ctx(), ROWS_LIVE, None::); + } if app.ui.color_wheel.vision { ui.add_space(4.0); vision_row(ui, &cms, color.as_ref()); } - let Some((hsb, phase)) = pick else { return }; let behind = super::alt_held(ui); 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))), + (_, Some((lch, phase))) => Some((oklab::from_oklch(lch[0], lch[1], lch[2]).0, phase, OKLCH_MEMORY, Remembered::Oklch(lch))), + _ => None, + }; + if let Some((srgb, phase, key, asked)) = rows { + // A hue on a gray, or a saturation on black or white, leaves the displayed color as it is: + // the rows keep what they were given, and the paint (a Gray color too) stays unchanged. + let current = color.filter(|c| { + let d = cms.display_rgb(c); + !behind && live.is_none() && (0..3).all(|i| (d[i] - srgb[i]).abs() <= 1e-5) + }); + if let Some(c) = current { + asked.remember(ui, key, Owner::of(app, &tgt, c), cms.display_rgb(&c)); + return; + } + let c = stored_srgb(&cms, srgb, replaced(app, &tgt, behind).as_ref(), cmyk_doc); + apply(app, &tgt, c, phase, behind); + set_pstate(ui.ctx(), ROWS_LIVE, (phase == Live::Dragging).then_some(app.ui.color_wheel.sliders)); + if !behind { + asked.remember(ui, key, Owner::of(app, &tgt, c), cms.display_rgb(&c)); + } + return; + } + let Some((hsb, phase)) = pick else { return }; let c = stored(&cms, hsb, replaced(app, &tgt, behind).as_ref(), cmyk_doc); apply(app, &tgt, c, phase, behind); if !behind { set_pstate(ui.ctx(), MEMORY, Some((Owner::of(app, &tgt, c), cms.display_rgb(&c), hsb))); } } + +/// What a slider row asked for, kept under its memory key. +enum Remembered { + Hsl([f32; 3]), + Oklch([f64; 3]), +} + +impl Remembered { + fn remember(self, ui: &Ui, key: &str, owner: Owner, shown: [f32; 3]) { + match self { + Remembered::Hsl(v) => set_pstate(ui.ctx(), key, Some((owner, shown, v))), + Remembered::Oklch(v) => set_pstate(ui.ctx(), key, Some((owner, shown, v))), + } + } +} diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index 7baaa062ab..e04c2780c1 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -347,7 +347,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { edit(app, json!({"reverse": true}), Live::Released); } }); - let radial = kind.is_centered() && placed; + // The default gradient (with nothing selected, or the Live Paint Bucket's) fits each object and has no aspect. + let radial = kind.is_centered() && placed && app.session.gradient_edit_has_objects(!app.session.fill_active); ui.horizontal(|ui| { icons::icon(ui, "scaling", 15.0, if radial { t.icon } else { t.text_disabled }).on_hover_text(tl!("Aspect Ratio")); // A mirrored conic's negative aspect shows as its size; an edit keeps the mirror. diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index bbf833b1aa..f91d4fbcf5 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -433,6 +433,37 @@ fn the_aspect_field_keeps_a_mirrored_conic_mirrored() { assert!((geom.aspect + 0.8).abs() < 1e-9 && geom.is_mirrored(), "{geom:?}"); } +/// With nothing selected, and while the Live Paint Bucket is active, the Aspect Ratio field is +/// dimmed: the default gradient fits each object and has no aspect, so typing in it changes +/// nothing and reports no error. +#[test] +fn the_aspect_field_is_dimmed_for_the_default_gradient() { + for bucket in [false, true] { + let mut app = app(json!({"gradient": {"kind": "radial"}})); + if bucket { + app.select_tool("livePaintBucket"); + } else { + app.run("select.set", json!({"ids": []})).unwrap(); + } + let default = app.session.paint.fill.clone(); + let mut p = Panel::new(); + let texts = p.frame(&mut app, vec![], Modifiers::NONE); + // The aspect field is the first 100% (above Opacity's). + let field = texts + .iter() + .filter(|(t, _)| t == "100%") + .map(|(_, at)| *at) + .min_by(|a, b| a.y.total_cmp(&b.y)) + .unwrap_or_else(|| panic!("the aspect field: {texts:?}")); + p.click(&mut app, field); + let key = |k, modifiers| Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers }; + p.frame(&mut app, vec![key(egui::Key::A, Modifiers::COMMAND), Event::Text("80".into())], Modifiers::NONE); + p.frame(&mut app, vec![key(egui::Key::Enter, Modifiers::NONE)], Modifiers::NONE); + assert_eq!(app.session.paint.fill, default, "bucket {bucket}: the default gradient"); + assert!(app.ui.status.is_empty(), "bucket {bucket}: {}", app.ui.status); + } +} + /// The Type row's Diamond button (the fourth of five) makes the gradient a diamond, and the /// Aspect Ratio field then edits its aspect. #[test] diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 18b9ecc6f5..7c69333bc6 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -2,8 +2,10 @@ //! (Small and Large List View), shown on a square or on type; a style with no fill and no stroke //! shows the shape outlined in black and filled with white, under a red slash. Clicking a style applies it to the //! selection (Alt-click adds it on top); Shift-click adds to the panel's selection every style from -//! the last one clicked without Shift through this one; Cmd/Ctrl-click adds or removes one; -//! double-click opens Graphic Style Options. Dragging a style moves it in the list (dropped on +//! the last one clicked without Shift through this one; Cmd/Ctrl-click adds or removes one. The +//! style last clicked into the selection is the one the Symbol Styler and the Symbol Sprayer's User +//! Defined Style apply. Double-click opens +//! Graphic Style Options. Dragging a style moves it in the list (dropped on //! another style with Alt held, replaces that style with its look), applies it //! to the art it is dropped on (`canvas::panel_drop`), or, dropped on New Graphic Style, adds a //! copy of it and of the styles highlighted with it at the end of the list; art dragged off the @@ -552,6 +554,11 @@ fn act(app: &mut VectorcraftApp, ui: &Ui, s: &Shown, ev: Events, picker: bool) { Some(Click::Pick(name, m)) => { let order: Vec<&str> = s.d.graphic_styles.iter().map(|g| g.name.as_str()).collect(); let sel = super::swatches::click_selection(ui, "gs-anchor", selected(ui.ctx(), s.d), &order, &name, m); + // The style clicked into the selection is the one the Symbol Styler and the Symbol + // Sprayer's User Defined Style apply (the two share it). + if sel.contains(&name) { + app.run("tool.setOption", json!({"tool": "symbolStyler", "values": {"style": name}})).ok(); + } set_pstate(ui.ctx(), "gs-sel", sel); // A plain click also applies the style (with nothing selected the next object drawn // takes it); Shift and Cmd/Ctrl clicks only select. @@ -1689,15 +1696,23 @@ mod tests { selected(&ctx, &app.session.active().unwrap().doc.clone()) }; let linked = |app: &VectorcraftApp| app.session.selection_graphic_style().map(|(g, _)| g.name.clone()); - // A plain click applies the style and selects it alone. + let styler = |app: &VectorcraftApp| app.session.tool_options_of("symbolStyler")["style"].as_str().map(str::to_string); + // A plain click applies the style and selects it alone; the Symbol Styler takes it. assert_eq!(click(&mut app, 0, egui::Modifiers::NONE), [n[0].clone()]); assert_eq!(linked(&app).as_ref(), Some(&n[0])); + assert_eq!(styler(&app).as_ref(), Some(&n[0])); // Shift-click selects from that style to the clicked one, and applies nothing. assert_eq!(click(&mut app, 3, egui::Modifiers::SHIFT), n[..4]); assert_eq!(linked(&app).as_ref(), Some(&n[0])); - // Cmd/Ctrl-click removes a selected style and adds it back. + assert_eq!(styler(&app).as_ref(), Some(&n[3])); + // Cmd/Ctrl-click removes a selected style and adds it back; the Styler keeps its style + // while one is removed. assert_eq!(click(&mut app, 2, egui::Modifiers::COMMAND), [n[0].clone(), n[1].clone(), n[3].clone()]); + assert_eq!(styler(&app).as_ref(), Some(&n[3])); assert_eq!(click(&mut app, 2, egui::Modifiers::COMMAND), [n[0].clone(), n[1].clone(), n[3].clone(), n[2].clone()]); + assert_eq!(styler(&app).as_ref(), Some(&n[2])); + // The Symbol Sprayer's User Defined Style applies the same style. + assert_eq!(app.session.tool_options_of("symbolSprayer")["style"].as_str(), Some(n[2].as_str())); // Shift-click extends from the style Cmd/Ctrl-clicked last. click(&mut app, 0, egui::Modifiers::NONE); click(&mut app, 2, egui::Modifiers::COMMAND); diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index 0d4d326b76..b0cdfad7f4 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -171,28 +171,17 @@ thread_local! { static TARGET_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// The object Trace acts on: the first selected image or Image Trace object in paint order, as -/// `imageTrace.make` takes it, else the first selected object. Only the selected images and Image -/// Trace objects are put in paint order. +/// The image or Image Trace object `imageTrace.make` takes from the selected roots, else the +/// first selected non-traceable object's metadata. Release and Expand keep their own selection scope. fn find_target(app: &VectorcraftApp) -> Target { let Some(st) = app.session.active() else { return Target::default() }; #[cfg(test)] TARGET_LOOKUPS.with(|n| n.set(n.get() + 1)); - let mut any_trace = false; - let traceable: Vec = st - .selection - .objects - .iter() - .copied() - .filter(|id| { - st.doc.node(*id).is_some_and(|n| { - let trace = is_trace(n); - any_trace |= trace; - trace || matches!(n.kind, NodeKind::Image(_)) - }) - }) - .collect(); - let node = st.doc.paint_order(traceable).into_iter().find_map(|id| st.doc.node(id)).or_else(|| first_node(app)); + let any_trace = st.selection.objects.iter().any(|id| st.doc.node(*id).is_some_and(is_trace)); + let node = vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null) + .ok() + .and_then(|id| st.doc.node(id)) + .or_else(|| first_node(app).filter(|n| !is_trace(n) && !matches!(n.kind, NodeKind::Image(_)))); let Some(n) = node else { return Target { any_trace, ..Target::default() } }; Target { object: Some((st.uid, n.id)), @@ -319,6 +308,175 @@ fn hold_source(app: &mut VectorcraftApp, ctx: &egui::Context, down: bool) { } } +/// The retained original image of a live trace, or the selected placed image itself. +fn source_image(n: &Node) -> Option<&vectorcraft_doc::ImageObject> { + let source = if is_trace(n) { n.children()?.first()?.as_ref() } else { n }; + match &source.kind { + NodeKind::Image(image) => Some(image), + _ => None, + } +} + +fn sampler_binding(s: &crate::state::TraceIgnoreSampler) -> Value { + json!({ "doc": s.doc, "target": s.target.0, "revision": s.revision }) +} + +fn sampler_valid(app: &VectorcraftApp, s: &crate::state::TraceIgnoreSampler) -> bool { + let Some(doc) = app.session.active() else { return false }; + doc.uid == s.doc + && doc.revision == s.revision + && find_target(app).object == Some((s.doc, s.target)) + && doc.doc.node(s.target).and_then(source_image).is_some_and(|image| doc.doc.images.contains_key(&image.key)) +} + +fn sampler_tool_active(app: &VectorcraftApp, s: &crate::state::TraceIgnoreSampler) -> bool { + app.session.tool_id() == "eyedropper" && app.session.tool_options()["imageTraceIgnoreColor"] == sampler_binding(s) +} + +/// Clear only this temporary mode. An explicit tool choice keeps the tool the user chose. +pub(crate) fn cancel_ignore_sampler(app: &mut VectorcraftApp, restore: bool) { + let Some(s) = app.ui.trace_ignore_sampler.take() else { return }; + // This UI session owns these transient fields even while Cmd/Ctrl parks the eyedropper + // behind a borrowed selection tool. The named setter also updates that stored lender. + let options = serde_json::Map::from_iter([("imageTraceIgnoreColor".into(), Value::Null), ("stop".into(), Value::Null)]); + app.session.set_tool_options(Some("eyedropper"), &options); + if restore && app.session.tool_id() == "eyedropper" { + app.return_to_tool(&s.back); + } + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); + } +} + +/// Presets and restored panel settings can turn Ignore Color off without its checkbox. +fn cancel_disabled_ignore_sampler(app: &mut VectorcraftApp, params: &Value) { + if params["ignoreWhite"] != true { + cancel_ignore_sampler(app, true); + } +} + +/// Also runs when the panel is closed: document changes and tool changes end the pick. +pub(crate) fn refresh_ignore_sampler(app: &mut VectorcraftApp) -> bool { + let Some(s) = app.ui.trace_ignore_sampler.as_ref() else { return false }; + if !sampler_valid(app, s) { + cancel_ignore_sampler(app, true); + } else if !sampler_tool_active(app, s) { + cancel_ignore_sampler(app, false); + } else { + return false; + } + true +} + +/// A stale sampler's click must not become a paint/selection click in the restored tool. +pub(crate) fn discard_stale_ignore_click(app: &mut VectorcraftApp) -> bool { + let Some(s) = app.ui.trace_ignore_sampler.as_ref() else { return false }; + if sampler_valid(app, s) && sampler_tool_active(app, s) { + return false; + } + let restore = app.session.tool_id() == "eyedropper"; + cancel_ignore_sampler(app, restore); + true +} + +fn start_ignore_sampler(app: &mut VectorcraftApp, ctx: &egui::Context) { + if app.ui.trace_ignore_sampler.is_some() { + cancel_ignore_sampler(app, true); + return; + } + let Some((doc, target)) = target(app, ctx).object else { return }; + let Some(revision) = app.session.active().map(|d| d.revision) else { return }; + let s = crate::state::TraceIgnoreSampler { doc, target, revision, back: app.session.tool_id().to_string() }; + if !sampler_valid(app, &s) { + return; + } + if let Err(e) = app.try_select_tool("eyedropper") { + app.status(e); + return; + } + if !sampler_valid(app, &s) { + app.return_to_tool(&s.back); + return; + } + app.session.set_tool_option("imageTraceIgnoreColor", &sampler_binding(&s)); + app.session.set_tool_option("stop", &json!(s.back.as_str())); + // Bind the reply to this panel's state, also when it is drawn without the full app frame. + app.ui_ctx = Some(ctx.clone()); + app.ui.trace_ignore_sampler = Some(s); + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); + } +} + +/// Match Image Trace's input bytes, not the current canvas result or the working-space colour. +fn sampled_ignore_color(app: &VectorcraftApp, s: &crate::state::TraceIgnoreSampler, p: &Value) -> Option { + let point = vectorcraft_geom::Point::new(p["point"][0].as_f64()?, p["point"][1].as_f64()?); + if !point.x.is_finite() || !point.y.is_finite() { + return None; + } + let doc = &app.session.active()?.doc; + let image = source_image(doc.node(s.target)?)?; + if image.xf.determinant().abs() < 1e-12 { + return None; + } + let pixel = image.xf.inverse() * point; + if !pixel.x.is_finite() + || !pixel.y.is_finite() + || pixel.x < 0.0 + || pixel.y < 0.0 + || pixel.x >= f64::from(image.width.max(1)) + || pixel.y >= f64::from(image.height.max(1)) + { + return None; + } + let [r, g, b, alpha] = doc.images.get(&image.key)?.sample_object(pixel.x, pixel.y, (image.width, image.height), 1)?; + (alpha != 0).then(|| format!("#{r:02x}{g:02x}{b:02x}")) +} + +/// A miss keeps the pick armed; only a valid source color, Escape or invalid binding ends it. +pub(crate) fn apply_ignore_color_sample(app: &mut VectorcraftApp, p: &Value) { + let Some(s) = app.ui.trace_ignore_sampler.as_ref() else { return }; + if p["binding"] != sampler_binding(s) { + return; + } + if p["cancel"] == true { + // Escape already carries its one deferred SwitchTool request. + cancel_ignore_sampler(app, false); + return; + } + if !sampler_valid(app, s) { + cancel_ignore_sampler(app, true); + return; + } + // Outside the source or over a transparent pixel there is no color to accept. Keep the + // binding and previous tool so the next canvas click can still complete this pick. + let Some(color) = sampled_ignore_color(app, s, p) else { return }; + let s = s.clone(); + // The canvas UI establishes this context before a real panel click can arm the sampler. + let Some(ctx) = app.ui_ctx.clone() else { return }; + cancel_ignore_sampler(app, false); + let all = presets(app, &ctx); + let mut st: TraceUi = pstate(&ctx, "image-trace"); + let Target { is_trace, stored, .. } = target(app, &ctx); + follow_preset_changes(app, &mut st, &all); + let changes: Vec<&TracePresetChange> = app.session.trace_preset_changes_since(0).collect(); + sync_with_object(&mut st, stored, Some((s.doc, s.target)), &all, &changes); + st.params["ignoreColor"] = json!(color); + st.preset = "Custom".into(); + let preview = app.ui.image_trace_preview; + if is_trace || !preview { + st.preview_off = !preview; + } + if is_trace && preview { + trace(app, &ctx, &mut st); + } + set_pstate(&ctx, "image-trace", st); + ctx.request_repaint(); + // Complete the temporary tool without treating its return as a fresh explicit tool choice. + // A miss above has no switch request and remains armed. + app.return_to_tool(&s.back); +} + /// The selected Image Trace object's View row (Control bar, Properties). pub(crate) fn view_row(app: &mut VectorcraftApp, ui: &mut Ui, current: TraceView, width: f32) { widgets::dim_label(ui, tl!("View:")); @@ -894,17 +1052,36 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.horizontal(|ui| { let on = st.params["ignoreWhite"].as_bool().unwrap_or(false); if widgets::check(ui, tl!("Ignore Color"), on, true) { + if on { + cancel_ignore_sampler(app, true); + } st.params["ignoreWhite"] = json!(!on); st.preset = "Custom".into(); retrace = true; } if on { let mut rgb = ignore_color(&st.params); - if ui.color_edit_button_srgb(&mut rgb).changed() { + let picker = ui.color_edit_button_srgb(&mut rgb); + if picker.clicked() { + cancel_ignore_sampler(app, true); + } + if picker.changed() { st.params["ignoreColor"] = json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])); st.preset = "Custom".into(); retrace = true; } + if widgets::icon_button_enabled( + ui, + "pipette", + tl!("Eyedropper: click the source image to sample the ignored color"), + app.ui.trace_ignore_sampler.is_some(), + is_trace || is_image, + 22.0, + ) + .clicked() + { + start_ignore_sampler(app, ui.ctx()); + } } }); } @@ -942,6 +1119,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if is_trace || !preview { st.preview_off = !preview; } + cancel_disabled_ignore_sampler(app, &st.params); if retrace && is_trace && preview { trace(app, ui.ctx(), &mut st); } diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index 15cbffe9e9..c35a961aa3 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -1763,7 +1763,8 @@ fn lookup_fixture() -> (VectorcraftApp, std::collections::HashMap<&'static str, /// The panel's lookup gives what putting the whole selection in paint order gave, field for field, /// for every kind of selection: images in either selection order, an Image Trace object with its /// own image, a clipping group named Image Trace, nested groups, hidden and locked images, two -/// layers, repeated ids, ids the document lacks, and nothing selected. The result kept for a +/// layers, repeated ids, ids the document lacks, and nothing selected. Selected ancestors with +/// their descendants have separate canonical-root expectations below. The result kept for a /// revision follows each change of the selection, an edit, Undo and a switch of document. #[test] fn the_target_lookup_matches_sorting_the_whole_selection() { @@ -1779,10 +1780,8 @@ fn the_target_lookup_matches_sorting_the_whole_selection() { &["trace image", "trace"], &["rect", "trace image"], &["clip"], - &["clip", "clipped"], &["rect", "clipped"], &["outer"], - &["outer", "deep"], &["inner", "rect"], &["deep", "back"], &["hidden", "locked"], @@ -1838,6 +1837,37 @@ fn the_target_lookup_matches_sorting_the_whole_selection() { assert_eq!(target(&none, &ctx), Target::default()); } +/// Trace only accepts selected roots: a selected parent blocks its image descendant. +/// Missing implicit-selection ids are dropped, while explicit ids are validated. +#[test] +fn the_target_lookup_obeys_canonical_roots_and_explicit_id_validation() { + let (mut app, ids) = lookup_fixture(); + let ctx = egui::Context::default(); + for (parent, child) in [("clip", "clipped"), ("outer", "deep")] { + select_as_is(&mut app, &[ids[parent], ids[child]]); + let uid = app.session.active().unwrap().uid; + let expected = Target { object: Some((uid, ids[parent])), ..Default::default() }; + assert_eq!(find_target(&app), expected, "the selected {parent} supplies metadata, not its pruned image"); + assert_eq!(target(&app, &ctx), expected); + assert_eq!(target(&app, &ctx), expected, "the canonical result is also cached"); + assert!(vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null).is_err()); + let document = app.session.active().unwrap().doc.clone(); + assert!(app.run("imageTrace.make", json!({})).is_err(), "Trace rejects that non-image root"); + assert_eq!(app.session.active().unwrap().doc, document); + select_as_is(&mut app, &[ids[child]]); + assert_eq!(vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null).unwrap(), ids[child], "the image alone remains eligible"); + } + let stale = NodeId(u64::MAX); + select_as_is(&mut app, &[stale, ids["front"]]); + assert_eq!(target(&app, &ctx).object.map(|(_, id)| id), Some(ids["front"]), "implicit stale entries do not hide a valid image"); + assert_eq!(vectorcraft_engine::cmd::image_trace_target(&app.session, &Value::Null).unwrap(), ids["front"]); + let explicit = json!({"ids": [stale.0, ids["front"].0]}); + let document = app.session.active().unwrap().doc.clone(); + assert!(vectorcraft_engine::cmd::image_trace_target(&app.session, &explicit).is_err(), "explicit missing ids are invalid"); + assert!(app.run("imageTrace.make", explicit).is_err()); + assert_eq!(app.session.active().unwrap().doc, document); +} + /// The panel and its menu look the object Trace acts on up once for each revision of the document, /// however many frames show it, and again once the revision moves. #[test] diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index cf68e1d5bd..b631596535 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -82,6 +82,26 @@ fn set_options(ctx: &egui::Context, f: impl FnOnce(&mut Options)) { set_pstate(ctx, "links-options", o); } +/// Show the Links panel on the selected image (the Control bar's Linked File or Embedded label), +/// wherever the panel is docked or floats; a panel that is already shown stays where it is. The +/// Link Info section opens, and when the panel next draws the list, a Show filter that leaves out +/// the image's row goes back to Show All and the list scrolls to the row ([`show`]). The sort, +/// thumbnail size and DCS option keep their settings. +pub(crate) fn show_selected_image(app: &mut VectorcraftApp, ctx: &egui::Context) { + let first = selected_images(app).first().copied(); + let request = app.session.active().map(|st| st.uid).zip(first); + set_pstate(ctx, "links-scroll-to", request); + // The list drawn next is read after this request, so a row a file change has just brought + // into the Show filter is there to scroll to. + let mut c: std::sync::Arc = pstate(ctx, "links-cache"); + std::sync::Arc::make_mut(&mut c).at = f64::NEG_INFINITY; + set_pstate(ctx, "links-cache", c); + set_options(ctx, |o| o.info = true); + if let Err(e) = crate::panel_docking::reveal_panel(app, ID) { + app.status(e); + } +} + /// The rows to show (cached per document revision, the files looked at again every [`RECHECK`] /// seconds) and the Link Info of the first selected image when the section is open. A frame that /// fetches nothing returns the stored cache without copying it and stores nothing. @@ -577,16 +597,32 @@ fn click(app: &mut VectorcraftApp, ctx: &egui::Context, rows: &[Value], id: u64, pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); - let o = options(ui.ctx()); + let mut o = options(ui.ctx()); super::layers::show_thumbs_of(app.session.active().map(|st| st.uid)); - let Some(cache) = cached(app, ui.ctx(), &o) else { + let Some(mut cache) = cached(app, ui.ctx(), &o) else { widgets::dim_label(ui, tl!("No document")); return; }; + // The row that `show_selected_image` asks for, used by this draw only and only in the document + // it was asked in. A Show filter that leaves the row out goes back to Show All, decided from the + // rows this frame draws and scrolls through. + let request: Option<(u64, u64)> = pstate(ui.ctx(), "links-scroll-to"); + if request.is_some() { + set_pstate::>(ui.ctx(), "links-scroll-to", None); + } + let uid = app.session.active().map(|st| st.uid); + let scroll_to = request.filter(|(doc, _)| Some(*doc) == uid).map(|(_, id)| id); + let listed = |cache: &Cache, id: u64| cache.list["links"].as_array().is_some_and(|rows| rows.iter().any(|r| r["id"].as_u64() == Some(id))); + if scroll_to.filter(|id| o.show != "all" && !listed(&cache, *id)).is_some() { + set_options(ui.ctx(), |o| o.show = "all"); + o = options(ui.ctx()); + let Some(all) = cached(app, ui.ctx(), &o) else { return }; + cache = all; + } let Some(st) = app.session.active() else { return }; let doc = st.doc.clone(); let thumbs = super::layers::ThumbSource::of(app, st, &doc); - let selected = selected_links(app, ui.ctx()); + let mut selected = selected_links(app, ui.ctx()); let rows: &[Value] = cache.list["links"].as_array().map_or(&[], Vec::as_slice); let mut clicked: Option<(u64, egui::Modifiers, bool)> = None; widgets::list_box(ui, |ui| { @@ -606,6 +642,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { for r in rows { let Some(id) = r["id"].as_u64() else { continue }; let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click()); + if scroll_to == Some(id) { + ui.scroll_to_rect(rect, Some(egui::Align::Center)); + } if !ui.is_rect_visible(rect) { continue; } @@ -659,6 +698,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .and_then(|m| doc.node(NodeId(m)).or_else(|| cache.nested_node(m).map(|n| &**n))) .map(|n| super::layers::shown_name(app, n, crate::i18n::current())); let resp = resp.on_hover_text(status_tip(r, mask)); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, ui.is_enabled(), selected.contains(&id), name)); + if resp.secondary_clicked() && !selected.contains(&id) { + click(app, ui.ctx(), rows, id, egui::Modifiers::NONE); + selected = selected_links(app, ui.ctx()); + } + resp.context_menu(|ui| { + row_context_menu(app, ui, r, id, &cache.list); + }); if resp.double_clicked() { clicked = Some((id, egui::Modifiers::NONE, true)); } else if resp.clicked() { @@ -728,6 +775,78 @@ fn break_link(app: &mut VectorcraftApp, ids: Vec) { }); } +/// Embed images `ids` (`links.embed`). +fn embed_images(app: &mut VectorcraftApp, ids: Vec) { + let r = app.run("links.embed", json!({ "ids": ids })); + report(app, r, |v| { + let missing = v["missing"].as_array().map_or(0, Vec::len); + let n = v["embedded"].as_array().map_or(0, Vec::len); + if missing == 0 { + crate::i18n::msg_n(n as u64, "Embedded {n} image", "Embedded {n} images", &[]) + } else { + crate::i18n::msg_n( + n as u64, + "Embedded {n} image; {missing} missing: relink them first", + "Embedded {n} images; {missing} missing: relink them first", + &[("missing", &missing.to_string())], + ) + } + }); +} + +/// An item's right-click context menu in the Links panel. +fn row_context_menu(app: &mut VectorcraftApp, ui: &mut Ui, r: &Value, id: u64, list: &Value) { + let selected = selected_links(app, ui.ctx()); + let sel = selected_rows(list, &selected); + let linked = ids(&sel, |r| r["linked"] == true); + let embedded: Vec<&Value> = sel.iter().copied().filter(|r| status_is(r, "embedded")).collect(); + let modified = ids(&sel, |r| status_is(r, "modified") || (r["preview"] == true && !status_is(r, "missing"))); + let can_edit = sel.iter().any(|r| r["linked"] == true && !status_is(r, "missing")); + let in_canvas = app.session.active().is_some_and(|st| st.doc.node(NodeId(id)).is_some()) && !nested_row(r); + + if menu_item(ui, tl!("Relink…"), !sel.is_empty() && can_pick(app), false) { + crate::menus::invoke(app, "ui.relinkDialog", json!({ "ids": ids(&sel, |_| true) })); + ui.close(); + } + if menu_item(ui, tl!("Go To Link"), in_canvas, false) { + go_to(app, id); + ui.close(); + } + if menu_item(ui, tl!("Update Link"), !modified.is_empty(), false) { + let r = app.run("links.update", json!({ "ids": modified })); + report(app, r, |v| updated_status(v["updated"].as_array().map_or(0, Vec::len))); + ui.close(); + } + if menu_item(ui, tl!("Edit Original"), can_edit, false) { + let file_arg = if r["linked"] == true && !status_is(r, "missing") { json!({ "id": id }) } else { file_row(&sel) }; + crate::menus::invoke(app, "links.editOriginal", file_arg); + ui.close(); + } + if menu_item(ui, tl!("Show in Folder"), can_edit, false) { + let file_arg = if r["linked"] == true && !status_is(r, "missing") { json!({ "id": id }) } else { file_row(&sel) }; + crate::menus::invoke(app, "links.reveal", file_arg); + ui.close(); + } + ui.separator(); + if status_is(r, "embedded") { + if menu_item(ui, tl!("Unembed…"), can_unembed(app, embedded.len()), false) { + match &embedded[..] { + [r] => { + if let Some(id) = r["id"].as_u64() { + let name = r["name"].as_str().unwrap_or("Image").to_string(); + unembed(app, id, &name); + } + } + rows => unembed_several(app, rows.iter().filter_map(|r| r["id"].as_u64()).collect()), + } + ui.close(); + } + } else if menu_item(ui, tl!("Embed Image"), !linked.is_empty(), false) { + embed_images(app, linked); + ui.close(); + } +} + /// The params of Edit Original and Show in Folder for the selected rows `sel`: the first linked /// row whose file is there (rows outside the layer tree included), else none (the selection's). fn file_row(sel: &[&Value]) -> Value { @@ -854,21 +973,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.separator(); if menu_item(ui, tl!("Embed Image(s)"), !linked.is_empty(), false) { - let r = app.run("links.embed", json!({ "ids": linked })); - report(app, r, |v| { - let missing = v["missing"].as_array().map_or(0, Vec::len); - let n = v["embedded"].as_array().map_or(0, Vec::len); - if missing == 0 { - crate::i18n::msg_n(n as u64, "Embedded {n} image", "Embedded {n} images", &[]) - } else { - crate::i18n::msg_n( - n as u64, - "Embedded {n} image; {missing} missing: relink them first", - "Embedded {n} images; {missing} missing: relink them first", - &[("missing", &missing.to_string())], - ) - } - }); + embed_images(app, linked); } if menu_item(ui, tl!("Unembed…"), can_unembed(app, embedded.len()), false) { match &embedded[..] { diff --git a/crates/ui-egui/src/panels/retype/tests.rs b/crates/ui-egui/src/panels/retype/tests.rs index 8a7370bc5a..49f067c0b2 100644 --- a/crates/ui-egui/src/panels/retype/tests.rs +++ b/crates/ui-egui/src/panels/retype/tests.rs @@ -97,6 +97,10 @@ fn more_adds_fonts_until_none_is_left() { } assert_eq!(last["more"], json!(false), "{last}"); assert_eq!(app.run("retype.find", json!({"more": true})).unwrap(), last, "nothing is left to add"); + // A null more is omitted: a new search lists the first ten again. A font added to the list + // tells the new search apart from adding more when ten or fewer fonts match. + app.ui.retype.fonts.push(super::Found { family: "Not Found".into(), style: "Regular".into(), matched: 0 }); + assert_eq!(app.run("retype.find", json!({"more": null})).unwrap(), first); // Before any search, more is a first search. app.run("retype.reset", json!({})).unwrap(); assert_eq!(app.run("retype.find", json!({"more": true})).unwrap(), first); diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index bdecc90a07..9e245fdc2c 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -109,10 +109,16 @@ fn arrow_label(a: Option<&Arrowhead>) -> &'static str { fn arrow_name(a: Option<&Arrowhead>) -> String { match a { Some(Arrowhead::Custom(c)) => c.name.clone(), - _ => tl!(arrow_label(a)).to_string(), + _ => builtin_arrow_name(arrow_label(a)).to_string(), } } +/// A built-in arrowhead's name `label` in the interface language. Its `arrowhead` row comes first, +/// so a name that is also an effect's (Feather) can be translated for each one. +pub(crate) fn builtin_arrow_name(label: &str) -> &str { + crate::i18n::tr_ctx(crate::i18n::current(), "arrowhead", label) +} + /// The preview cache key of `a`: its name, and for a custom head its art. fn arrow_key(a: Option<&Arrowhead>) -> String { match a { diff --git a/crates/ui-egui/src/panels/swatches/actions.rs b/crates/ui-egui/src/panels/swatches/actions.rs index 812a3ffb33..dc26c78550 100644 --- a/crates/ui-egui/src/panels/swatches/actions.rs +++ b/crates/ui-egui/src/panels/swatches/actions.rs @@ -276,6 +276,11 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { if menu_item(ui, tl!("Add Used Colors"), true, false) { app.run("swatch.addUsedColors", json!({})).ok(); } + // The selected art's new colors, as global swatches its paints link to. + let art_selected = app.session.active().is_some_and(|st| !st.selection.objects.is_empty()); + if menu_item(ui, tl!("Add Selected Colors"), art_selected, false) { + app.run("swatch.addUsedColors", json!({"selection": true, "global": true})).ok(); + } ui.separator(); if menu_item(ui, tl!("Sort by Name"), true, false) { app.run("swatch.sortByName", json!({})).ok(); diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index 5cf2d06b23..dc76bb3fc7 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -65,8 +65,10 @@ pub(super) enum Drop { /// nor a tint swatch. With Cmd/Ctrl held (`spot`), a solid color other than Registration /// becomes a spot color swatch. New { paint: Paint, target: Option, replace: bool, spot: bool }, - /// Art dragged off the canvas becomes a pattern swatch made of a copy of it (the art stays). - Pattern { ids: Vec }, + /// Art dragged off the canvas becomes a pattern swatch made of a copy of it (the art stays); + /// with Alt held (`replace`) over pattern swatch `target`, a copy of it becomes that pattern's + /// tile art instead. + Pattern { ids: Vec, target: Option, replace: bool }, } impl Drop { @@ -81,16 +83,42 @@ impl Drop { Some(Drop::Move { names: r.names.clone(), target, after, with }) } PanelDrag::Paint { paint, .. } => Some(Drop::New { paint: paint.clone(), target, replace, spot }), - PanelDrag::Art(ids) => Some(Drop::Pattern { ids: ids.iter().map(|id| id.0).collect() }), + PanelDrag::Art(ids) => Some(Drop::Pattern { ids: ids.iter().map(|id| id.0).collect(), target, replace }), _ => None, } } } -/// The drag held over `resp`, if the panel takes it (paints and art dragged off the canvas, not the -/// Appearance panel's thumbnail). +/// Whether the panel takes drag `d`: paints and art dragged off the canvas, not the Appearance +/// panel's thumbnail. +fn takes(d: &PanelDrag) -> bool { + matches!(d, PanelDrag::Paint { .. } | PanelDrag::Art(_)) +} + +/// The drag held over `resp`, if the panel takes it ([`takes`]). fn held(resp: &Response) -> Option> { - resp.dnd_hover_payload::().filter(|d| matches!(**d, PanelDrag::Paint { .. } | PanelDrag::Art(_))) + resp.dnd_hover_payload::().filter(|d| takes(d)) +} + +/// The drag in progress, if the panel takes it ([`takes`]), wherever the pointer is. +fn dragged(ui: &Ui) -> Option> { + egui::DragAndDrop::payload::(ui.ctx()).filter(|d| takes(d)) +} + +/// Where the primary button came up this frame and the modifiers held then, when that was over +/// `resp` with no other layer on top (the test [`egui::Context::rect_contains_pointer`] makes of the +/// pointer). A drop lands there with those modifiers, even when the pointer moved on or a key was +/// let go later in the same frame. +fn released_over(ui: &Ui, resp: &Response) -> Option<(egui::Pos2, egui::Modifiers)> { + let up = ui.input(|i| { + i.events.iter().find_map(|e| match e { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers } => Some((*pos, *modifiers)), + _ => None, + }) + })?; + let ctx = ui.ctx(); + let rect = ctx.layer_transform_to_global(resp.layer_id).map_or(resp.interact_rect, |t| t * resp.interact_rect); + (rect.is_positive() && rect.contains(up.0) && ctx.layer_id_at(up.0) == Some(resp.layer_id)).then_some(up) } /// The drag a tile or row of `e` starts, moving rows `names`. Colour groups have no paint of their @@ -157,64 +185,80 @@ pub(super) fn tile_input(ui: &Ui, resp: Response, e: &Entry, items: &[Entry], se } /// A drag held over the tile or row `resp` of entry `e` shows where it would land (before or after -/// it by the pointer's half, or into a folder); a release there sets the drop. +/// it by the pointer's half, or into a folder), by where the pointer is and the keys held now. A +/// release over it ([`released_over`]) sets the drop, by where the button came up and the keys held +/// then. fn tile_drop(ui: &Ui, resp: &Response, e: &Entry, list: bool, ev: &mut TileEvents) { - let Some(d) = held(resp) else { return }; - let PanelDrag::Paint { rows, .. } = &*d else { return }; - let name = e.name(); - ev.over = true; - // Swatches dropped on one of themselves stay where they are. - if rows.as_ref().is_some_and(|r| r.names.iter().any(|n| n == name)) { - resp.dnd_release_payload::(); + let up = released_over(ui, resp); + let hover = held(resp); + let Some(d) = hover.clone().or_else(|| up.and_then(|_| dragged(ui))) else { return }; + let take = || egui::DragAndDrop::take_payload::(ui.ctx()).is_some(); + // Art held with Alt over a pattern swatch would replace its tile art, and the swatch is + // outlined; other art goes to the list (see [`zone_input`]). + if let PanelDrag::Art(_) = &*d { + if !matches!(e, Entry::Swatch { paint: Paint::Pattern { .. }, .. }) { + return; + } + if hover.is_some() && crate::panels::alt_held(ui) { + ev.over = true; + let t = Tokens::get(ui.ctx()); + ui.painter().rect_stroke(resp.rect.expand(1.0), 0.0, Stroke::new(1.5, t.accent), StrokeKind::Outside); + } + if up.is_some_and(|(_, m)| m.alt) && take() { + ev.drop = Drop::of(&d, Some(e.name().to_string()), false, true, false); + } return; } - let t = Tokens::get(ui.ctx()); - let r = resp.rect; - let at = ui.input(|i| i.pointer.interact_pos()).unwrap_or(r.center()); - let after = if list { at.y > r.center().y } else { at.x > r.center().x }; - // A paint from elsewhere, or swatches over a folder, go into it; otherwise a bar marks the slot. - if rows.as_ref().is_none_or(|d| e.is_folder() && !d.groups) { - ui.painter().rect_stroke(r.expand(1.0), 0.0, Stroke::new(1.5, t.accent), StrokeKind::Outside); - } else if list { - let y = if after { r.bottom() } else { r.top() }; - ui.painter().line_segment([pos2(r.left(), y), pos2(r.right(), y)], Stroke::new(2.0, t.accent)); - } else { - let x = if after { r.right() + 0.75 } else { r.left() - 0.75 }; - ui.painter().line_segment([pos2(x, r.top() - 1.0), pos2(x, r.bottom() + 1.0)], Stroke::new(2.0, t.accent)); + let PanelDrag::Paint { rows, .. } = &*d else { return }; + let name = e.name(); + if hover.is_some() { + ev.over = true; } - if resp.dnd_release_payload::().is_some() { - let m = release_modifiers(ui); - ev.drop = Drop::of(&d, Some(name.to_string()), after, m.alt, m.command); + // Swatches dropped on one of themselves stay where they are. + if rows.as_ref().is_some_and(|r| r.names.iter().any(|n| n == name)) { + if up.is_some() { + take(); + } + return; + } + let r = resp.rect; + let side = |at: egui::Pos2| if list { at.y > r.center().y } else { at.x > r.center().x }; + if hover.is_some() { + let t = Tokens::get(ui.ctx()); + let after = side(ui.input(|i| i.pointer.interact_pos()).unwrap_or(r.center())); + // A paint from elsewhere, or swatches over a folder, go into it; otherwise a bar marks the slot. + if rows.as_ref().is_none_or(|d| e.is_folder() && !d.groups) { + ui.painter().rect_stroke(r.expand(1.0), 0.0, Stroke::new(1.5, t.accent), StrokeKind::Outside); + } else if list { + let y = if after { r.bottom() } else { r.top() }; + ui.painter().line_segment([pos2(r.left(), y), pos2(r.right(), y)], Stroke::new(2.0, t.accent)); + } else { + let x = if after { r.right() + 0.75 } else { r.left() - 0.75 }; + ui.painter().line_segment([pos2(x, r.top() - 1.0), pos2(x, r.bottom() + 1.0)], Stroke::new(2.0, t.accent)); + } + } + if let Some((at, m)) = up + && take() + { + ev.drop = Drop::of(&d, Some(name.to_string()), side(at), m.alt, m.command); } } /// Drops between and after the tiles (`zone`: the list's viewport) go to the end of the ungrouped /// swatches (colour groups to the end of the groups); the list is outlined while one is held there. +/// A tile that took the release first leaves nothing to drop here. pub(super) fn zone_input(ui: &Ui, zone: &Response, ev: &mut TileEvents) { - let Some(d) = held(zone) else { return }; - if !ev.over { + if held(zone).is_some() && !ev.over { ui.painter().rect_stroke(zone.rect, 0.0, Stroke::new(1.5, Tokens::get(ui.ctx()).accent), StrokeKind::Inside); } - if zone.dnd_release_payload::().is_some() { - ev.drop = Drop::of(&d, None, false, false, release_modifiers(ui).command); + if let Some((_, m)) = released_over(ui, zone) + && let Some(d) = dragged(ui) + && egui::DragAndDrop::take_payload::(ui.ctx()).is_some() + { + ev.drop = Drop::of(&d, None, false, false, m.command); } } -/// The modifiers (Alt; Cmd on macOS, Ctrl on Windows and Linux) held when the primary button was -/// released this frame, as the release event carries them, so a key let go later in the same frame -/// does not change the drop. Without such an event, the modifiers held at the end of the frame. -fn release_modifiers(ui: &Ui) -> egui::Modifiers { - ui.input(|i| { - i.events - .iter() - .find_map(|e| match e { - egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } => Some(*modifiers), - _ => None, - }) - .unwrap_or(i.modifiers) - }) -} - /// The colour group `name` is, or the one swatch `name` belongs to. pub(super) fn group_of(d: &Document, name: &str) -> Option { if d.swatch_groups.iter().any(|g| g.name == name) { @@ -270,6 +314,14 @@ fn replaces(d: &Document, with: &str, target: &str) -> bool { } } +/// The pattern swatch `name` paints with. +fn swatch_pattern(d: &Document, name: &str) -> Option { + match &d.swatch(name)?.paint { + Paint::Pattern { pattern, .. } => Some(pattern.clone()), + _ => None, + } +} + /// `paint` as swatch params. A solid color other than Registration is sent as the color the drag /// carries, not as its base swatch and tint, which the command would resolve again at the drop. fn shown_color_params(paint: &Paint) -> Value { @@ -280,10 +332,11 @@ fn shown_color_params(paint: &Paint) -> Value { } /// Run a drop on the panel: move the swatches, give the paint of a swatch Alt-dropped on another of -/// its kind to that one, or make a swatch of the proxy's paint (a color dropped on a folder or a +/// its kind to that one, make a swatch of the proxy's paint (a color dropped on a folder or a /// grouped swatch joins that group; a color Cmd/Ctrl-dropped becomes a new spot color of the color -/// the drag shows, tints included). With Alt also held, a color dropped on a swatch it can replace -/// replaces that swatch's color with the color the drag shows and makes no spot color. +/// the drag shows, tints included), or make a pattern swatch of art (Alt-dropped on a pattern +/// swatch: the art becomes that pattern's tile art). With Alt also held, a color dropped on a swatch +/// it can replace replaces that swatch's color with the color the drag shows and makes no spot color. pub(super) fn apply_drop(app: &mut VectorcraftApp, drop: Drop) { let Some(d) = app.session.active().map(|st| &st.doc) else { return }; let (cmd, params) = match drop { @@ -315,7 +368,11 @@ pub(super) fn apply_drop(app: &mut VectorcraftApp, drop: Drop) { } ("swatch.new", p) } - Drop::Pattern { ids } => ("object.pattern.make", json!({"ids": ids, "edit": false})), + // Alt: over a pattern swatch, the art becomes that pattern's tile art. + Drop::Pattern { ids, target, replace } => match target.filter(|_| replace).and_then(|t| swatch_pattern(d, &t)) { + Some(name) => ("object.pattern.replaceArt", json!({"name": name, "ids": ids})), + None => ("object.pattern.make", json!({"ids": ids, "edit": false})), + }, }; if let Err(e) = app.run(cmd, params) { app.status(e); diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index e871c8d68b..a3e7120c7a 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -1021,6 +1021,92 @@ fn art_dropped_on_the_panel_becomes_a_pattern_swatch() { assert!(egui::DragAndDrop::payload::(&ctx).is_none()); } +/// Art released with Alt held over a pattern swatch becomes that pattern's tile art in one undo +/// step: no pattern or swatch is added and the art stays. With Alt over a color swatch, or without +/// Alt over the pattern swatch, the art becomes a new pattern swatch as before. +#[test] +fn art_alt_dropped_on_a_pattern_swatch_replaces_its_tile_art() { + let mut app = app(); + let square = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + app.run("object.pattern.make", json!({"ids": [square], "name": "Dots", "edit": false})).unwrap(); + let id = app.run("shape.star", json!({"cx": 50, "cy": 50, "radius1": 20, "radius2": 9, "points": 5})).unwrap()["id"].as_u64().unwrap(); + let star = vectorcraft_doc::NodeId(id); + let count = |app: &mut VectorcraftApp| app.run("pattern.list", json!({})).unwrap()["patterns"].as_array().map(Vec::len); + let tile_art = |app: &VectorcraftApp| app.session.doc().unwrap().doc.pattern("Dots").map(|p| p.art.clone()); + let ctx = context(); + let drop = |app: &mut VectorcraftApp, on: &str, modifiers: Modifiers, time: f64| { + frame(app, &ctx, vec![], time, show); + let at = tile_center(&ctx, on); + egui::DragAndDrop::set_payload(&ctx, PanelDrag::Art(vec![star])); + let release = Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers }; + frame_with(app, &ctx, vec![Event::PointerMoved(at), release], modifiers, time + 0.5, show); + assert!(egui::DragAndDrop::payload::(&ctx).is_none(), "{on}: the drop is taken"); + }; + let (before, undo, star_before) = (tile_art(&app), undo_steps(&app), app.session.doc().unwrap().doc.node(star).cloned()); + drop(&mut app, "Dots", Modifiers::ALT, 0.0); + let art = tile_art(&app).expect("Dots stays"); + assert_ne!(Some(&art), before.as_ref(), "{}", app.ui.status); + assert_eq!(art.len(), 1); + assert_eq!(Some(&art[0].kind), star_before.as_ref().map(|n| &n.kind), "the star is the tile art"); + assert_eq!(count(&mut app), Some(1), "no new pattern"); + assert_eq!(undo_steps(&app), undo + 1, "one undo step"); + assert_eq!(app.session.doc().unwrap().doc.node(star).cloned(), star_before, "the star stays as it was"); + // Alt over a color swatch: a new pattern. + drop(&mut app, "Bright Red", Modifiers::ALT, 1.0); + assert_eq!(count(&mut app), Some(2), "Alt over a color swatch makes a pattern"); + // No Alt over the pattern swatch: a new pattern, and Dots keeps its art. + drop(&mut app, "Dots", Modifiers::NONE, 2.0); + assert_eq!(count(&mut app), Some(3), "a plain drop on a pattern swatch makes a pattern"); + assert_eq!(tile_art(&app), Some(art), "Dots keeps its tile art"); +} + +/// A drop lands where the button came up, with the keys held then. Art released with Alt held +/// over pattern swatch Dots replaces the tile art of Dots when Alt is let go, or the pointer moves +/// on to pattern swatch Stripes, later in the same frame. Art released over Dots without Alt makes +/// a new pattern when Alt is pressed later in that frame. A color released with Alt held over Red +/// gives Red that color when Alt is let go later in the frame. +#[test] +fn a_drop_lands_where_the_button_came_up_with_the_keys_held_then() { + let mut app = app(); + for (x, name) in [(0, "Dots"), (20, "Stripes")] { + let id = app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + app.run("object.pattern.make", json!({"ids": [id], "name": name, "edit": false})).unwrap(); + } + let id = app.run("shape.star", json!({"cx": 50, "cy": 50, "radius1": 20, "radius2": 9, "points": 5})).unwrap()["id"].as_u64().unwrap(); + let star = vectorcraft_doc::NodeId(id); + let star_kind = app.session.doc().unwrap().doc.node(star).map(|n| n.kind.clone()); + let tile_kind = + |app: &VectorcraftApp, name: &str| app.session.doc().unwrap().doc.pattern(name).and_then(|p| p.art.first().map(|n| n.kind.clone())); + let count = |app: &mut VectorcraftApp| app.run("pattern.list", json!({})).unwrap()["patterns"].as_array().map(Vec::len); + let ctx = context(); + // In one frame: release over `on` with `up` held, then hold `then` and move over `to`. + let drop = |app: &mut VectorcraftApp, payload: PanelDrag, on: &str, up: Modifiers, then: Modifiers, to: &str, time: f64| { + frame(app, &ctx, vec![], time, show); + let (at, next) = (tile_center(&ctx, on), tile_center(&ctx, to)); + egui::DragAndDrop::set_payload(&ctx, payload); + let release = Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: up }; + let events = vec![Event::PointerMoved(at), release, Event::ModifiersChanged(then), Event::PointerMoved(next)]; + frame_with(app, &ctx, events, up, time + 0.5, show); + assert!(egui::DragAndDrop::payload::(&ctx).is_none(), "{on}: the drop is taken"); + }; + let stripes = tile_kind(&app, "Stripes"); + drop(&mut app, PanelDrag::Art(vec![star]), "Dots", Modifiers::ALT, Modifiers::NONE, "Dots", 0.0); + assert_eq!(tile_kind(&app, "Dots"), star_kind, "Alt let go after the release: {}", app.ui.status); + assert_eq!(count(&mut app), Some(2), "no new pattern"); + app.run("edit.undo", json!({})).unwrap(); + drop(&mut app, PanelDrag::Art(vec![star]), "Dots", Modifiers::ALT, Modifiers::ALT, "Stripes", 1.0); + assert_eq!(tile_kind(&app, "Dots"), star_kind, "the pointer moved on to Stripes after the release"); + assert_eq!(tile_kind(&app, "Stripes"), stripes, "Stripes keeps its tile art"); + app.run("edit.undo", json!({})).unwrap(); + let dots = tile_kind(&app, "Dots"); + drop(&mut app, PanelDrag::Art(vec![star]), "Dots", Modifiers::NONE, Modifiers::ALT, "Dots", 2.0); + assert_eq!(count(&mut app), Some(3), "Alt pressed after a plain release makes a pattern"); + assert_eq!(tile_kind(&app, "Dots"), dots, "Dots keeps its tile art"); + let rgb = Color::from_hex("#2a6fb0").unwrap(); + drop(&mut app, PanelDrag::paint(Paint::solid(rgb)), "Red", Modifiers::ALT, Modifiers::NONE, "Red", 3.0); + assert_eq!(app.session.doc().unwrap().doc.swatch("Red").map(|w| w.paint.color()), Some(Some(rgb)), "Alt let go after the release on Red"); +} + #[test] fn a_proxy_dropped_on_the_panel_becomes_a_swatch() { let mut app = app(); @@ -1652,6 +1738,15 @@ fn click_menu_item(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { menu_frame(app, ctx, vec![button(false)]); } +/// Whether the panel menu's item `label` is enabled, as the accessibility tree reports it. +fn menu_item_enabled(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) -> bool { + ctx.enable_accesskit(); + let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(236.0, 700.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| menu(app, ui)); + out.textures_delta.clear(); + footer_button(&out, label).1 +} + /// The panel menu's Color Group Options… opens on the selected color group when that group is the /// whole selection; with nothing selected, a swatch alone, or a swatch or a second group beside the /// group, it opens nothing. After OK, and after `swatch.renameGroup` run on its own or in a batch, @@ -1930,3 +2025,44 @@ fn the_list_fills_a_tall_panel_above_its_footer() { let loose = list(None); assert!(loose.height() <= 150.5, "unsized, the list keeps its height: {loose:?}"); } + +/// The panel menu's Add Selected Colors adds only the selected art's new colors, as global swatches +/// the art links to, in one undo step; with nothing selected it is off. +#[test] +fn add_selected_colors_adds_the_selection_colors_as_global_swatches() { + let mut app = app(); + let rect = |app: &mut VectorcraftApp, color: &str| { + let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [id], "color": color})).unwrap(); + app.run("paint.setStroke", json!({"ids": [id], "none": true})).unwrap(); + id + }; + let picked = rect(&mut app, "#abcdef"); + rect(&mut app, "#fedcba"); + let ctx = context(); + let undo = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + app.run("select.set", json!({"ids": []})).unwrap(); + let (before, steps) = (app.session.active().unwrap().doc.clone(), undo(&app)); + assert!(!menu_item_enabled(&mut app, &ctx, "Add Selected Colors"), "off with nothing selected"); + click_menu_item(&mut app, &ctx, "Add Selected Colors"); + assert_eq!(app.session.active().unwrap().doc, before, "off with nothing selected"); + assert_eq!(undo(&app), steps); + app.run("select.set", json!({"ids": [picked]})).unwrap(); + assert!(menu_item_enabled(&mut app, &ctx, "Add Selected Colors"), "on with art selected"); + let (before, steps) = (app.session.active().unwrap().doc.clone(), undo(&app)); + click_menu_item(&mut app, &ctx, "Add Selected Colors"); + let doc = &app.session.active().unwrap().doc; + let swatch = doc.swatch("R=171 G=205 B=239").expect("the selected art's color is a swatch"); + assert!(swatch.global); + assert!(doc.swatch("R=254 G=220 B=186").is_none(), "unselected art adds nothing"); + let fill = doc.node(vectorcraft_doc::NodeId(picked.as_u64().unwrap())).unwrap().appearance.fill_paint(); + assert!(matches!(fill, Paint::Solid { swatch: Some(ref n), .. } if n == "R=171 G=205 B=239"), "{fill:?}"); + assert_eq!(undo(&app), steps + 1); + // Run again, the color is in the panel already: nothing is added and no undo step is recorded. + let after = app.session.active().unwrap().doc.clone(); + click_menu_item(&mut app, &ctx, "Add Selected Colors"); + assert_eq!(app.session.active().unwrap().doc, after); + assert_eq!(undo(&app), steps + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc, before); +} diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index ba924ea184..e351e1a385 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -474,7 +474,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); let zone = ui.interact(list_rect, ui.scope_id().with("symbols-drop"), Sense::hover()); if !over_symbol && let Some(ids) = widgets::art_drop(ui, &zone) { - // Shift held at the release keeps the dropped art as ordinary art. + // Shift held at the release that ends the drag keeps the dropped art as ordinary art. let mut p = json!({ "ids": ids, "type": "dynamic" }); if modifiers_at_release(ui).shift { p["keepArt"] = json!(true); @@ -529,8 +529,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } else if new.clicked() { // Alt skips Symbol Options: the symbol is made under the default name, dynamic as the // dialog's default. Shift keeps the selected art as ordinary art, with or without Alt. - // Both are read as the primary button went up, when it did in this frame. - let m = modifiers_at_release(ui); + // Both are read as the button went up on it. + let m = modifiers_released_in(ui, new.interact_rect, new.clicked_by(egui::PointerButton::Primary)); let (cmd, mut p) = if m.alt { ("symbol.new", json!({"type": "dynamic"})) } else { ("ui.symbolOptions", json!({})) }; if m.shift { p["keepArt"] = json!(true); @@ -545,7 +545,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let picked = if marked.contains(&name) { &marked[..] } else { &[] }; delete(app, picked, Some(&name), alt_at_release(ui)); } else if trash.clicked() { - delete(app, &marked, sel.as_deref(), alt_at_release(ui)); + let pointer = trash.clicked_by(egui::PointerButton::Primary); + delete(app, &marked, sel.as_deref(), modifiers_released_in(ui, trash.interact_rect, pointer).alt); } }); } @@ -558,18 +559,21 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let has_sel = app.session.active().is_some_and(|d| !d.selection.is_empty()); let inst = has_instances_selected(app); let name = json!({"name": sel}); - // Shift keeps the selected art as ordinary art instead of making it an instance. It is read as - // the primary button went up, when it did in this frame. - let shift = modifiers_at_release(ui).shift; - let redefine = if shift { json!({"name": sel, "keepArt": true}) } else { name.clone() }; - let new = if shift { json!({"keepArt": true}) } else { json!({}) }; - let items: [(&str, bool, &str, Value); 3] = [ - (tl!("New Symbol…"), has_sel, "ui.symbolOptions", new), - (tl!("Redefine Symbol"), has_sel && sel.is_some(), "symbol.update", redefine), - (tl!("Duplicate Symbol"), sel.is_some(), "symbol.duplicate", name.clone()), + // Shift, held as the button went up on New Symbol… or Redefine Symbol, keeps the selected art + // as ordinary art instead of making it an instance. + let items: [(&str, bool, &str, Value, bool); 3] = [ + (tl!("New Symbol…"), has_sel, "ui.symbolOptions", json!({}), true), + (tl!("Redefine Symbol"), has_sel && sel.is_some(), "symbol.update", name.clone(), true), + (tl!("Duplicate Symbol"), sel.is_some(), "symbol.duplicate", name.clone(), false), ]; - for (label, enabled, cmd, params) in items { - if menu_item(ui, label, enabled, false) { + for (label, enabled, cmd, mut params, keeps_art) in items { + let top = ui.cursor().min.y; + let item = widgets::menu_item_response(ui, label, enabled, false); + if item.clicked() { + let row = egui::Rect::from_x_y_ranges(ui.max_rect().x_range(), top..=ui.cursor().min.y); + if keeps_art && modifiers_released_in(ui, row, item.clicked_by(egui::PointerButton::Primary)).shift { + params["keepArt"] = json!(true); + } app.run(cmd, params).ok(); } } @@ -668,14 +672,71 @@ fn art_redefine_drop(ui: &Ui, item: &egui::Response, doc: &Document, uid: Option item.dnd_release_payload::().map(|_| ids.iter().map(|id| id.0).collect()) } -/// Whether Alt (Option) is held for a drop or a click: when the primary button went up in this frame, as it -/// went up, else now. +/// Whether Alt (Option) is held for a drop: as [`modifiers_at_release`] gives it. fn alt_at_release(ui: &Ui) -> bool { modifiers_at_release(ui).alt } -/// The modifiers held for a drop or a click: when the primary button went up in this frame, as it went up, -/// else now. +/// The modifiers held for a click on the widget whose interact rectangle is `rect`: when the +/// primary button last went up in this frame as a click (the pointer stayed within egui's click +/// distance of where the button went down) after going down over `rect` or within egui's interact +/// radius of it (egui gives a press that close to the widget), as it went up (egui reports the +/// click of the last such release in the frame); else, when no such click happened in this frame, +/// as the first release of the frame went up, which ends a press of an earlier frame that egui +/// counted as the click; else now. A release that ends a drag is not a click and is skipped. +/// `pointer` is whether egui reports the widget clicked by the primary button; when it is false, +/// the click came from the keyboard or a screen reader and the modifiers held now are used. +fn modifiers_released_in(ui: &Ui, rect: egui::Rect, pointer: bool) -> egui::Modifiers { + if !pointer { + return ui.input(|i| i.modifiers); + } + let radius = ui.ctx().global_style().interaction.interact_radius; + let max_click_dist = ui.ctx().options(|o| o.input_options.max_click_dist); + ui.input(|i| { + // Where the button went down in this frame, and whether the pointer has since moved too far + // for a click. + let mut origin: Option = None; + let mut moved = false; + // Whether a button went down earlier in this frame; until one does, a release ends a press + // of an earlier frame. + let mut pressed_here = false; + // The modifiers of the release that ends a press of an earlier frame. + let mut early = None; + let mut found = None; + for e in &i.events { + match e { + egui::Event::PointerMoved(pos) => { + moved |= origin.is_some_and(|o| o.distance(*pos) > max_click_dist); + } + egui::Event::PointerButton { pos, pressed: true, .. } => { + origin = Some(*pos); + moved = false; + pressed_here = true; + } + egui::Event::PointerButton { pos, button, pressed: false, modifiers } => { + moved |= origin.is_some_and(|o| o.distance(*pos) > max_click_dist); + let over = origin.is_some_and(|o| rect.distance_sq_to_pos(o) <= radius * radius); + if *button == egui::PointerButton::Primary { + if !pressed_here { + early = early.or(Some(*modifiers)); + } else if !moved && over { + found = Some(*modifiers); + } + } + origin = None; + moved = false; + } + _ => {} + } + } + // egui tracks a press of an earlier frame. A widget it reports clicked by the pointer, with + // no click on it after a press of this frame, was clicked by the early release. + found.or(early).unwrap_or(i.modifiers) + }) +} + +/// The modifiers held for a drop: when the primary button went up in this frame, as it first went +/// up, which is the release that ends a drag under way when the frame starts; else now. fn modifiers_at_release(ui: &Ui) -> egui::Modifiers { ui.input(|i| { i.events @@ -1110,6 +1171,21 @@ mod tests { assert_eq!(art(&app, "New Symbol 2"), (1, 0), "without Shift the rectangle becomes an instance"); } + /// A Shift-click on New Symbol… in the panel menu that goes down in one frame and up in the next + /// keeps the art as ordinary art, though a plain click elsewhere follows in the same frame. + #[test] + fn a_shift_click_on_new_symbol_in_the_menu_counts_though_a_click_elsewhere_follows() { + let (mut app, _) = leaf_dot_and_rect(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let off = pos2(-10.0, -10.0); + let after = vec![egui::Event::PointerMoved(off), button(off, true), button(off, false), egui::Event::ModifiersChanged(egui::Modifiers::NONE)]; + click_menu_held_then(&ctx, &mut app, "New Symbol…", egui::Modifiers::SHIFT, after); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_options::KIND)); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(art(&app, "New Symbol"), (0, 1), "the rectangle stays ordinary art"); + } + /// Clicks the panel's New Symbol button with `modifiers` held. fn click_new(app: &mut VectorcraftApp, modifiers: egui::Modifiers) { click_button_then(app, "New Symbol", modifiers, vec![]); @@ -1267,6 +1343,181 @@ mod tests { assert_eq!(art(&app, "New Symbol 2"), (1, 0), "without Shift the rectangle becomes an instance"); } + /// A drop on the panel reads Shift from the release that ends the drag: a click on the list + /// without Shift later in the same frame keeps a Shift drop's art as ordinary art, and a click + /// with Shift does not keep a plain drop's art. + #[test] + fn a_drop_on_the_panel_reads_shift_from_the_release_that_ends_the_drag() { + let (mut app, rect) = leaf_dot_and_rect(); + let ctx = egui::Context::default(); + let at = pos2(180.0, 60.0); + let release = |modifiers| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers }; + let press = |modifiers| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers }; + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![rect]); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::SHIFT); + let plain = egui::Modifiers::NONE; + let events = vec![release(egui::Modifiers::SHIFT), egui::Event::ModifiersChanged(plain), press(plain), release(plain)]; + frame_held(&ctx, &mut app, events, egui::Modifiers::SHIFT); + assert_eq!(art(&app, "New Symbol"), (0, 1), "the Shift drop keeps the rectangle as ordinary art"); + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![rect]); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], plain); + let shift = egui::Modifiers::SHIFT; + let events = vec![release(plain), egui::Event::ModifiersChanged(shift), press(shift), release(shift)]; + frame_held(&ctx, &mut app, events, plain); + assert_eq!(art(&app, "New Symbol 2"), (1, 0), "the plain drop makes the rectangle an instance"); + } + + /// A click of the primary button off the panel with no modifiers held, the pointer then back + /// at `at`. + fn stray_click(at: Pos2) -> [egui::Event; 4] { + let off = pos2(-10.0, -10.0); + let button = + |pressed| egui::Event::PointerButton { pos: off, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + [egui::Event::PointerMoved(off), button(true), button(false), egui::Event::PointerMoved(at)] + } + + /// Clicks the panel button labeled `label` with `modifiers` held as the primary button goes up, + /// between two clicks off the panel without them, and lets them go later in the same frame. + fn click_button_let_go(app: &mut VectorcraftApp, label: &str, modifiers: egui::Modifiers) { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let out = frame_held(&ctx, app, vec![], modifiers); + let at = clickable(&out).into_iter().find(|(l, _)| l == label).unwrap_or_else(|| panic!("a {label} button")).1; + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; + let let_go = egui::Event::ModifiersChanged(egui::Modifiers::NONE); + let mut events = stray_click(at).to_vec(); + events.extend([press(true), press(false), let_go]); + events.extend(stray_click(at)); + frame_held(&ctx, app, events, modifiers); + } + + /// Clicks the menu item labeled `label` with `modifiers` held as the primary button goes up, + /// between two clicks off the menu without them, and lets them go later in the same frame. + fn click_menu_let_go(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str, modifiers: egui::Modifiers) { + let held = egui::Event::ModifiersChanged(modifiers); + let labels = menu_frame(ctx, app, vec![held.clone()]); + let item = labels.iter().find(|(t, _)| t.trim() == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("{label} in the menu")); + let press = |pressed| egui::Event::PointerButton { pos: item, button: egui::PointerButton::Primary, pressed, modifiers }; + let mut events = vec![held]; + events.extend(stray_click(item)); + events.extend([press(true), press(false), egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + events.extend(stray_click(item)); + menu_frame(ctx, app, events); + } + + /// The New Symbol and Delete Symbol buttons and the menu's New Symbol… and Redefine Symbol read + /// Shift and Alt as the primary button goes up on them, though clicks elsewhere without them + /// come before and after and they are let go later in the same frame. + #[test] + fn symbol_clicks_read_the_modifiers_as_the_button_goes_up() { + let (mut app, rect) = leaf_dot_and_rect(); + click_button_let_go(&mut app, "New Symbol", egui::Modifiers::SHIFT | egui::Modifiers::ALT); + assert_eq!(dialog_kind(&app), None, "Alt skips Symbol Options"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot", "New Symbol"]); + assert_eq!(art(&app, "New Symbol"), (0, 1), "Shift: the rectangle stays ordinary art"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + click_menu_let_go(&ctx, &mut app, "New Symbol…", egui::Modifiers::SHIFT); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(art(&app, "New Symbol 2"), (0, 1), "the menu's Shift keeps the rectangle as ordinary art"); + app.run("symbol.setCurrent", json!({"name": "Dot"})).unwrap(); + click_menu_let_go(&ctx, &mut app, "Redefine Symbol", egui::Modifiers::SHIFT); + assert_eq!(art(&app, "Dot"), (0, 1), "Redefine Symbol with Shift keeps the rectangle as ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect]); + // Dot holds the rectangle now and nothing places it, so Alt deletes it without asking. + click_button_let_go(&mut app, "Delete Symbol", egui::Modifiers::ALT); + assert_eq!(dialog_kind(&app), None, "Alt deletes an unused symbol without asking"); + assert_eq!(symbols(&mut app), ["Leaf", "New Symbol", "New Symbol 2"]); + } + + /// A click just outside New Symbol, which egui still counts as a click on it, reads Shift and + /// Alt as the primary button goes up there, though they are let go later in the same frame. + #[test] + fn a_click_just_outside_new_symbol_reads_the_modifiers_as_the_button_goes_up() { + let (mut app, _) = leaf_dot_and_rect(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let modifiers = egui::Modifiers::SHIFT | egui::Modifiers::ALT; + let out = frame_held(&ctx, &mut app, vec![], modifiers); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let b = nodes + .iter() + .find(|(_, n)| n.label().is_some_and(|l| l.trim() == "New Symbol")) + .and_then(|(_, n)| n.bounds()) + .expect("a New Symbol button"); + let at = pos2(b.x0 as f32 - 2.0, ((b.y0 + b.y1) / 2.0) as f32); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; + let events = vec![egui::Event::PointerMoved(at), press(true), press(false), egui::Event::ModifiersChanged(egui::Modifiers::NONE)]; + frame_held(&ctx, &mut app, events, modifiers); + assert_eq!(dialog_kind(&app), None, "Alt skips Symbol Options"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot", "New Symbol"]); + assert_eq!(art(&app, "New Symbol"), (0, 1), "Shift: the rectangle stays ordinary art"); + } + + /// A click that goes down on the edge of New Symbol and, in the next frame, up past egui's + /// interact radius but within its click distance counts as a click on it and reads Shift and Alt + /// as the button goes up, though they are let go later in the same frame. + #[test] + fn a_click_released_past_the_interact_radius_reads_the_modifiers_as_the_button_goes_up() { + let (mut app, _) = leaf_dot_and_rect(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let modifiers = egui::Modifiers::SHIFT | egui::Modifiers::ALT; + let out = frame_held(&ctx, &mut app, vec![], modifiers); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let b = nodes + .iter() + .find(|(_, n)| n.label().is_some_and(|l| l.trim() == "New Symbol")) + .and_then(|(_, n)| n.bounds()) + .expect("a New Symbol button"); + let y = ((b.y0 + b.y1) / 2.0) as f32; + let (down, up) = (pos2(b.x0 as f32 + 0.5, y), pos2(b.x0 as f32 - 5.4, y)); + let radius = ctx.global_style().interaction.interact_radius; + let max_click_dist = ctx.options(|o| o.input_options.max_click_dist); + assert!(down.distance(up) <= max_click_dist && b.x0 as f32 - up.x > radius, "the release is a click outside the radius"); + let button = |at, pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(down), button(down, true)], modifiers); + let events = vec![egui::Event::PointerMoved(up), button(up, false), egui::Event::ModifiersChanged(egui::Modifiers::NONE)]; + frame_held(&ctx, &mut app, events, modifiers); + assert_eq!(dialog_kind(&app), None, "Alt skips Symbol Options"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot", "New Symbol"]); + assert_eq!(art(&app, "New Symbol"), (0, 1), "Shift: the rectangle stays ordinary art"); + } + + /// An Alt-click on Delete Symbol followed in the same frame by a drag that ends just outside + /// it without Alt reads Alt from the click: the release that ends the drag is not a click. + #[test] + fn a_drag_ending_near_delete_symbol_after_an_alt_click_keeps_the_click_modifiers() { + let mut app = leaf_and_dot(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let out = frame_held(&ctx, &mut app, vec![], egui::Modifiers::NONE); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let b = nodes + .iter() + .find(|(_, n)| n.label().is_some_and(|l| l.trim() == "Delete Symbol")) + .and_then(|(_, n)| n.bounds()) + .expect("a Delete Symbol button"); + let center = pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32); + let near = pos2(b.x0 as f32 - 1.0, center.y); + let from = pos2(near.x, near.y - 12.0); + let button = |pos, pressed, modifiers| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers }; + let (alt, none) = (egui::Modifiers::ALT, egui::Modifiers::NONE); + let events = vec![ + egui::Event::PointerMoved(center), + button(center, true, alt), + button(center, false, alt), + egui::Event::ModifiersChanged(none), + egui::Event::PointerMoved(from), + button(from, true, none), + egui::Event::PointerMoved(near), + button(near, false, none), + ]; + frame_held(&ctx, &mut app, events, alt); + assert_eq!(dialog_kind(&app), None, "Alt deletes the unused symbol without asking"); + assert_eq!(symbols(&mut app), ["Leaf"]); + } + /// `ui.symbolOptions` takes `keepArt` only as true or false, and only for a new symbol. #[test] fn symbol_options_checks_keep_art() { @@ -2962,6 +3213,111 @@ mod tests { assert!(Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "Leaf is unchanged"); } + /// A plain art drop on a symbol followed in the same frame by an Alt-click on that symbol makes + /// a new symbol and leaves the symbol as it was: the release that ends the drag decides. + #[test] + fn an_alt_click_after_a_plain_art_drop_in_the_same_frame_does_not_redefine() { + let mut app = leaf_and_dot(); + let shape = app.run("shape.rectangle", json!({"x": 200, "y": 120, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let leaf = symbol_art(&app, "Leaf"); + let ctx = egui::Context::default(); + let at = item_at(&ctx, &mut app, "Leaf"); + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![NodeId(shape)]); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::NONE); + let alt_press = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::ALT }; + let events = vec![button(at, false), egui::Event::ModifiersChanged(egui::Modifiers::ALT), alt_press, alt_release(at)]; + frame_held(&ctx, &mut app, events, egui::Modifiers::NONE); + assert_eq!(symbols(&mut app).len(), 3, "a new symbol"); + assert!(Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "Leaf is unchanged"); + } + + /// A plain drop of an unused symbol on Delete Symbol followed in the same frame by an Alt-click + /// on the button still asks first: the release that ends the drag decides. + #[test] + fn an_alt_click_after_a_plain_drop_on_delete_in_the_same_frame_still_asks() { + let mut app = leaf_and_dot(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let trash = button_rect(&ctx, &mut app, "Delete Symbol").center(); + let dot = item_at(&ctx, &mut app, "Dot"); + frame(&ctx, &mut app, vec![]); + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(dot), button(dot, true)]); + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(dot + vec2(40.0, 40.0))]); + frame(&ctx, &mut app, vec![egui::Event::PointerMoved(dot + vec2(80.0, 80.0))]); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(trash)], egui::Modifiers::NONE); + let alt_press = + egui::Event::PointerButton { pos: trash, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::ALT }; + let events = vec![button(trash, false), egui::Event::ModifiersChanged(egui::Modifiers::ALT), alt_press, alt_release(trash)]; + frame_held(&ctx, &mut app, events, egui::Modifiers::NONE); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::KIND), "the plain drop asks first"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"]); + } + + /// A screen reader's Click on Delete Symbol asks first for an unused symbol, though an Alt-click + /// elsewhere comes before it in the same frame and Alt is let go after. + #[test] + fn a_screen_reader_click_on_delete_does_not_take_alt_from_another_click() { + use egui::accesskit::{Action, ActionRequest, TreeId}; + let mut app = leaf_and_dot(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let out = frame_held(&ctx, &mut app, vec![], egui::Modifiers::NONE); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let node = + nodes.iter().find(|(_, n)| n.label().is_some_and(|l| l.trim() == "Delete Symbol")).map(|(id, _)| *id).expect("a Delete Symbol node"); + let off = pos2(-10.0, -10.0); + let alt = |pressed| egui::Event::PointerButton { pos: off, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::ALT }; + let click = + egui::Event::AccessKitActionRequest(ActionRequest { action: Action::Click, target_node: node, target_tree: TreeId::ROOT, data: None }); + let events = vec![egui::Event::PointerMoved(off), alt(true), alt(false), egui::Event::ModifiersChanged(egui::Modifiers::NONE), click]; + frame_held(&ctx, &mut app, events, egui::Modifiers::ALT); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::KIND), "the screen reader's Click asks first"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"]); + } + + /// A screen reader's Click on Delete Symbol asks first for an unused symbol, though in the same + /// frame an Alt release over the button ends a drag that began in an earlier frame and Alt is + /// let go after. + #[test] + fn a_screen_reader_click_on_delete_does_not_take_alt_from_a_drag_begun_earlier() { + use egui::accesskit::{Action, ActionRequest, TreeId}; + let mut app = leaf_and_dot(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let out = frame_held(&ctx, &mut app, vec![], egui::Modifiers::NONE); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let node = + nodes.iter().find(|(_, n)| n.label().is_some_and(|l| l.trim() == "Delete Symbol")).map(|(id, _)| *id).expect("a Delete Symbol node"); + let trash = clickable(&out).into_iter().find(|(l, _)| l == "Delete Symbol").expect("a Delete Symbol button").1; + let off = pos2(-10.0, -10.0); + let press = egui::Event::PointerButton { pos: off, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::ALT }; + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(off), press], egui::Modifiers::ALT); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(trash - vec2(0.0, 80.0))], egui::Modifiers::ALT); + let click = + egui::Event::AccessKitActionRequest(ActionRequest { action: Action::Click, target_node: node, target_tree: TreeId::ROOT, data: None }); + let events = vec![egui::Event::PointerMoved(trash), alt_release(trash), egui::Event::ModifiersChanged(egui::Modifiers::NONE), click]; + frame_held(&ctx, &mut app, events, egui::Modifiers::ALT); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_delete::KIND), "the screen reader's Click asks first"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"]); + } + + /// A click on Delete Symbol that goes down in one frame and up with Alt held in the next deletes + /// an unused symbol without asking, though a plain click elsewhere follows in the same frame. + #[test] + fn an_alt_click_on_delete_across_frames_counts_though_a_click_elsewhere_follows() { + let mut app = leaf_and_dot(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let out = frame_held(&ctx, &mut app, vec![], egui::Modifiers::NONE); + let trash = clickable(&out).into_iter().find(|(l, _)| l == "Delete Symbol").expect("a Delete Symbol button").1; + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(trash), button(trash, true)], egui::Modifiers::ALT); + let off = pos2(-10.0, -10.0); + let events = vec![alt_release(trash), egui::Event::PointerMoved(off), button(off, true), button(off, false)]; + frame_held(&ctx, &mut app, events, egui::Modifiers::ALT); + assert_eq!(dialog_kind(&app), None, "Alt deletes an unused symbol without asking"); + assert_eq!(symbols(&mut app), ["Leaf"]); + } + /// An Alt drop that cannot redefine the symbol under the pointer changes nothing, makes no new /// symbol and adds no undo step: art of another document, objects the document no longer has, /// no objects, and a release away from the panel are not outlined, and art holding an instance diff --git a/crates/ui-egui/src/panels/tests_brush_libraries.rs b/crates/ui-egui/src/panels/tests_brush_libraries.rs index e1605c0c0e..8f19ba6926 100644 --- a/crates/ui-egui/src/panels/tests_brush_libraries.rs +++ b/crates/ui-egui/src/panels/tests_brush_libraries.rs @@ -197,6 +197,7 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { json!("calligraphic-nibs"), json!("pressure-sensitive"), json!("bristle-brushes"), + json!("paint"), json!("pattern-borders"), json!("scatter-shapes"), json!("stipple"), @@ -204,8 +205,10 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { json!("energy-beams"), json!("dry-media"), json!("tech-circuit"), + json!("engraving"), json!("arrows"), - json!("image-brush") + json!("image-brush"), + json!("artistic") ] ); let dry = entries.iter().find(|e| under(e) && e.params["library"] == "dry-media").map(|e| e.label.as_str()); @@ -236,21 +239,42 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { click(&mut app, &ctx, "Circuit Trace", Modifiers::NONE, 2.0); assert!(has(&app, "Circuit Trace") && !has(&app, "Bus Lines")); assert_eq!(undo_len(&app), undo + 1); + let r = app.run("window.brushLibrary", json!({"library": "Artistic Brushes"})).unwrap(); + assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("artistic"), Some(4))); + let previous = crate::i18n::current(); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").unwrap()); + assert_eq!(crate::menus::display_label(&app, "window.brushLibrary", "Artistic Brushes"), "Künstlerische Pinsel"); + crate::i18n::set_current(previous); + let undo = undo_len(&app); + click(&mut app, &ctx, "Orbit Lines", Modifiers::NONE, 3.0); + assert!(has(&app, "Orbit Lines") && !has(&app, "Facet Sweep")); + assert_eq!(undo_len(&app), undo + 1); let r = app.run("window.brushLibrary", json!({"library": "Pressure Sensitive"})).unwrap(); assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("pressure-sensitive"), 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, "Flex Ribbon", Modifiers::NONE, 3.0); + click(&mut app, &ctx, "Flex Ribbon", Modifiers::NONE, 4.0); assert!(has(&app, "Flex Ribbon") && !has(&app, "Pulse Stroke")); 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("Flex Ribbon") ); + let r = app.run("window.brushLibrary", json!({"library": "Paint"})).unwrap(); + assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("paint"), Some(4))); + let path = app.run("shape.line", json!({"x1": 10, "y1": 140, "x2": 180, "y2": 140})).unwrap()["id"].as_u64().unwrap(); + let undo = undo_len(&app); + click(&mut app, &ctx, "Flat Sweep", Modifiers::NONE, 5.0); + assert!(has(&app, "Flat Sweep") && !has(&app, "Dry Drag")); + 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("Flat Sweep") + ); let r = app.run("window.brushLibrary", json!({"library": "Image Brush"})).unwrap(); assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("image-brush"), Some(4))); let undo = undo_len(&app); - click(&mut app, &ctx, "Soft Bloom", Modifiers::NONE, 4.0); + click(&mut app, &ctx, "Soft Bloom", Modifiers::NONE, 6.0); assert!(has(&app, "Soft Bloom") && !has(&app, "Color Flecks")); assert_eq!(undo_len(&app), undo + 1); // Without brushes there is nothing to save. diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index 798a842e4c..103e3f4823 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -11,7 +11,9 @@ use vectorcraft_color::cms::{self, Cms, ColorSettings, delta_e2000}; use vectorcraft_color::{Color, Paint}; use vectorcraft_engine::Session; -use super::color_wheel::{ID, display_hsb, remembered_hsb, show, stored}; +use super::color_wheel::{ + ID, Settings, Sliders, chroma_tick, display_hsb, oklch_rows, oklch_track, remembered_hsb, remembered_hsl, remembered_oklch, set, show, stored, +}; use crate::VectorcraftApp; /// An app with a selected rectangle filled with `fill`. @@ -581,3 +583,573 @@ fn the_color_pickers_field_takes_the_arrow_keys() { assert!(near(stepped, [after[0], after[1] + 0.01, after[2]], [1e-3, 1e-4, 1e-4]), "{after:?} → {stepped:?}"); assert!(h.state().ui.dialog.is_some(), "the dialog stays open"); } + +/// The panel with OKLCH Sliders shown, in a flyout tall enough for the rows. +fn oklch_harness(mut app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap(); + oklch_harness_shown(app) +} + +/// The panel in a flyout tall enough for the rows, with the app's settings as they are. +fn oklch_harness_shown(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + let mut h = Harness::builder().with_size(vec2(260.0, 420.0)).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + crate::shortcuts::handle(app, ui.ctx()); + }, + app, + ); + h.run_steps(2); + h +} + +/// The slider row named `name` (its number field has the same name). +fn oklch_slider<'a>(h: &'a Harness<'static, VectorcraftApp>, name: &'a str) -> egui_kittest::Node<'a> { + h.query_all_by_label(name).find(|n| n.accesskit_node().role() == egui::accesskit::Role::Slider).expect("a slider row") +} + +/// The point at `t` (0..1) along the bar of a slider row. +fn on_rail(rail: Rect, t: f32) -> Pos2 { + Pos2::new(rail.left() + 4.0 + t * (rail.width() - 8.0), rail.top() + 7.0) +} + +fn fill_oklch(app: &VectorcraftApp) -> [f64; 3] { + vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&fill(app))) +} + +/// `ui.colorWheel {sliders: "oklch"}` shows L, C and H rows with the fill's OKLCH, and the panel +/// keeps the setting with the preferences. +#[test] +fn oklch_sliders_show_the_fills_lightness_chroma_and_hue() { + let h = oklch_harness(app(json!("#ff0000"))); + assert_eq!(h.state().ui.color_wheel.sliders, Sliders::Oklch); + let value = |name: &str| oklch_slider(&h, name).accesskit_node().numeric_value().unwrap(); + assert_eq!((value("Lightness"), value("Chroma"), value("Hue")), (63.0, 64.0, 29.0)); + let saved = serde_json::to_value(&h.state().ui).unwrap(); + assert_eq!(saved["color_wheel"]["sliders"], json!("oklch")); +} + +/// A drag on L past the chroma sRGB holds stores the largest chroma that fits at the same hue, and +/// the C row keeps the chroma asked for, so dragging L back brings it back. +#[test] +fn a_drag_on_lightness_keeps_the_chroma_asked_for() { + let mut h = oklch_harness(app(json!("#0000ff"))); + let [l0, c0, h0] = fill_oklch(h.state()); + let rail = oklch_slider(&h, "Lightness").rect(); + drag(&mut h, &[on_rail(rail, l0 as f32), on_rail(rail, 0.9)], Modifiers::NONE); + let [l1, c1, h1] = fill_oklch(h.state()); + assert!((l1 - 0.9).abs() < 0.01 && c1 < c0 - 0.1 && (h1 - h0).abs() < 1.0, "{:?} → {:?}", [l0, c0, h0], [l1, c1, h1]); + let chroma = oklch_slider(&h, "Chroma").accesskit_node().numeric_value().unwrap(); + assert_eq!(chroma, (c0 / 0.4 * 100.0).round(), "the C row keeps the requested chroma"); + drag(&mut h, &[on_rail(rail, 0.9), on_rail(rail, l0 as f32)], Modifiers::NONE); + let [l2, c2, _] = fill_oklch(h.state()); + assert!((l2 - l0).abs() < 0.01 && (c2 - c0).abs() < 0.01, "{:?} → {:?}", [l0, c0], [l2, c2]); +} + +/// A press on a row gives it the keyboard focus, and → raises it by one unit as one undo step. +/// Each row reports its range and the adjust actions to screen readers. +#[test] +fn the_oklch_rows_take_the_arrow_keys_and_screen_readers_actions() { + let mut h = oklch_harness(app(json!("#808080"))); + for (name, max) in [("Lightness", 100.0), ("Chroma", 100.0), ("Hue", 360.0)] { + let node = oklch_slider(&h, name).accesskit_node(); + assert_eq!((node.min_numeric_value(), node.max_numeric_value(), node.numeric_value_step()), (Some(0.0), Some(max), Some(1.0)), "{name}"); + assert!([Action::Increment, Action::Decrement, Action::SetValue].iter().all(|a| node.data().supports_action(*a)), "{name}"); + } + let rail = oklch_slider(&h, "Lightness").rect(); + let l = fill_oklch(h.state())[0]; + click(&mut h, on_rail(rail, l as f32), Modifiers::NONE); + let before = fill_oklch(h.state())[0]; + let undo = undo_len(h.state()); + key(&mut h, egui::Key::ArrowRight, Modifiers::NONE); + let after = fill_oklch(h.state())[0]; + assert!((after - ((before * 100.0).round() + 1.0) / 100.0).abs() < 0.003, "{before} → {after}"); + assert_eq!(undo_len(h.state()), undo + 1, "one undo step"); + let (gray, undo) = (fill(h.state()), undo_len(h.state())); + let (target_node, target_tree) = oklch_slider(&h, "Hue").accesskit_node().locate(); + let data = Some(ActionData::NumericValue(200.0)); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data })); + // The frame that takes the request draws the row before it applies it. + h.run_steps(2); + assert_eq!(oklch_slider(&h, "Hue").accesskit_node().numeric_value(), Some(200.0), "a gray keeps the hue it was given"); + assert_eq!((fill(h.state()), undo_len(h.state())), (gray, undo), "a hue on a gray changes nothing and records no undo step"); +} + +/// Each track dims the colors outside sRGB, and the C track's tick sits at the largest chroma sRGB +/// holds, along the track's 0 to 0.4. +#[test] +fn the_oklch_tracks_dim_the_colors_outside_srgb_and_the_tick_marks_the_largest_chroma() { + let (l, h) = (0.7, 150.0); + let max = vectorcraft_color::oklab::max_chroma(l, h); + for max_chroma in [Some(max), None] { + assert_eq!(oklch_track([l, max * 0.5, h], max_chroma).a(), 255, "{max_chroma:?}: inside sRGB"); + assert!(oklch_track([l, 0.4, h], max_chroma).a() < 255, "{max_chroma:?}: outside sRGB is dimmed"); + } + // Near white, an L or H track shows the color a pick there stores: the largest chroma that fits, + // not each channel clamped on its own. + let (stored, lowered) = vectorcraft_color::oklab::from_oklch(0.98, 0.2, h); + let [r, g, b] = stored.map(|v| (f64::from(v).clamp(0.0, 1.0) * 255.0).round() as u8); + assert!(lowered); + assert_eq!(oklch_track([0.98, 0.2, h], None), egui::Color32::from_rgb(r, g, b).gamma_multiply(0.3)); + // At blue's L and H the ray leaves sRGB below the largest chroma and comes back at blue: the C + // track dims that gap and shows the color a pick there stores. + let [bl, _, bh] = vectorcraft_color::oklab::to_oklch([0.0, 0.0, 1.0]); + let blue_max = vectorcraft_color::oklab::max_chroma(bl, bh); + let (stored, lowered) = vectorcraft_color::oklab::from_oklch(bl, 0.29, bh); + let [r, g, b] = stored.map(|v| (f64::from(v).clamp(0.0, 1.0) * 255.0).round() as u8); + assert!(lowered && blue_max > 0.3); + assert_eq!(oklch_track([bl, 0.29, bh], Some(blue_max)), egui::Color32::from_rgb(r, g, b).gamma_multiply(0.3)); + assert_eq!(oklch_track([bl, blue_max, bh], Some(blue_max)).a(), 255, "blue itself is inside sRGB"); + assert!((chroma_tick(max) - (max / 0.4) as f32).abs() < 1e-6 && chroma_tick(max) > 0.1 && chroma_tick(max) < 1.0); + assert_eq!((chroma_tick(0.0), chroma_tick(0.5)), (0.0, 1.0)); +} + +/// After Edit › Color Settings picks a working RGB space other than sRGB, Panel menu › OKLCH Sliders +/// is gray and `ui.colorWheel {sliders: "oklch"}` answers an error; rows already shown are gray. +#[test] +fn oklch_sliders_are_gray_after_the_working_space_changes() { + const CHILD: &str = "VECTORCRAFT_TEST_COLOR_WHEEL_P3"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: change them in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "panels::tests_color_wheel::oklch_sliders_are_gray_after_the_working_space_changes", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated working space test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + let mut app = app(json!("#ff0000")); + app.run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + assert_eq!(app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap_err(), "OKLCH needs sRGB as the working RGB space"); + assert_eq!(app.ui.color_wheel.sliders, Sliders::None); + let mut fonts = false; + let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + super::color_wheel::menu(app, ui); + }, + app, + ); + h.run_steps(3); + assert!(h.get_by_label(" OKLCH Sliders").accesskit_node().is_disabled()); + // The color settings stay with the process, so a new app works in Display P3 as well. + let mut app = self::app(json!("#ff0000")); + app.ui.color_wheel.sliders = Sliders::Oklch; + let h = oklch_harness_shown(app); + assert!(oklch_slider(&h, "Lightness").accesskit_node().is_disabled()); +} + +/// A drag on an OKLCH row during which Edit › Color Settings picks a working RGB space other than +/// sRGB keeps the color the drag previewed as one undo step and leaves no interaction open, though +/// the gray rows report no release. +#[test] +fn a_working_space_change_during_an_oklch_drag_keeps_its_color_as_one_undo_step() { + const CHILD: &str = "VECTORCRAFT_TEST_COLOR_WHEEL_P3_DRAG"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: change them in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "panels::tests_color_wheel::a_working_space_change_during_an_oklch_drag_keeps_its_color_as_one_undo_step", + "--nocapture", + ]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated working space test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + let mut h = oklch_harness(app(json!("#ff8000"))); + let rail = oklch_slider(&h, "Lightness").rect(); + let undo = undo_len(h.state()); + press(&mut h, on_rail(rail, 0.5), true, Modifiers::NONE); + for _ in 0..2 { + h.event(Event::PointerMoved(on_rail(rail, 0.25))); + h.run_steps(1); + } + assert!(h.state().session.in_interaction(), "the drag previews"); + let previewed = fill(h.state()); + h.state_mut().run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + h.run_steps(2); + assert!(oklch_slider(&h, "Lightness").accesskit_node().is_disabled()); + press(&mut h, on_rail(rail, 0.25), false, Modifiers::NONE); + assert!(!h.state().session.in_interaction(), "the interaction ended"); + assert_eq!((fill(h.state()), undo_len(h.state())), (previewed, undo + 1)); +} + +/// A CMYK fill's L, C and H are those of its display color, not of its naive separation. +#[test] +fn a_cmyk_fills_oklch_is_that_of_its_display_color() { + let h = oklch_harness(app(json!({"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0}))); + let shown = vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&Color::cmyk(1.0, 0.0, 0.0, 0.0))); + let naive = vectorcraft_color::oklab::to_oklch([0.0, 1.0, 1.0]); + let lightness = oklch_slider(&h, "Lightness").accesskit_node().numeric_value().unwrap(); + assert_eq!(lightness, (shown[0] * 100.0).round()); + assert_ne!(lightness, (naive[0] * 100.0).round()); +} + +/// Panel menu › OKLCH Sliders shows the rows and, checked, hides them. +#[test] +fn the_panel_menu_shows_and_hides_the_oklch_rows() { + let mut fonts = false; + let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + // The fonts, which hold the check mark, take effect from the next frame. + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + super::color_wheel::menu(app, ui); + }, + app(json!("#ff0000")), + ); + h.run_steps(3); + h.get_by_label(" OKLCH Sliders").click(); + h.run_steps(2); + assert_eq!(h.state().ui.color_wheel.sliders, Sliders::Oklch); + h.get_by_label("✓ OKLCH Sliders").click(); + h.run_steps(2); + assert_eq!(h.state().ui.color_wheel.sliders, Sliders::None); +} + +/// In a working RGB space other than sRGB, `sliders: "oklch"` is an error and the rows are gray; +/// the error leaves the settings as they were. +#[test] +fn oklch_sliders_need_srgb_as_the_working_space() { + let p3 = Cms::new(&ColorSettings { rgb: cms::DISPLAY_P3.into(), ..ColorSettings::default() }).unwrap(); + let mut settings = Settings::default(); + assert_eq!(set(&mut settings, &json!({"sliders": "oklch"}), &p3).unwrap_err(), "OKLCH needs sRGB as the working RGB space"); + assert_eq!(settings.sliders, Sliders::None); + set(&mut settings, &json!({"sliders": "oklch"}), &Cms::default()).unwrap(); + assert_eq!(settings.sliders, Sliders::Oklch); + set(&mut settings, &json!({"sliders": "none"}), &p3).unwrap(); + assert_eq!(settings.sliders, Sliders::None, "the rows can be hidden in any working space"); + let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + let tgt = super::color::wheel_target(app, ui); + let color = tgt.color(); + let picked = oklch_rows(app, ui, &tgt, color, &p3); + assert!(picked.is_none(), "a gray row picks nothing: {picked:?}"); + }, + app(json!("#ff0000")), + ); + h.run_steps(2); + assert!(oklch_slider(&h, "Lightness").accesskit_node().is_disabled()); + let rail = oklch_slider(&h, "Lightness").rect(); + click(&mut h, on_rail(rail, 0.2), Modifiers::NONE); + key(&mut h, egui::Key::ArrowRight, Modifiers::NONE); + set_slider_value(&mut h, "Lightness", 20.0); +} + +/// The rows show what they asked for while the color displays as it did, and the color's own +/// OKLCH after the color settings change its display. +#[test] +fn the_remembered_oklch_follows_a_change_of_working_space() { + let srgb = Cms::default(); + let p3 = Cms::new(&ColorSettings { rgb: cms::DISPLAY_P3.into(), ..ColorSettings::default() }).unwrap(); + let c = Color::rgb(0.5, 0.3, 0.2); + let asked = [0.5, 0.3, 40.0]; + let shown = srgb.display_rgb(&c); + assert_eq!(remembered_oklch(&srgb, &c, shown, asked), asked); + assert_eq!(remembered_oklch(&p3, &c, shown, asked), vectorcraft_color::oklab::to_oklch(p3.display_rgb(&c))); +} + +/// The panel with HSL Sliders shown, in a flyout tall enough for the rows. `oklch_slider` and +/// `oklch_harness_shown` find and draw any slider row, the HSL rows included. +fn hsl_harness(mut app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + app.run("ui.colorWheel", json!({"sliders": "hsl"})).unwrap(); + oklch_harness_shown(app) +} + +fn fill_hsl(app: &VectorcraftApp) -> [f32; 3] { + vectorcraft_color::rgb_to_hsl(cms::active().display_rgb(&fill(app))) +} + +/// Sets the slider row named `name` to `v` as a screen reader does. +fn set_slider_value(h: &mut Harness<'static, VectorcraftApp>, name: &str, v: f64) { + let (target_node, target_tree) = oklch_slider(h, name).accesskit_node().locate(); + let data = Some(ActionData::NumericValue(v)); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data })); + // The frame that takes the request draws the row before it applies it. + h.run_steps(2); +} + +/// `ui.colorWheel {sliders: "hsl"}` shows H, S and L rows with the fill's HSL, CSS Color 4's +/// `hsl()` of its display sRGB, and the panel keeps the setting with the preferences. +#[test] +fn hsl_sliders_show_the_fills_hue_saturation_and_lightness() { + let h = hsl_harness(app(json!("#ff8000"))); + assert_eq!(h.state().ui.color_wheel.sliders, Sliders::Hsl); + let value = |name: &str| oklch_slider(&h, name).accesskit_node().numeric_value().unwrap(); + assert_eq!((value("HSL Hue"), value("HSL Saturation"), value("HSL Lightness")), (30.0, 100.0, 50.0)); + assert!(h.query_by_label("Chroma").is_none(), "OKLCH Sliders are hidden"); + let saved = serde_json::to_value(&h.state().ui).unwrap(); + assert_eq!(saved["color_wheel"]["sliders"], json!("hsl")); +} + +/// In Box View with the Saturation channel, screen readers tell the box strip's HSB saturation +/// from the S row's HSL saturation by their names. +#[test] +fn the_hsl_rows_names_differ_from_the_box_strips() { + let mut app = app(json!("#996633")); + app.run("ui.colorWheel", json!({"view": "box", "channel": "saturation"})).unwrap(); + let h = hsl_harness(app); + let sliders = |name: &str| h.query_all_by_label(name).filter(|n| n.accesskit_node().role() == egui::accesskit::Role::Slider).count(); + assert_eq!((sliders("Saturation"), sliders("HSL Saturation")), (1, 1)); + let strip = oklch_slider(&h, "Saturation").accesskit_node().numeric_value().unwrap(); + let row = oklch_slider(&h, "HSL Saturation").accesskit_node().numeric_value().unwrap(); + assert_ne!(strip, row, "HSB and HSL saturation differ for this color"); +} + +/// A drag on L changes the lightness and keeps the hue and the saturation. +#[test] +fn a_drag_on_hsl_lightness_keeps_the_hue_and_saturation() { + let mut h = hsl_harness(app(json!("#ff8000"))); + let rail = oklch_slider(&h, "HSL Lightness").rect(); + let undo = undo_len(h.state()); + drag(&mut h, &[on_rail(rail, 0.5), on_rail(rail, 0.25)], Modifiers::NONE); + assert!(near(fill_hsl(h.state()), [30.0, 1.0, 0.25], [1.0, 0.01, 0.01]), "{:?}", fill_hsl(h.state())); + assert_eq!(undo_len(h.state()), undo + 1, "a drag is one undo step"); +} + +/// A press on S gives it the keyboard focus, and → raises it by 1 % as one undo step. Each row +/// reports its range and the adjust actions to screen readers. +#[test] +fn the_hsl_rows_take_the_arrow_keys_and_screen_readers_actions() { + let mut h = hsl_harness(app(json!("#996633"))); + for (name, max) in [("HSL Hue", 360.0), ("HSL Saturation", 100.0), ("HSL Lightness", 100.0)] { + let node = oklch_slider(&h, name).accesskit_node(); + assert_eq!((node.min_numeric_value(), node.max_numeric_value(), node.numeric_value_step()), (Some(0.0), Some(max), Some(1.0)), "{name}"); + assert!([Action::Increment, Action::Decrement, Action::SetValue].iter().all(|a| node.data().supports_action(*a)), "{name}"); + } + let rail = oklch_slider(&h, "HSL Saturation").rect(); + let s = fill_hsl(h.state())[1]; + click(&mut h, on_rail(rail, s), Modifiers::NONE); + let before = fill_hsl(h.state()); + let undo = undo_len(h.state()); + key(&mut h, egui::Key::ArrowRight, Modifiers::NONE); + let after = fill_hsl(h.state()); + let raised = ((before[1] * 100.0).round() + 1.0) / 100.0; + assert!(near(after, [before[0], raised, before[2]], [1.0, 0.008, 0.003]), "{before:?} → {after:?}"); + assert_eq!(undo_len(h.state()), undo + 1, "one undo step"); +} + +/// A gray has no hue: a hue given to it stays on the H row while the color is unchanged, and a +/// saturation picked next uses that hue. +#[test] +fn a_gray_keeps_the_hsl_hue_it_was_given() { + let mut h = hsl_harness(app(json!("#808080"))); + let (gray, undo) = (fill(h.state()), undo_len(h.state())); + set_slider_value(&mut h, "HSL Hue", 200.0); + assert_eq!(oklch_slider(&h, "HSL Hue").accesskit_node().numeric_value(), Some(200.0), "a gray keeps the hue it was given"); + assert_eq!((fill(h.state()), undo_len(h.state())), (gray, undo), "a hue on a gray changes nothing and records no undo step"); + set_slider_value(&mut h, "HSL Saturation", 60.0); + let got = fill_hsl(h.state()); + assert!(near(got, [200.0, 0.6, 0.5], [1.0, 0.01, 0.01]), "{got:?}"); +} + +/// In a working RGB space wider than sRGB, an HSL pick goes from display sRGB into that space +/// through the color settings: the fill displays the HSL asked for, and its stored RGB numbers are +/// those of the working space, not the sRGB numbers of that HSL. +#[test] +fn an_hsl_pick_in_display_p3_goes_into_the_working_space() { + const CHILD: &str = "VECTORCRAFT_TEST_COLOR_WHEEL_HSL_P3"; + if std::env::var_os(CHILD).is_none() { + // Color settings are process-wide: change them in a separate test process. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "panels::tests_color_wheel::an_hsl_pick_in_display_p3_goes_into_the_working_space", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated working space test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + let mut app = app(json!("#996633")); + app.run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + let mut h = hsl_harness(app); + let [hue, sat, _] = fill_hsl(h.state()); + let undo = undo_len(h.state()); + set_slider_value(&mut h, "HSL Lightness", 60.0); + let asked = [hue, sat, 0.6]; + assert!(near(fill_hsl(h.state()), asked, [0.5, 0.005, 0.005]), "{asked:?} → {:?}", fill_hsl(h.state())); + assert_eq!(undo_len(h.state()), undo + 1, "one undo step"); + let Color::Rgb { r, g, b } = fill(h.state()) else { panic!("an RGB fill stays RGB") }; + let srgb = vectorcraft_color::hsl_to_rgb(asked); + assert!((0..3).any(|i| ([r, g, b][i] - srgb[i]).abs() > 0.01), "{:?} is stored as the sRGB numbers {srgb:?}", [r, g, b]); +} + +/// Panel menu › HSL Sliders shows the H, S and L rows in place of OKLCH Sliders and, checked, +/// hides them; it is offered in any working RGB space. +#[test] +fn the_panel_menu_shows_and_hides_the_hsl_rows() { + let mut fonts = false; + let mut app = app(json!("#ff0000")); + app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap(); + let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + // The fonts, which hold the check mark, take effect from the next frame. + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + super::color_wheel::menu(app, ui); + }, + app, + ); + h.run_steps(3); + h.get_by_label(" HSL Sliders").click(); + h.run_steps(2); + assert_eq!(h.state().ui.color_wheel.sliders, Sliders::Hsl); + assert!(h.query_by_label("✓ OKLCH Sliders").is_none(), "the two slider sets show one at a time"); + h.get_by_label("✓ HSL Sliders").click(); + h.run_steps(2); + assert_eq!(h.state().ui.color_wheel.sliders, Sliders::None); + let p3 = Cms::new(&ColorSettings { rgb: cms::DISPLAY_P3.into(), ..ColorSettings::default() }).unwrap(); + let mut settings = Settings::default(); + set(&mut settings, &json!({"sliders": "hsl"}), &p3).unwrap(); + assert_eq!(settings.sliders, Sliders::Hsl, "HSL needs no particular working space"); +} + +/// The rows show what they asked for while the color displays as it did, and the color's own HSL +/// after the color settings change its display. +#[test] +fn the_remembered_hsl_follows_a_change_of_working_space() { + let srgb = Cms::default(); + let p3 = Cms::new(&ColorSettings { rgb: cms::DISPLAY_P3.into(), ..ColorSettings::default() }).unwrap(); + let c = Color::rgb(0.5, 0.3, 0.2); + let asked = [20.0, 0.43, 0.35]; + let shown = srgb.display_rgb(&c); + assert_eq!(remembered_hsl(&srgb, &c, shown, asked), asked); + assert_eq!(remembered_hsl(&p3, &c, shown, asked), vectorcraft_color::rgb_to_hsl(p3.display_rgb(&c))); +} + +/// Saved settings are read key by key: a value this version does not know (one a newer version +/// wrote) gives the default, and the other preferences still load. +#[test] +fn saved_color_wheel_settings_are_read_leniently() { + let mut saved = serde_json::to_value(crate::UiState::default()).unwrap(); + saved["color_rgb_percent"] = json!(true); + for (value, sliders) in [ + (json!({"sliders": "oklch"}), Sliders::Oklch), + (json!({"sliders": "hsl"}), Sliders::Hsl), + (json!({"sliders": "hwb", "view": "box"}), Sliders::None), + (json!(5), Sliders::None), + ] { + saved["color_wheel"] = value.clone(); + let ui: crate::UiState = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!((ui.color_wheel.sliders, ui.color_rgb_percent), (sliders, true), "{value}"); + } +} + +/// `ui.colorWheel {sliders}` sets the rows and keeps the view and the channel, and an unknown +/// `sliders` value is an error that changes nothing. +#[test] +fn ui_color_wheel_sets_and_reads_the_sliders() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("ui.colorWheel", json!({"view": "box", "channel": "red"})).unwrap(); + 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", "harmony": false, "harmonyRule": "complementary", "vision": false, "sliders": "oklch"}); + 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"); + assert_eq!(app.ui.color_wheel.view, crate::panels::color_wheel::View::Box, "an error changes nothing"); +} + +/// A hue given to a Gray color does not change how it displays, so its paint stays a Gray color +/// and no undo step is recorded; the hue row keeps the hue. +#[test] +fn a_hue_on_a_gray_color_leaves_its_paint_gray() { + for (rows, hue) in [("hsl", "HSL Hue"), ("oklch", "Hue")] { + let mut app = app(json!({"gray": 0.5})); + app.run("ui.colorWheel", json!({"sliders": rows})).unwrap(); + let mut h = oklch_harness_shown(app); + let (gray, undo) = (fill(h.state()), undo_len(h.state())); + assert!(matches!(gray, Color::Gray { .. }), "{gray:?}"); + set_slider_value(&mut h, hue, 200.0); + assert_eq!(oklch_slider(&h, hue).accesskit_node().numeric_value(), Some(200.0), "{rows}"); + assert_eq!((fill(h.state()), undo_len(h.state())), (gray, undo), "{rows}: the Gray fill stays as it was"); + } +} + +/// For a fill outside sRGB, the HSL and OKLCH rows show the components of its display color +/// clipped to sRGB, the color the panel shows, not of the unclipped one. +#[test] +fn the_rows_show_a_color_outside_srgb_clipped_to_srgb() { + let rgb = json!([1.6, 0.2, -0.4]); + let raw = cms::active().display_rgb(&fill(&app(rgb.clone()))); + let clipped = raw.map(|v| v.clamp(0.0, 1.0)); + assert_ne!(raw, clipped, "the fill lies outside sRGB"); + let want_hsl = (f64::from(vectorcraft_color::rgb_to_hsl(clipped)[2]) * 100.0).round(); + assert_ne!(want_hsl, (f64::from(vectorcraft_color::rgb_to_hsl(raw)[2]) * 100.0).round(), "the unclipped lightness differs"); + let h = hsl_harness(app(rgb.clone())); + assert_eq!(oklch_slider(&h, "HSL Lightness").accesskit_node().numeric_value(), Some(want_hsl)); + let want_l = (vectorcraft_color::oklab::to_oklch(clipped)[0] * 100.0).round(); + assert_ne!(want_l, (vectorcraft_color::oklab::to_oklch(raw)[0] * 100.0).round(), "the unclipped OKLCH lightness differs"); + let h = oklch_harness(app(rgb)); + assert_eq!(oklch_slider(&h, "Lightness").accesskit_node().numeric_value(), Some(want_l)); +} + +/// The hue given to a gray is dropped once the panel shows another color, so the same gray applied +/// again later shows its own hue, 0°. +#[test] +fn a_remembered_hue_is_dropped_after_the_paint_changes() { + for (rows, hue) in [("hsl", "HSL Hue"), ("oklch", "Hue")] { + let mut app = app(json!("#808080")); + app.run("ui.colorWheel", json!({"sliders": rows})).unwrap(); + let mut h = oklch_harness_shown(app); + set_slider_value(&mut h, hue, 240.0); + assert_eq!(oklch_slider(&h, hue).accesskit_node().numeric_value(), Some(240.0), "{rows}"); + h.state_mut().run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + h.run_steps(2); + h.state_mut().run("paint.setFill", json!({"color": "#808080"})).unwrap(); + h.run_steps(2); + assert_eq!(oklch_slider(&h, hue).accesskit_node().numeric_value(), Some(0.0), "{rows}: the gray's own hue"); + } +} + +/// Hiding the rows, or showing the other rows, during a drag on a row keeps the color the drag +/// previewed as one undo step and leaves no interaction open. +#[test] +fn hiding_the_rows_during_a_drag_keeps_its_color_as_one_undo_step() { + for rows in ["none", "oklch"] { + let mut h = hsl_harness(app(json!("#ff8000"))); + let rail = oklch_slider(&h, "HSL Lightness").rect(); + let undo = undo_len(h.state()); + press(&mut h, on_rail(rail, 0.5), true, Modifiers::NONE); + for _ in 0..2 { + h.event(Event::PointerMoved(on_rail(rail, 0.25))); + h.run_steps(1); + } + assert!(h.state().session.in_interaction(), "{rows}: the drag previews"); + let previewed = fill(h.state()); + h.state_mut().run("ui.colorWheel", json!({"sliders": rows})).unwrap(); + h.run_steps(2); + press(&mut h, on_rail(rail, 0.25), false, Modifiers::NONE); + assert!(!h.state().session.in_interaction(), "{rows}: the interaction ended"); + assert_eq!((fill(h.state()), undo_len(h.state())), (previewed, undo + 1), "{rows}"); + } +} 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 3b55f52ac2..d0f35ee13c 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,7 @@ 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!({"harmony": false, "harmonyRule": "complementary", "vision": false}); + let harmony = json!({"sliders": "none", "harmony": false, "harmonyRule": "complementary", "vision": false}); let with = |v: serde_json::Value| { let mut v = v; v.as_object_mut().unwrap().extend(harmony.as_object().unwrap().clone()); @@ -217,9 +217,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, harmony, harmonyRule, vision"); + assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, sliders, harmony, harmonyRule, vision"); let e = app.run("ui.colorWheel", json!({"view": "wheel", "chanel": "blue"})).unwrap_err(); - assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, harmony, harmonyRule, vision"); + assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, sliders, harmony, harmonyRule, vision"); 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_vision.rs b/crates/ui-egui/src/panels/tests_color_wheel_vision.rs index 7c07b71f90..31bb3bc48b 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_vision.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_vision.rs @@ -225,8 +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", "harmony": false, "harmonyRule": "complementary", "vision": vision}); + let settings = |view: &str, vision: bool| json!({"view": view, "channel": "hue", "harmony": false, "harmonyRule": "complementary", "vision": vision, "sliders": "none"}); 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); @@ -237,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, harmony, harmonyRule, vision" + "unknown parameter `visoin`; the command takes: view, channel, sliders, harmony, harmonyRule, vision" ); 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 b681fcc5cf..b0be98c21e 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -136,6 +136,158 @@ fn the_panel_lists_the_images_with_link_info_for_the_selected_one() { } } +/// Click the flyout item `name`, checked or not (frames at `time` and just after). +fn click_menu_item(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str, time: f64) { + let frame = |app: &mut VectorcraftApp, events: Vec, time: f64| { + super::tests_appearance::frame_raw(ctx, app, egui::RawInput { events, time: Some(time), ..Default::default() }, super::links::menu) + }; + let texts = frame(app, vec![], time); + let item = texts.iter().find(|(t, _)| t.trim_start_matches('✓').trim() == name); + let at = item.unwrap_or_else(|| panic!("`{name}` not drawn: {texts:?}")).1.center(); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + for (i, e) in [egui::Event::PointerMoved(at), button(true), button(false)].into_iter().enumerate() { + frame(app, vec![e], time + 0.01 * (i + 1) as f64); + } +} + +/// Opening the panel on the selected image (the Control bar's Linked File or Embedded label) opens +/// Link Info when it was closed, and sets a Show filter that leaves out the image's row back to +/// Show All; a filter that lists the row stays. +#[test] +fn opening_the_panel_on_the_selected_image_shows_its_row_and_link_info() { + let dir = Folder::new("show-selected"); + let (mut app, linked, embedded) = app(&dir); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let text = |app: &mut VectorcraftApp, time: f64| { + let raw = egui::RawInput { time: Some(time), ..Default::default() }; + let texts = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show); + texts.into_iter().map(|(t, _)| t).collect::>().join("\n") + }; + app.run("select.set", json!({"ids": [linked]})).unwrap(); + click_menu_item(&mut app, &ctx, "Show Link Info", 1.0); + click_menu_item(&mut app, &ctx, "Show Embedded", 2.0); + let before = text(&mut app, 3.0); + assert!(!before.contains("linked.png") && !before.contains("Location"), "the filter hides the row, Link Info is closed: {before}"); + app.run("window.panel.close", json!({"panel": super::links::ID})).ok(); + super::links::show_selected_image(&mut app, &ctx); + assert!(crate::panel_docking::visible(&app.ui, super::links::ID), "status: {}", app.ui.status); + let after = text(&mut app, 4.0); + assert!(after.contains("linked.png") && after.contains("embedded.png"), "Show All lists every row: {after}"); + assert!(after.contains("Location") && after.contains("300 × 200 px"), "Link Info shows the linked image: {after}"); + // An embedded image under Show Embedded keeps the filter. + app.run("select.set", json!({"ids": [embedded]})).unwrap(); + click_menu_item(&mut app, &ctx, "Show Link Info", 5.0); + click_menu_item(&mut app, &ctx, "Show Embedded", 6.0); + super::links::show_selected_image(&mut app, &ctx); + assert!(crate::panel_docking::visible(&app.ui, super::links::ID), "an open panel stays open"); + let embedded_only = text(&mut app, 7.0); + assert!(embedded_only.contains("embedded.png") && !embedded_only.contains("linked.png"), "Show Embedded stays: {embedded_only}"); + assert!(embedded_only.contains("Effective PPI"), "Link Info shows the embedded image: {embedded_only}"); +} + +/// Opening the panel on the selected image scrolls the list to the image's row when it is out of +/// view. +#[test] +fn opening_the_panel_on_the_selected_image_scrolls_to_its_row() { + let dir = Folder::new("show-selected-scroll"); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + // The panel lists the image placed first last, below the list's view. + let mut first = None; + for i in 0..20 { + let path = dir.file(&format!("img{i:02}.png"), &png(10, 10)); + let id = app.run("file.place", json!({"path": path, "at": [10 + 15 * i, 100]})).unwrap()["ids"][0].as_u64().unwrap(); + first.get_or_insert(id); + } + app.run("select.set", json!({"ids": [first]})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + // How many times the first image's name is drawn: its row while in view, and Link Info. + let drawn = |app: &mut VectorcraftApp, time: f64| { + let raw = egui::RawInput { time: Some(time), ..Default::default() }; + let texts = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show); + texts.iter().filter(|(t, _)| t == "img00.png").count() + }; + let before = drawn(&mut app, 1.0); + assert_eq!(drawn(&mut app, 2.0), before, "the list stays at the top"); + super::links::show_selected_image(&mut app, &ctx); + // The list scrolls over the frames after the one that asks. + for time in [3.0, 4.0, 5.0] { + drawn(&mut app, time); + } + assert_eq!(drawn(&mut app, 6.0), before + 1, "the row scrolled into view"); +} + +/// Opening the panel on the selected image draws a list read after the request, so a row that a +/// file change brought into the Show filter since the list was last read is there to scroll to. +#[test] +fn opening_the_panel_on_the_selected_image_reads_the_list_again() { + let dir = Folder::new("show-selected-fresh"); + let (mut app, linked, _) = app(&dir); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + // How many times the linked image's name is drawn: its row, and Link Info. + let drawn = |app: &mut VectorcraftApp, time: f64| { + let raw = egui::RawInput { time: Some(time), ..Default::default() }; + let texts = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show); + texts.iter().filter(|(t, _)| t == "linked.png").count() + }; + app.run("select.set", json!({"ids": [linked]})).unwrap(); + click_menu_item(&mut app, &ctx, "Show Missing", 1.0); + assert_eq!(drawn(&mut app, 2.0), 1, "Link Info only: nothing is missing yet"); + std::fs::remove_file(dir.0.join("linked.png")).unwrap(); + // Within the time the panel keeps its list before it looks at the files again. + super::links::show_selected_image(&mut app, &ctx); + assert_eq!(drawn(&mut app, 2.1), 2, "the missing image's row and its Link Info are drawn"); +} + +/// The Show filter is set back to Show All from the rows the panel draws, not from the files as +/// they were when the panel was asked to open: a missing image restored before the list is drawn +/// still gets its row. +#[test] +fn opening_the_panel_on_the_selected_image_decides_the_filter_from_the_drawn_rows() { + let dir = Folder::new("show-selected-drawn"); + let (mut app, linked, _) = app(&dir); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let drawn = |app: &mut VectorcraftApp, time: f64| { + let raw = egui::RawInput { time: Some(time), ..Default::default() }; + let texts = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show); + texts.iter().filter(|(t, _)| t == "linked.png").count() + }; + app.run("select.set", json!({"ids": [linked]})).unwrap(); + click_menu_item(&mut app, &ctx, "Show Missing", 1.0); + let bytes = std::fs::read(dir.0.join("linked.png")).unwrap(); + std::fs::remove_file(dir.0.join("linked.png")).unwrap(); + super::links::show_selected_image(&mut app, &ctx); + std::fs::write(dir.0.join("linked.png"), bytes).unwrap(); + assert_eq!(drawn(&mut app, 2.0), 2, "the restored image's row and its Link Info are drawn"); + assert_eq!(super::pstate::>(&ctx, "links-scroll-to"), None, "the scroll request is used on the row"); +} + +/// A request to show the selected image applies only in the document it was made in: drawn for +/// another document, the panel keeps its Show filter and drops the request. +#[test] +fn opening_the_panel_on_the_selected_image_leaves_another_document_alone() { + let dir = Folder::new("show-selected-other-doc"); + let (mut app, linked, _) = app(&dir); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let text = |app: &mut VectorcraftApp, time: f64| { + let raw = egui::RawInput { time: Some(time), ..Default::default() }; + let texts = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show); + texts.into_iter().map(|(t, _)| t).collect::>().join("\n") + }; + app.run("select.set", json!({"ids": [linked]})).unwrap(); + click_menu_item(&mut app, &ctx, "Show Missing", 1.0); + super::links::show_selected_image(&mut app, &ctx); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let other = text(&mut app, 2.0); + assert!(other.contains("Nothing matches the Show filter."), "the other document keeps Show Missing: {other}"); + assert_eq!(super::pstate::>(&ctx, "links-scroll-to"), None, "the request is dropped"); +} + /// A frame that fetches nothing keeps the stored rows and Link Info as they are, without a copy; the /// two-second recheck, another first selected image and an edit each store a new cache. #[test] @@ -584,3 +736,93 @@ fn the_links_menu_items_run_commands() { assert!(ids("Edit").contains("links.editOriginal")); assert!(ids("Window").contains(super::links::ID)); } + +#[test] +fn right_click_context_menu_in_links_panel() { + use egui::vec2; + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + let dir = Folder::new("context-menu"); + let (mut app, linked, embedded) = app(&dir); + + let revealed: Rc>> = Rc::default(); + let rev = revealed.clone(); + app.services.reveal = Some(Box::new(move |p: &str| { + rev.borrow_mut().push(p.to_string()); + Ok(()) + })); + + // Initially embedded is selected, linked is unselected + assert_eq!(selected(&app), vec![embedded]); + + let mut h = Harness::builder().with_size(vec2(280.0, 500.0)).with_accessibility_check(false).build_ui_state( + |ui, app: &mut VectorcraftApp| { + super::links::show(app, ui); + }, + app, + ); + h.run_steps(2); + + let right_click = |h: &mut Harness<'static, VectorcraftApp>, label: &str| { + let node = h.get_all_by_label(label).find(|n| n.accesskit_node().role() == egui::accesskit::Role::ListItem).unwrap(); + let pos = node.rect().center(); + h.event(egui::Event::PointerMoved(pos)); + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + }; + + // 1. Right-click unselected "linked.png": selects it and opens context menu + right_click(&mut h, "linked.png"); + assert_eq!(selected(h.state()), vec![linked], "right-clicking unselected row selects that row first"); + + let relink = h.get_by_label(" Relink…"); + let go_to = h.get_by_label(" Go To Link"); + let update = h.get_by_label(" Update Link"); + let edit_orig = h.get_by_label(" Edit Original"); + let show_folder = h.get_by_label(" Show in Folder"); + let embed_img = h.get_by_label(" Embed Image"); + + // "Relink…" is disabled because app has no pick_open service by default + assert!(relink.accesskit_node().is_disabled()); + // "Go To Link" is enabled because linked node is in canvas document + assert!(!go_to.accesskit_node().is_disabled()); + // "Update Link" is disabled because linked file is not modified + assert!(update.accesskit_node().is_disabled()); + // "Edit Original" and "Show in Folder" are enabled because linked file exists + assert!(!edit_orig.accesskit_node().is_disabled()); + assert!(!show_folder.accesskit_node().is_disabled()); + // "Embed Image" is enabled because it is a linked image + assert!(!embed_img.accesskit_node().is_disabled()); + + // 2. Click "Show in Folder" dispatches links.reveal + show_folder.click(); + h.run_steps(2); + assert_eq!(revealed.borrow().len(), 1); + assert!(revealed.borrow()[0].ends_with("linked.png")); + + // 3. Multi-selection: select both linked and embedded + h.state_mut().run("select.set", json!({"ids": [linked, embedded]})).unwrap(); + assert_eq!(selected(h.state()), vec![linked, embedded]); + + // Right-click "linked.png" while already selected in multi-selection: preserves selection + right_click(&mut h, "linked.png"); + assert_eq!(selected(h.state()), vec![linked, embedded], "right-clicking selected row preserves multi-selection"); + + // 4. Click "Go To Link" focuses the art on canvas via go_to + let go_to_btn = h.get_by_label(" Go To Link"); + assert!(!go_to_btn.accesskit_node().is_disabled()); + go_to_btn.click(); + h.run_steps(2); + assert_eq!(selected(h.state()), vec![linked]); + assert!(h.state().view().unwrap().fitted); + + // 5. Right-click embedded image: displays "Unembed…" while "Edit Original" and "Show in Folder" are disabled + right_click(&mut h, "embedded.png"); + assert_eq!(selected(h.state()), vec![embedded]); + let unembed_btn = h.get_by_label(" Unembed…"); + assert!(!unembed_btn.accesskit_node().is_disabled()); + assert!(h.get_by_label(" Edit Original").accesskit_node().is_disabled()); + assert!(h.get_by_label(" Show in Folder").accesskit_node().is_disabled()); +} diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index 14eb352d31..42e0dba358 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -441,6 +441,8 @@ pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, l if headed { widgets::subheader(ui, tl!("Rectangle Properties:")); } + let fw = super::field_width(ui); + shape_angle_row(app, ui, live, &format!("{id}-rectangle"), "rectangleAngle", fw); corner_radius_row(app, ui, n, &format!("{id}-radius")); } LiveShape::Polygon { .. } => { @@ -451,6 +453,7 @@ pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, l } LiveShape::Ellipse { pie, .. } => { widgets::subheader(ui, tl!("Ellipse Properties:")); + shape_angle_row(app, ui, live, &format!("{id}-ellipse"), "ellipseAngle", 60.0); pie_rows(app, ui, *pie, &format!("{id}-pie")); } LiveShape::Line { .. } => return line_rows(app, ui, live, &format!("{id}-line")), @@ -459,6 +462,55 @@ pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, l true } +/// A live rectangle's or ellipse's Angle row (Rectangle and Ellipse Angle, counterclockwise): the +/// angle the selected shapes of its kind share, blank when they differ. `key` is the +/// `object.setLiveShape` param an edit sets, which turns each of them about its own center. +fn shape_angle_row(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape, id: &str, key: &str, width: f32) { + let angle = shared_shape_angle(app, ui.ctx(), live); + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Angle:")); + if let Some(a) = widgets::mixed_field_named(ui, (id, "angle"), Some(tl!("Angle:")), angle, "°", 1, width) { + app.run("object.setLiveShape", json!({ key: a })).ok(); + } + }); +} + +/// The selected live shapes of `live`'s kind, the document uid and revision they were read at, and +/// the angle they share. +type SharedAngle = Option<((u64, u64, std::mem::Discriminant), Option)>; + +/// The angle ([`LiveShape::shape_angle`]) every selected live shape of `live`'s kind shares, `None` +/// when they differ or none is selected. Measured once per (document uid, revision) and kind: the +/// panels read it every frame, and Select All can select hundreds of thousands of shapes. +fn shared_shape_angle(app: &VectorcraftApp, ctx: &egui::Context, live: &LiveShape) -> Option { + let st = app.session.active()?; + let key = (st.uid, st.revision, std::mem::discriminant(live)); + if let Some((k, angle)) = pstate::(ctx, "shape-angle") + && k == key + { + return angle; + } + let mut angles = st + .selection + .objects + .iter() + .filter_map(|id| st.doc.node(*id)?.live_shape()) + .filter(|l| std::mem::discriminant(*l) == key.2) + .filter_map(LiveShape::shape_angle); + // With no shape of its kind selected, the panel shows `live`'s own angle. + let angle = match angles.next() { + None => live.shape_angle(), + Some(first) => angles + .all(|a| { + let d = (a - first).rem_euclid(360.0); + d.min(360.0 - d) < 1e-9 + }) + .then_some(first), + }; + set_pstate::(ctx, "shape-angle", Some((key, angle))); + angle +} + /// Whether every selected object is a live line (and one is selected). fn only_lines_selected(app: &VectorcraftApp) -> bool { let Some(st) = app.session.active() else { return false }; @@ -546,6 +598,7 @@ pub(crate) fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live let side = radius.map(|r| 2.0 * r * (std::f64::consts::PI / f64::from((*sides).max(3))).sin()); let kind = super::corner_style(app, n).1; let kinds: Vec<&str> = CornerKind::ALL.iter().map(|k| corner_kind(*k)).collect(); + let angle = shared_shape_angle(app, ui.ctx(), live); // The `object.setLiveShape` param an edited field sets. let mut set = None; egui::Grid::new((id, "grid")).num_columns(2).spacing([6.0, 6.0]).show(ui, |ui| { @@ -555,7 +608,7 @@ pub(crate) fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live } ui.end_row(); widgets::dim_label(ui, tl!("Angle:")); - if let Some(a) = widgets::plain_field_named(ui, (id, "angle"), Some(tl!("Angle:")), live.polygon_angle().unwrap_or(0.0), "°", 1, fw) { + if let Some(a) = widgets::mixed_field_named(ui, (id, "angle"), Some(tl!("Angle:")), angle, "°", 1, fw) { set = Some(("polygonAngle", json!(a))); } ui.end_row(); diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index bb6b5f5000..dbb92b3cd4 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -154,6 +154,56 @@ fn an_ellipse_shows_its_pie_properties() { assert!(shown.iter().any(|s| s == "30°") && shown.iter().any(|s| s == "120°"), "{shown:?}"); } +/// A live rectangle and a live ellipse show their own angle (Rectangle and Ellipse Angle) in the +/// Transform panel and the Properties panel's Transform section, apart from the Rotate field's box +/// angle, which Reset Bounding Box squares to the page. Selected shapes of one kind at different +/// angles show a blank angle. +#[test] +fn a_rectangle_and_an_ellipse_show_their_angle() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + for (shape, heading) in [("shape.rectangle", "Rectangle Properties:"), ("shape.ellipse", "Ellipse Properties:")] { + let mut ids = vec![]; + for (y, angle) in [(20, 30), (200, 60)] { + let id = app.run(shape, json!({"x": 50, "y": y, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap(); + app.run("object.rotate", json!({"angle": angle, "absolute": true})).unwrap(); + app.run("object.resetBoundingBox", json!({})).unwrap(); + ids.push(id); + } + app.run("select.set", json!({"ids": [ids[0]]})).unwrap(); + for (draw, rotate) in [(show as fn(&mut VectorcraftApp, &mut Ui), "Rotate"), (crate::panels::properties::transform_section, "Rotation")] { + assert_eq!(field_text(&mut app, draw, rotate), "0°", "{shape}: {rotate}"); + assert_eq!(field_text(&mut app, draw, "Angle:"), "30°", "{shape}: {rotate}"); + } + assert!(texts(&mut app, show).iter().any(|s| s == heading), "{heading}"); + app.run("select.set", json!({"ids": ids})).unwrap(); + assert_eq!(field_text(&mut app, show, "Angle:"), "", "{shape}: mixed angles"); + app.run("select.set", json!({"ids": [ids[1]]})).unwrap(); + assert_eq!(field_text(&mut app, show, "Angle:"), "60°", "{shape}"); + } +} + +/// The text in `draw`'s input named `label`, read from the accessibility tree of a headless frame. +fn field_text(app: &mut VectorcraftApp, draw: fn(&mut VectorcraftApp, &mut Ui), label: &str) -> String { + use egui_kittest::kittest::Queryable; + let state = std::mem::replace(app, VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(320.0, 900.0)).with_accessibility_check(false).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + draw(app, ui); + }, + state, + ); + h.run_steps(3); + let text = h.get_by_role_and_label(egui::accesskit::Role::TextInput, label).value().unwrap_or_default(); + *app = h.into_state(); + text +} + /// Ellipse Properties' Constrain Pie Angle link, in the Transform panel and the Properties panel's /// Transform section: off at first, a click or Space with the keyboard on it toggles it, and while /// it is on a typed Pie Start or End Angle moves the other angle by as much, keeping the span, in diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index e3d277e357..0ccaec912c 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -279,11 +279,11 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ ), ( "gpuPreference", - "From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it.", + "From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it.", ), ( "lowLatencyDrawing", - "From the next start, the desktop version shows frames without waiting for the display's refresh, at most 240 a second; off, the display paces them.", + "From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it.", ), ( "historyStates", @@ -368,6 +368,24 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ "pasteTextFormatting", "Keep Formatting keeps the styles of text copied from VectorCraft type when it is pasted into type; Keep Plain Text gives it the style where it lands.", ), + // Appearance of Black + ( + "blackOnScreen", + "Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas; Display All Blacks Accurately converts it through the CMYK working space.", + ), + ( + "blackOutput", + "Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing.", + ), + // Devices + ( + "touchWorkspace", + "On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from.", + ), + ( + "touchGestures", + "A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode.", + ), ]; /// The sentence that describes the setting `key`, in English, or `None` when it has none yet. diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index d08c2079e1..0b05159a72 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -1892,6 +1892,40 @@ fn painted(texts: &[(String, egui::Rect)], sentence: &str) -> bool { texts.iter().any(|(t, _)| t == sentence) } +/// Tab presses from where the focus is, at most 40, until each of `keys` has had its sentence shown. +/// → The keys in the order Tab first showed their sentences, each with the description the focused +/// control carried in that frame. +fn tab_order(a: &mut VectorcraftApp, ctx: &egui::Context, keys: &[&'static str]) -> Vec<(&'static str, Option)> { + let sentences: Vec<_> = + keys.iter().map(|key| (*key, descriptions::description(key).unwrap_or_else(|| panic!("`{key}` has a sentence")))).collect(); + let mut reached: Vec<(&'static str, Option)> = vec![]; + for _ in 0..40 { + if reached.len() == keys.len() { + break; + } + let (texts, described) = description_frame(a, ctx, key_press(egui::Key::Tab, egui::Modifiers::NONE)); + for (key, sentence) in &sentences { + if painted(&texts, sentence) && !reached.iter().any(|(k, _)| k == key) { + reached.push((key, described.clone())); + } + } + } + reached +} + +/// Tab from where the focus is reaches the controls of `keys` in that order, the first time round: +/// the line shows each one's sentence in turn, and a screen reader gets it as the focused control's +/// description. +fn assert_tab_order(a: &mut VectorcraftApp, ctx: &egui::Context, keys: &[&'static str]) { + let reached = tab_order(a, ctx, keys); + let order: Vec<_> = reached.iter().map(|(key, _)| *key).collect(); + assert_eq!(order, keys, "Tab first reaches the controls in this order"); + for (key, described) in &reached { + let sentence = descriptions::description(key).unwrap_or_else(|| panic!("`{key}` has a sentence")); + assert_eq!(described.as_deref(), Some(sentence), "the focused `{key}` control carries the sentence"); + } +} + /// The pointer over a Units row shows that row's sentence at the bottom of the dialog, and the /// dialog keeps its size. #[test] @@ -2032,11 +2066,11 @@ fn a_row_without_a_description_leaves_the_line_empty() { } /// Every setting the General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, -/// Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling and Clipboard -/// Handling categories show on this platform, the Smart Guides box included, has exactly one -/// sentence, and no key has two. +/// Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard +/// Handling, Appearance of Black and Devices categories show on this platform, the Smart Guides box +/// included, has exactly one sentence, and no key has two. #[test] -fn every_setting_from_general_to_clipboard_handling_has_one_description() { +fn every_setting_from_general_to_devices_has_one_description() { let mut bad = vec![]; let categories = [ "General", @@ -2050,6 +2084,8 @@ fn every_setting_from_general_to_clipboard_handling_has_one_description() { "Performance", "File Handling", "Clipboard Handling", + "Appearance of Black", + "Devices", ]; for s in settings().filter(|s| categories.contains(&s.category)) { match descriptions::DESCRIPTIONS.iter().filter(|(k, _)| *k == s.key).count() { @@ -2415,27 +2451,7 @@ fn keyboard_focus_on_a_hyphenation_row_shows_its_description() { crate::theme::install_fonts(&ctx); description_frame(&mut a, &ctx, vec![]); description_frame(&mut a, &ctx, vec![]); - assert!(ctx.memory(|m| m.has_focus(search_edit_id())), "the search field has the focus on open"); - let language = descriptions::description("hyphenationLanguage").expect("Default Language has a sentence"); - let exceptions = descriptions::description("hyphenationExceptions").expect("Exceptions has a sentence"); - let mut language_seen = false; - let mut exceptions_seen = false; - for _ in 0..40 { - let (texts, described) = description_frame(&mut a, &ctx, key_press(egui::Key::Tab, egui::Modifiers::NONE)); - assert!(!ctx.memory(|m| m.has_focus(search_edit_id())), "Tab came back to the search field before both rows were reached"); - if painted(&texts, language) { - assert!(!exceptions_seen, "Tab reached the Exceptions row before the Default Language row"); - assert!(described.iter().any(|d| d == language), "the focused menu carries the sentence: {described:?}"); - language_seen = true; - } else if painted(&texts, exceptions) { - assert!(language_seen, "Tab reached the Exceptions row before the Default Language row"); - assert!(described.iter().any(|d| d == exceptions), "the focused field carries the sentence: {described:?}"); - exceptions_seen = true; - break; - } - } - assert!(language_seen, "Tab reaches the Default Language row and its sentence shows"); - assert!(exceptions_seen, "Tab goes on to the Exceptions row and its sentence shows"); + assert_tab_order(&mut a, &ctx, &["hyphenationLanguage", "hyphenationExceptions"]); } /// The pointer over each row of Plug-ins & Scratch Disks, Additional Plug-ins Folder, Plug-in @@ -2467,9 +2483,9 @@ fn hovering_a_plugins_and_scratch_disks_row_shows_its_description() { } } -/// Tab from the search field reaches the Additional Plug-ins Folder field, then Primary, then -/// Secondary: the line shows each one's sentence in turn, and a screen reader gets it as the focused -/// field's description. +/// Tab from the search field reaches the Additional Plug-ins Folder field, the Plug-in Instruction +/// Budget menu, then Primary, then Secondary: the line shows each one's sentence in turn, and a +/// screen reader gets it as the focused control's description. #[test] fn keyboard_focus_on_a_plugins_and_scratch_disks_row_shows_its_description() { let mut a = app(); @@ -2479,20 +2495,7 @@ fn keyboard_focus_on_a_plugins_and_scratch_disks_row_shows_its_description() { crate::theme::install_fonts(&ctx); description_frame(&mut a, &ctx, vec![]); description_frame(&mut a, &ctx, vec![]); - let mut tab_to = |sentence: &str| { - for _ in 0..40 { - let (texts, described) = description_frame(&mut a, &ctx, key_press(egui::Key::Tab, egui::Modifiers::NONE)); - if painted(&texts, sentence) { - return Some(described); - } - } - None - }; - for key in ["pluginsFolder", "scratchPrimary", "scratchSecondary"] { - let sentence = descriptions::description(key).unwrap_or_else(|| panic!("`{key}` has a sentence")); - let described = tab_to(sentence).unwrap_or_else(|| panic!("Tab reaches the `{key}` field and its sentence shows")); - assert!(described.iter().any(|d| d == sentence), "the focused `{key}` field carries the sentence: {described:?}"); - } + assert_tab_order(&mut a, &ctx, &["pluginsFolder", "pluginInstructionBudget", "scratchPrimary", "scratchSecondary"]); } /// System Title Bar and VectorCraft Title Bar on Every Desktop, which only some platforms show, @@ -2548,11 +2551,21 @@ fn hovering_a_user_interface_row_shows_its_description() { } texts = description_frame(&mut a, &ctx, vec![wheel.clone()]).0; } + // The wheel scrolls smoothly over several frames: wait until the row stays put. + for _ in 0..60 { + let next = description_frame(&mut a, &ctx, vec![]).0; + let still = row(&next, label) == row(&texts, label); + texts = next; + if still { + break; + } + } description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, label))]); let (after, _) = description_frame(&mut a, &ctx, vec![]); for (j, sentence) in sentences.iter().enumerate() { assert_eq!(painted(&after, sentence), i == j, "pointer over `{label}`, sentence {j}: {after:?}"); } + texts = after; } } @@ -2568,20 +2581,7 @@ fn keyboard_focus_on_a_user_interface_row_shows_its_description() { crate::theme::install_fonts(&ctx); description_frame(&mut a, &ctx, vec![]); description_frame(&mut a, &ctx, vec![]); - let mut tab_to = |sentence: &str| { - for _ in 0..40 { - let (texts, described) = description_frame(&mut a, &ctx, key_press(egui::Key::Tab, egui::Modifiers::NONE)); - if painted(&texts, sentence) { - return Some(described); - } - } - None - }; - for key in ["uiBrightness", "uiColorScheme", "uiAccent", "canvasColor", "autoCollapseIconPanels"] { - let sentence = descriptions::description(key).unwrap_or_else(|| panic!("`{key}` has a sentence")); - let described = tab_to(sentence).unwrap_or_else(|| panic!("Tab reaches the `{key}` control and its sentence shows")); - assert!(described.iter().any(|d| d == sentence), "the focused `{key}` control carries the sentence: {described:?}"); - } + assert_tab_order(&mut a, &ctx, &["uiBrightness", "uiColorScheme", "uiAccent", "canvasColor", "autoCollapseIconPanels"]); } /// Linux Display Server, which only Linux shows, and Use Monitor Profile for Canvas, which the @@ -2609,17 +2609,15 @@ fn hovering_a_performance_row_shows_its_description() { let row = |texts: &[(String, egui::Rect)], label: &str| { texts.iter().rev().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")) }; - let mut rows = vec![ - ("GPU Performance", "gpuPerformance"), - ("Animated Zoom", "animatedZoom"), - ("Graphics Processor:", "gpuPreference"), + let mut rows = vec![("GPU Performance", "gpuPerformance"), ("Animated Zoom", "animatedZoom"), ("Graphics Processor:", "gpuPreference")]; + if !cfg!(target_arch = "wasm32") { + rows.push(("Low-Latency Drawing", "lowLatencyDrawing")); + } + rows.extend([ ("History States:", "historyStates"), ("Real-time Drawing and Editing", "realTimeDrawing"), ("Render Threads (-1 = Automatic):", "renderThreads"), - ]; - if !cfg!(target_arch = "wasm32") { - rows.insert(3, ("Low-Latency Drawing", "lowLatencyDrawing")); - } + ]); if cfg!(target_os = "linux") { rows.push(("Linux Display Server:", "linuxDisplayServer")); } @@ -2662,8 +2660,9 @@ fn hovering_a_performance_row_shows_its_description() { } /// Tab from the search field reaches the GPU Performance checkbox, then Animated Zoom, the -/// Graphics Processor menu and the History States field: the line shows each one's sentence in -/// turn, and a screen reader gets it as the focused control's description. +/// Graphics Processor menu, the Low-Latency Drawing checkbox on the desktop and the History States +/// field: the line shows each one's sentence in turn, and a screen reader gets it as the focused +/// control's description. #[test] fn keyboard_focus_on_a_performance_row_shows_its_description() { let mut a = app(); @@ -2673,20 +2672,12 @@ fn keyboard_focus_on_a_performance_row_shows_its_description() { crate::theme::install_fonts(&ctx); description_frame(&mut a, &ctx, vec![]); description_frame(&mut a, &ctx, vec![]); - let mut tab_to = |sentence: &str| { - for _ in 0..40 { - let (texts, described) = description_frame(&mut a, &ctx, key_press(egui::Key::Tab, egui::Modifiers::NONE)); - if painted(&texts, sentence) { - return Some(described); - } - } - None - }; - for key in ["gpuPerformance", "animatedZoom", "gpuPreference", "historyStates"] { - let sentence = descriptions::description(key).unwrap_or_else(|| panic!("`{key}` has a sentence")); - let described = tab_to(sentence).unwrap_or_else(|| panic!("Tab reaches the `{key}` control and its sentence shows")); - assert!(described.iter().any(|d| d == sentence), "the focused `{key}` control carries the sentence: {described:?}"); + let mut keys = vec!["gpuPerformance", "animatedZoom", "gpuPreference"]; + if !cfg!(target_arch = "wasm32") { + keys.push("lowLatencyDrawing"); } + keys.push("historyStates"); + assert_tab_order(&mut a, &ctx, &keys); } /// The pointer over each of the 14 File Handling rows, from Enable Background Save to Use @@ -2765,20 +2756,7 @@ fn keyboard_focus_on_a_file_handling_row_shows_its_description() { crate::theme::install_fonts(&ctx); description_frame(&mut a, &ctx, vec![]); description_frame(&mut a, &ctx, vec![]); - let mut tab_to = |sentence: &str| { - for _ in 0..40 { - let (texts, described) = description_frame(&mut a, &ctx, key_press(egui::Key::Tab, egui::Modifiers::NONE)); - if painted(&texts, sentence) { - return Some(described); - } - } - None - }; - for key in ["backgroundSave", "backgroundExport", "autosaveRecovery", "autosaveInterval"] { - let sentence = descriptions::description(key).unwrap_or_else(|| panic!("`{key}` has a sentence")); - let described = tab_to(sentence).unwrap_or_else(|| panic!("Tab reaches the `{key}` control and its sentence shows")); - assert!(described.iter().any(|d| d == sentence), "the focused `{key}` control carries the sentence: {described:?}"); - } + assert_tab_order(&mut a, &ctx, &["backgroundSave", "backgroundExport", "autosaveRecovery", "autosaveInterval"]); } /// The pointer over each of the five Clipboard Handling rows, from Include SVG Code to When @@ -2824,22 +2802,86 @@ fn keyboard_focus_on_a_clipboard_handling_row_shows_its_description() { crate::theme::install_fonts(&ctx); description_frame(&mut a, &ctx, vec![]); description_frame(&mut a, &ctx, vec![]); - let mut tab_to = |sentence: &str| { - for _ in 0..40 { - let (texts, described) = description_frame(&mut a, &ctx, key_press(egui::Key::Tab, egui::Modifiers::NONE)); - if painted(&texts, sentence) { - return Some(described); - } - } - None + assert_tab_order(&mut a, &ctx, &["copyAsSvg", "copyAsPdf", "copyAicb", "aicbMode", "pasteTextFormatting"]); +} + +/// The pointer over each of the two Appearance of Black rows, On Screen and Printing / Exporting, +/// shows that row's sentence and not the other row's. +#[test] +fn hovering_an_appearance_of_black_row_shows_its_description() { + let mut a = app(); + open(&mut a, Some("Appearance of Black")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + let (texts, _) = description_frame(&mut a, &ctx, vec![]); + let row = |texts: &[(String, egui::Rect)], label: &str| { + texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")) }; - for key in ["copyAsSvg", "copyAsPdf", "copyAicb", "aicbMode", "pasteTextFormatting"] { - let sentence = descriptions::description(key).unwrap_or_else(|| panic!("`{key}` has a sentence")); - let described = tab_to(sentence).unwrap_or_else(|| panic!("Tab reaches the `{key}` control and its sentence shows")); - assert!(described.iter().any(|d| d == sentence), "the focused `{key}` control carries the sentence: {described:?}"); + let rows = [("On Screen:", "blackOnScreen"), ("Printing / Exporting:", "blackOutput")]; + let sentences: Vec<_> = rows.iter().map(|(_, key)| descriptions::description(key).unwrap_or_else(|| panic!("`{key}` has a sentence"))).collect(); + for (i, (label, _)) in rows.iter().enumerate() { + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, label))]); + let (after, _) = description_frame(&mut a, &ctx, vec![]); + for (j, sentence) in sentences.iter().enumerate() { + assert_eq!(painted(&after, sentence), i == j, "pointer over `{label}`, sentence {j}: {after:?}"); + } } } +/// Tab from the search field reaches the On Screen and Printing / Exporting menus: the line shows +/// each one's sentence in turn, and a screen reader gets it as the focused control's description. +#[test] +fn keyboard_focus_on_an_appearance_of_black_row_shows_its_description() { + let mut a = app(); + open(&mut a, Some("Appearance of Black")); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + description_frame(&mut a, &ctx, vec![]); + assert_tab_order(&mut a, &ctx, &["blackOnScreen", "blackOutput"]); +} + +/// The pointer over each of the two Devices rows, Enable Touch Workspace and Enable Touch Gestures, +/// shows that row's sentence and not the other row's. +#[test] +fn hovering_a_devices_row_shows_its_description() { + let mut a = app(); + open(&mut a, Some("Devices")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + let (texts, _) = description_frame(&mut a, &ctx, vec![]); + let row = |texts: &[(String, egui::Rect)], label: &str| { + texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")) + }; + let rows = [("Enable Touch Workspace", "touchWorkspace"), ("Enable Touch Gestures", "touchGestures")]; + let sentences: Vec<_> = rows.iter().map(|(_, key)| descriptions::description(key).unwrap_or_else(|| panic!("`{key}` has a sentence"))).collect(); + for (i, (label, _)) in rows.iter().enumerate() { + description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, label))]); + let (after, _) = description_frame(&mut a, &ctx, vec![]); + for (j, sentence) in sentences.iter().enumerate() { + assert_eq!(painted(&after, sentence), i == j, "pointer over `{label}`, sentence {j}: {after:?}"); + } + } +} + +/// Tab from the search field reaches the Enable Touch Workspace and Enable Touch Gestures boxes: the +/// line shows each one's sentence in turn, and a screen reader gets it as the focused control's +/// description. +#[test] +fn keyboard_focus_on_a_devices_row_shows_its_description() { + let mut a = app(); + open(&mut a, Some("Devices")); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + description_frame(&mut a, &ctx, vec![]); + assert_tab_order(&mut a, &ctx, &["touchWorkspace", "touchGestures"]); +} + /// A sentence shown when the dialog closed does not come back when it opens again with the /// pointer away from the rows. #[test] diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index b4ef813ef4..dccb71f531 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -6,6 +6,15 @@ use vectorcraft_geom::Point; use crate::theme::Brightness; +/// A one-shot Image Trace Ignore Color sampler, bound to the unchanged selected source. +#[derive(Clone, Debug)] +pub struct TraceIgnoreSampler { + pub doc: u64, + pub target: vectorcraft_doc::NodeId, + pub revision: u64, + pub back: String, +} + /// A Brush Options Key Color click, owned by its dialog and document until release or cancel. #[derive(Clone, Debug)] pub struct BrushKeyColorPick { @@ -493,6 +502,10 @@ pub struct UiState { /// starts under the selection at every launch. #[serde(skip)] pub task_bar_place: TaskBarPlace, + /// The Contextual Task Bar's actions (`canvas::TASK_BAR_ACTIONS`) that More Options › Bar + /// 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, /// 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)] @@ -816,8 +829,8 @@ pub struct UiState { /// of an RGB field, `ui.colorPanel`, [`crate::panels::color::deserialize_rgb_percent`]). #[serde(default, deserialize_with = "crate::panels::color::deserialize_rgb_percent")] pub color_rgb_percent: bool, - /// Color Wheel panel: the wheel or the box, the box's channel, and the color vision row - /// (`ui.colorWheel`, [`crate::panels::color_wheel::deserialize_settings`]). + /// Color Wheel panel: the wheel or the box, the box's channel, the slider rows and the color + /// vision row (`ui.colorWheel`, [`crate::panels::color_wheel::deserialize_settings`]). #[serde(default, deserialize_with = "crate::panels::color_wheel::deserialize_settings")] pub color_wheel: crate::panels::color_wheel::Settings, /// Swatches panel: Show Recent Colors in its panel menu, which draws the panel's Recent Colors @@ -859,6 +872,11 @@ pub struct UiState { /// [`crate::dialogs::settle`] opens the choice again once no dialog is open. #[serde(skip)] pub stopped_plugin: Option, + /// The proof view the Proof Setup dialog found, and the view its preview shows on the canvas, + /// while the preview shows. When another dialog takes its place, [`crate::dialogs::settle`] + /// puts the first view back, unless the view has changed from the preview since. + #[serde(skip)] + pub proof_preview: Option<(Value, vectorcraft_render::proof::ProofView)>, /// The search the Missing Fonts dialog started (`text.findFontFiles`'s `id`), stopped once the /// dialog is gone. #[serde(skip)] @@ -932,6 +950,9 @@ pub struct UiState { /// panel's eye button is held down ([`vectorcraft_render::RenderOptions::trace_source`]). #[serde(skip)] pub trace_hold_source: Option>>, + /// Ignore Color's one-shot canvas sampler; independent of the eye button's press lifetime. + #[serde(skip)] + pub trace_ignore_sampler: Option, /// Layers panel › Panel Options… (row size, thumbnails, Show Layers Only, Locate Selected Objects). #[serde(default)] pub layers_panel: crate::panels::layers::PanelOptions, @@ -1257,6 +1278,7 @@ impl Default for UiState { toolbar_advanced: false, task_bar: true, task_bar_place: TaskBarPlace::default(), + task_bar_hidden_actions: Default::default(), shape_modes_compound: false, context_locked: None, context_intertwine: None, @@ -1358,6 +1380,7 @@ impl Default for UiState { pending_fonts: vec![], fonts_dialog: None, stopped_plugin: None, + proof_preview: None, dialog_search: None, links_search: None, dxf_options: Value::Null, @@ -1377,6 +1400,7 @@ impl Default for UiState { psd_import: Value::Null, home: None, trace_hold_source: None, + trace_ignore_sampler: None, layers_panel: Default::default(), navigator_panel: Default::default(), attributes_panel: Default::default(), diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index 7a904e4646..3affa544ec 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -672,6 +672,30 @@ fn ui_inspect_leaves_out_paths_outside_the_read_root() { let _ = std::fs::remove_dir_all(base); } +/// `ui.inspect` leaves out the file of a saved proof setup that an open Insert Menu Item dialog +/// picked when it is outside the read root, and shows one inside it. +#[test] +fn ui_inspect_leaves_out_an_insert_menu_item_path_outside_the_read_root() { + let (mut app, tx, base) = confined("inspect-insert-menu-item"); + let load = crate::dialogs::proof_setup::LOAD; + let (inside, outside) = (s(base.join("in/Press.vcproof")), s(base.join("outside/Press.vcproof"))); + let dialog = |path: &str| { + let fields = json!({"find": "", "command": load, "params": {"path": path}, "note": ""}); + Some(crate::state::Dialog::new(crate::dialogs::action_insert_menu_item::KIND, fields)) + }; + app.ui.dialog = dialog(&outside); + let ctx = egui::Context::default(); + assert_eq!(crate::control::inspect(&app, &ctx)["ui"]["dialog"]["fields"]["params"]["path"], outside, "the person sees it"); + let r = request(&mut app, &tx, "ui.inspect", json!({})); + let fields = &r["result"]["ui"]["dialog"]["fields"]; + assert_eq!((fields["command"].as_str(), fields["params"].get("path")), (Some(load), None), "{r}"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.fields["params"]["path"].clone()), Some(json!(outside)), "the UI state is not changed"); + app.ui.dialog = dialog(&inside); + let r = request(&mut app, &tx, "ui.inspect", json!({})); + assert_eq!(r["result"]["ui"]["dialog"]["fields"]["params"]["path"], inside, "{r}"); + let _ = std::fs::remove_dir_all(base); +} + /// `ui.inspect` checks a folder preference as it is written: the read root's path with a space before /// it is a relative path, outside the root, and is left out. #[test] @@ -1310,7 +1334,9 @@ fn ui_inspect_script_report_leaves_out_files_outside_the_read_root() { std::fs::write(base.join("outside/bad.jsxinc"), "\nthrow new Error('stopped here');\n").unwrap(); finish(&mut app, json!({"path": s(base.join("outside/run.jsx"))})); let person = crate::control::inspect(&app, &ctx); - assert_eq!(person["scriptReport"]["file"], json!(s(base.join("outside/bad.jsxinc"))), "{person}"); + // The report names the file by its real path (on macOS the temp folder is reached through a link). + let bad = std::fs::canonicalize(base.join("outside/bad.jsxinc")).unwrap(); + assert_eq!(person["scriptReport"]["file"], json!(s(bad)), "{person}"); let r = request(&mut app, &tx, "ui.inspect", json!({})); assert_eq!(r["result"]["scriptReport"]["file"], "bad.jsxinc", "{r}"); assert!(r["result"]["scriptReport"]["console"].to_string().contains("bad.jsxinc:2:"), "{r}"); diff --git a/crates/ui-egui/src/tests/recolor.rs b/crates/ui-egui/src/tests/recolor.rs index 9eda6674fe..986dbb6290 100644 --- a/crates/ui-egui/src/tests/recolor.rs +++ b/crates/ui-egui/src/tests/recolor.rs @@ -1496,6 +1496,169 @@ fn a_color_bars_menu_removes_its_color() { assert_eq!(field(h.state(), "__sel"), json!([0])); } +/// Right-clicks the point `at`. +fn right_click_at(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, at: Pos2) { + h.event(Event::PointerMoved(at)); + h.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE }); + h.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +/// The smaller angle between hues `a` and `b`, in degrees. +fn hue_gap(a: f32, b: f32) -> f32 { + (a - b).rem_euclid(360.0).min((b - a).rem_euclid(360.0)) +} + +/// A marker's right-click menu has Set As Base Color, Select Shade, Color Picker and Remove Color. +/// Set As Base Color marks the row as the base, whose menu then has neither Set As Base Color nor +/// Remove Color; with another color selected, a harmony rule builds from the base color, and OK +/// recolors the art. +#[test] +fn a_markers_menu_sets_the_base_color_that_the_rules_build_from() { + let mut h = edit_harness(&["#ff0000", "#0000ff", "#00ff00"]); + let hsb = new_hsb(h.state()); + let at = wheel_at(&h, hsb[1][0], hsb[1][1]); + right_click_at(&mut h, at); + for item in [" Set As Base Color", " Select Shade", " Color Picker", " Remove Color"] { + assert!(h.query_by_label(item).is_some(), "{item}"); + } + h.get_by_label(" Set As Base Color").click(); + h.run_steps(3); + let rows = field(h.state(), "rows"); + assert_eq!(rows[1]["base"], json!(true), "{rows}"); + assert!(rows[0].get("base").is_none() && rows[2].get("base").is_none()); + right_click_at(&mut h, at); + assert!(h.get_by_label(" Set As Base Color").accesskit_node().is_disabled(), "it is the base already"); + assert!(h.get_by_label(" Remove Color").accesskit_node().is_disabled(), "the base color can't be removed"); + h.key_press(egui::Key::Escape); + h.run_steps(2); + // The selected color is another one; the rule still builds from the base. + set(h.state_mut(), "__sel", json!([0])); + h.run_steps(3); + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Harmony Rules:").click(); + h.run_steps(2); + h.get_by_label("Triad").click(); + h.run_steps(3); + let now = new_hsb(h.state()); + assert!(hue_gap(now[1][0], hsb[1][0]) < 1.0, "the base color keeps its hue: {hsb:?} -> {now:?}"); + assert!(hue_gap(now[0][0], now[1][0]) > 110.0 && hue_gap(now[2][0], now[1][0]) > 110.0, "the others are a triad from it: {now:?}"); + assert_eq!(field(h.state(), "rows")[1]["base"], json!(true), "the rule keeps the base mark"); + let before = fills(h.state()); + let app = h.state_mut(); + dialogs::confirm(app).unwrap(); + assert_eq!(fills(app), before, "OK keeps the previewed colors"); +} + +/// Select Shade on a marker's menu shows a grid of the color's hue; a click on a cell gives the color +/// that saturation and brightness, keeping its hue, and closes the menu. Unlinked, the other colors +/// stay; linked, they move as a drag would move them. +#[test] +fn select_shade_gives_a_marker_the_shade_clicked() { + for linked in [false, true] { + let mut h = edit_harness(&["rgb 200 100 100", "rgb 100 200 200"]); + set(h.state_mut(), "linked", json!(linked)); + h.run_steps(3); + let hsb = new_hsb(h.state()); + let at = wheel_at(&h, hsb[0][0], hsb[0][1]); + right_click_at(&mut h, at); + h.get_by_label(" Select Shade").click(); + h.run_steps(2); + let cell = "Saturation 50%, Brightness 57%"; + h.get_by_label(cell).click(); + h.run_steps(3); + let now = new_hsb(h.state()); + assert!(hue_gap(now[0][0], hsb[0][0]) < 1.0 && (now[0][1] - 0.5).abs() < 0.01 && (now[0][2] - 4.0 / 7.0).abs() < 0.01, "{now:?}"); + let other_moved = (now[1][2] - hsb[1][2]).abs() > 0.01; + assert_eq!(other_moved, linked, "linked {linked}: {hsb:?} -> {now:?}"); + assert!(h.query_by_label(cell).is_none(), "the menu closes"); + assert_eq!(field(h.state(), "__sel"), json!([0])); + } +} + +/// Color Picker on a marker's menu opens the Color Picker for that color. +#[test] +fn a_markers_menu_opens_the_color_picker() { + let mut h = edit_harness(&["rgb 200 100 100", "rgb 100 200 200"]); + let hsb = new_hsb(h.state()); + let at = wheel_at(&h, hsb[1][0], hsb[1][1]); + right_click_at(&mut h, at); + h.get_by_label(" Color Picker").click(); + h.run_steps(3); + assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("colorPicker")); +} + +/// A right-click on the wheel away from the markers offers Add New Color, which adds the hue and +/// saturation there as a new color. A color added on the line from the center to a marker moves +/// with that marker when the colors are unlinked, and the others stay. +#[test] +fn add_new_color_on_a_markers_line_moves_with_that_marker() { + let mut h = edit_harness(&["rgb 200 100 100", "rgb 100 200 200"]); + set(h.state_mut(), "linked", json!(false)); + set(h.state_mut(), "__sel", json!([0])); + h.run_steps(4); + let hsb = new_hsb(h.state()); + let at = wheel_at(&h, 90.0, 0.6); + right_click_at(&mut h, at); + assert!(h.query_by_label(" Set As Base Color").is_none(), "no marker there"); + h.get_by_label(" Add New Color").click(); + h.run_steps(3); + let rows = field(h.state(), "rows"); + assert_eq!(rows.as_array().unwrap().len(), 3, "{rows}"); + assert_eq!((&rows[2]["from"], &rows[2]["added"]), (&json!([]), &json!(true))); + assert!(rows[2].get("follows").is_none(), "off every marker's line"); + let [hue, s, v] = new_hsb(h.state())[2]; + assert!((hue - 90.0).abs() < 1.0 && (s - 0.6).abs() < 0.01 && (v - hsb[0][2]).abs() < 0.01, "{:?}", [hue, s, v]); + assert_eq!(field(h.state(), "__sel"), json!([2])); + // Halfway along the second color's line. + let on_line = wheel_at(&h, hsb[1][0], hsb[1][1] / 2.0); + right_click_at(&mut h, on_line); + h.get_by_label(" Add New Color").click(); + h.run_steps(3); + let rows = field(h.state(), "rows"); + assert_eq!(rows.as_array().unwrap().len(), 4); + assert!(rows[1]["tie"].is_u64() && rows[3]["follows"] == rows[1]["tie"], "{rows}"); + // Drag the second color's marker a little way round: the color on its line turns with it. + let before = new_hsb(h.state()); + let start = wheel_at(&h, before[1][0], before[1][1]); + h.hover_at(start); + h.run_steps(1); + h.drag_at(start); + h.run_steps(1); + let mut p = start; + for k in 1..=6 { + p = wheel_at(&h, before[1][0] + 5.0 * k as f32, before[1][1]); + h.hover_at(p); + h.run_steps(1); + } + h.drop_at(p); + h.run_steps(2); + let after = new_hsb(h.state()); + let turned = hue_gap(after[1][0], before[1][0]); + assert!(turned > 20.0, "the marker turned: {before:?} -> {after:?}"); + assert!((hue_gap(after[3][0], before[3][0]) - turned).abs() < 1.0, "the color on its line turned as far: {before:?} -> {after:?}"); + assert!(hue_gap(after[0][0], before[0][0]) < 0.5 && hue_gap(after[2][0], before[2][0]) < 0.5, "the others stay: {before:?} -> {after:?}"); +} + +/// Set Current Color As Base Color makes the selected color the base; it is off while the selected +/// color is the base. A color bar's menu has Set As Base Color too. +#[test] +fn set_current_color_as_base_color_marks_the_selected_color() { + let mut h = edit_harness(&["#ff0000", "#0000ff", "#00ff00"]); + let name = "Set Current Color As Base Color"; + assert!(h.get_by_role_and_label(egui::accesskit::Role::Button, name).accesskit_node().is_disabled(), "the base color is the selected one"); + set(h.state_mut(), "__sel", json!([2])); + h.run_steps(3); + click_button(&mut h, name); + assert_eq!(field(h.state(), "rows")[2]["base"], json!(true)); + assert!(h.get_by_role_and_label(egui::accesskit::Role::Button, name).accesskit_node().is_disabled()); + show_display(&mut h, "Show color bars"); + right_click_bar(&mut h, "Color 1"); + h.get_by_label(" Set As Base Color").click(); + h.run_steps(3); + let rows = field(h.state(), "rows"); + assert_eq!((&rows[0]["base"], rows[2].get("base")), (&json!(true), None), "{rows}"); +} + // Optional local visual QA; these captures are not committed assets. fn capture_recolor(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, name: &str) { if let Some(dir) = std::env::var_os("VECTORCRAFT_RECOLOR_CAPTURE_DIR") { diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index bc4734db5a..1615681f57 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -1573,3 +1573,469 @@ fn the_task_bar_follows_edits_and_undo() { assert!(has(&texts, "10 pt") && !has(&texts, "20 pt"), "{texts:?}"); assert!(!locked(&app, rect), "the button doesn't lock the shape"); } + +/// Turns the bar's action or chip `action` on or off (`window.taskBar.actions`). +fn show_action(app: &mut VectorcraftApp, action: &str, visible: bool) { + let r = app.run("window.taskBar.actions", json!({"action": action, "visible": visible})).unwrap(); + assert_eq!(r, json!({"action": action, "visible": visible})); +} + +/// An action turned off in Bar Actions leaves the bar for every selection that offers it, and its +/// Object menu command stays enabled. Toggled, it comes back. +#[test] +fn an_action_turned_off_leaves_the_bar_and_stays_in_its_menu() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let line = id(app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 200, "y2": 120})).unwrap()); + select(&mut app, &[line]); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Offset Path") && has(&texts, "Join"), "{texts:?}"); + show_action(&mut app, "offsetPath", false); + assert_eq!(crate::menus::checked(&app, "window.taskBar.actions", &json!({"action": "offsetPath"})), Some(false)); + assert_eq!(crate::menus::checked(&app, "window.taskBar.actions", &json!({"action": "join"})), Some(true)); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Offset Path"), "{texts:?}"); + assert!(has(&texts, "Join") && has(&texts, "Simplify") && has(&texts, "Edit Path"), "the other actions stay: {texts:?}"); + assert!(crate::menus::enabled(&app, "object.path.offsetPath"), "Object › Path › Offset Path… still runs"); + + // Another selection that offers the same action leaves it out too: a rectangle. + let rect = id(app.run("shape.rectangle", json!({"x": 220, "y": 40, "width": 80, "height": 60})).unwrap()); + select(&mut app, &[rect]); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Offset Path") && has(&texts, "Edit Path"), "{texts:?}"); + + // Toggled (no `visible`), it shows again. + assert_eq!(app.run("window.taskBar.actions", json!({"action": "offsetPath"})).unwrap(), json!({"action": "offsetPath", "visible": true})); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Offset Path"), "{texts:?}"); + // A `visible` of null counts as omitted and toggles too. + let r = app.run("window.taskBar.actions", json!({"action": "offsetPath", "visible": null})).unwrap(); + assert_eq!(r, json!({"action": "offsetPath", "visible": false})); +} + +/// The Fill, Stroke, Recolor Artwork, Lock and Shape Properties chips each turn off on their own: +/// Lock off leaves a basic shape's Shape Properties, and Shape Properties off leaves Lock. +#[test] +fn a_chip_turned_off_leaves_the_bar() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let rect = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60})).unwrap()); + let line = id(app.run("shape.line", json!({"x1": 50, "y1": 150, "x2": 200, "y2": 220})).unwrap()); + select(&mut app, &[rect]); + let names = |app: &mut VectorcraftApp| buttons(app).1.into_iter().map(|(n, _)| n).collect::>(); + let shown = names(&mut app); + for name in ["Fill", "Stroke", "Shape Properties"] { + assert!(shown.iter().any(|n| n == name), "{name}: {shown:?}"); + } + show_action(&mut app, "fill", false); + show_action(&mut app, "lock", false); + let shown = names(&mut app); + assert!(!shown.iter().any(|n| n == "Fill"), "{shown:?}"); + assert!(shown.iter().any(|n| n == "Stroke") && shown.iter().any(|n| n == "Shape Properties"), "{shown:?}"); + select(&mut app, &[line]); + let shown = names(&mut app); + assert!(!shown.iter().any(|n| n.starts_with("Lock")), "Lock is off: {shown:?}"); + show_action(&mut app, "lock", true); + show_action(&mut app, "shapeProperties", false); + let shown = names(&mut app); + assert!(shown.iter().any(|n| n.starts_with("Lock")), "Lock is on again: {shown:?}"); + select(&mut app, &[rect]); + let shown = names(&mut app); + assert!(!shown.iter().any(|n| n == "Shape Properties"), "{shown:?}"); +} + +/// Reset Bar Actions shows every action and chip again and returns the ids it showed. +#[test] +fn reset_bar_actions_shows_every_action_again() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let line = id(app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 200, "y2": 120})).unwrap()); + select(&mut app, &[line]); + show_action(&mut app, "simplify", false); + show_action(&mut app, "duplicate", false); + show_action(&mut app, "stroke", false); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Simplify") && !has(&texts, "Duplicate"), "{texts:?}"); + assert_eq!(app.run("window.taskBar.resetActions", json!({})).unwrap(), json!(["duplicate", "simplify", "stroke"])); + assert!(app.ui.task_bar_hidden_actions.is_empty()); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Simplify") && has(&texts, "Duplicate"), "{texts:?}"); + assert_eq!(app.run("window.taskBar.resetActions", json!({})).unwrap(), json!([]), "nothing left to show"); +} + +/// Each of the bar's actions and chips has its own id, and no two actions run the same command +/// with the same tool. +#[test] +fn bar_action_ids_are_distinct() { + let ids: Vec<&str> = canvas::TASK_BAR_ACTIONS.iter().map(|a| a.0).chain(canvas::TASK_BAR_CHIPS).collect(); + let set: std::collections::BTreeSet<&str> = ids.iter().copied().collect(); + assert_eq!(set.len(), ids.len(), "{ids:?}"); + let runs: std::collections::BTreeSet<(&str, Option<&str>)> = canvas::TASK_BAR_ACTIONS.iter().map(|a| (a.1, a.2)).collect(); + assert_eq!(runs.len(), canvas::TASK_BAR_ACTIONS.len()); +} + +/// An action the bar does not have, a missing one, or a `visible` that is not true, false or null is +/// an error and changes nothing. +#[test] +fn bar_actions_refuse_bad_params() { + let mut app = app(); + show_action(&mut app, "group", false); + for p in [json!({"action": "teleport"}), json!({}), json!({"action": 3}), json!({"action": "unite", "visible": "yes"})] { + assert!(app.run("window.taskBar.actions", p.clone()).is_err(), "{p}"); + } + let err = app.run("window.taskBar.actions", json!({"action": "teleport"})).unwrap_err(); + assert!(err.contains("imageTrace") && err.contains("shapeProperties"), "{err}"); + assert_eq!(app.ui.task_bar_hidden_actions.iter().map(String::as_str).collect::>(), ["group"]); + assert_eq!(crate::menus::checked(&app, "window.taskBar.actions", &json!({"action": "teleport"})), Some(false)); +} + +/// The actions that are off are kept with the preferences. Ids the bar does not have are dropped, +/// a value that is not a list turns none off, and older preferences without it show every action. +#[test] +fn bar_actions_are_kept_with_the_preferences() { + let mut app = app(); + show_action(&mut app, "unite", false); + show_action(&mut app, "recolor", false); + let mut prefs = serde_json::to_value(&app.ui).unwrap(); + let back: crate::state::UiState = serde_json::from_value(prefs.clone()).unwrap(); + let ids = |ui: &crate::state::UiState| ui.task_bar_hidden_actions.iter().cloned().collect::>(); + assert_eq!(ids(&back), ["recolor", "unite"]); + prefs["task_bar_hidden_actions"] = json!(["unite", "teleport", 7, "fill"]); + assert_eq!(ids(&serde_json::from_value(prefs.clone()).unwrap()), ["fill", "unite"], "ids the bar does not have are dropped"); + prefs["task_bar_hidden_actions"] = json!("unite"); + assert!(ids(&serde_json::from_value(prefs.clone()).unwrap()).is_empty(), "a value that is not a list turns none off"); + prefs.as_object_mut().unwrap().remove("task_bar_hidden_actions"); + assert!(ids(&serde_json::from_value(prefs).unwrap()).is_empty(), "older preferences show every action"); + app.run("window.taskBar.resetActions", json!({})).unwrap(); + assert_eq!(serde_json::to_value(&app.ui).unwrap()["task_bar_hidden_actions"], json!([]), "none off"); +} + +/// More Options › Bar Actions lists the actions and chips the bar offers for the selection, each +/// checked while it shows; a click turns one off, it is listed unchecked after that, and a click on +/// Reset Bar Actions shows it again. +#[test] +fn more_options_bar_actions_turns_an_action_off_and_on() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let line = id(app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 200, "y2": 120})).unwrap()); + select(&mut app, &[line]); + let more = buttons(&mut app).1.into_iter().find(|(n, _)| n == "More Options").expect("More Options").1.center(); + let (ctx, _) = bar(&mut app); + let click_at = |app: &mut VectorcraftApp, p: Pos2| { + 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![]) + }; + let texts = click_at(&mut app, more); + let item = at(&texts, " Bar Actions"); + frame(&mut app, &ctx, vec![Event::PointerMoved(item)]); + let texts = frame(&mut app, &ctx, vec![]); + for name in ["✓ Join", "✓ Edit Path", "✓ Offset Path", "✓ Simplify", "✓ Duplicate", "✓ Fill", "✓ Stroke", "✓ Lock"] { + assert!(has(&texts, name), "{name}: {texts:?}"); + } + assert!(has(&texts, " Reset Bar Actions"), "{texts:?}"); + let offset = at(&texts, "✓ Offset Path"); + // Along the submenu's row first, so the pointer stays over the menu on its way. + frame(&mut app, &ctx, vec![Event::PointerMoved(Pos2::new(offset.x, item.y))]); + click_at(&mut app, offset); + assert!(app.ui.task_bar_hidden_actions.contains("offsetPath"), "{:?}", app.ui.task_bar_hidden_actions); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Offset Path") && has(&texts, "Simplify"), "{texts:?}"); + + // Opened again, Bar Actions lists it unchecked; Reset Bar Actions turns it on. + let more = buttons(&mut app).1.into_iter().find(|(n, _)| n == "More Options").expect("More Options").1.center(); + let (ctx, _) = bar(&mut app); + let click_at = |app: &mut VectorcraftApp, p: Pos2| { + 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![]) + }; + let texts = click_at(&mut app, more); + let item = at(&texts, " Bar Actions"); + let reset = at(&texts, " Reset Bar Actions"); + frame(&mut app, &ctx, vec![Event::PointerMoved(item)]); + let texts = frame(&mut app, &ctx, vec![]); + assert!(has(&texts, " Offset Path") && has(&texts, "✓ Simplify"), "{texts:?}"); + // Back along the menu's column to Reset Bar Actions, closing the submenu on the way. + frame(&mut app, &ctx, vec![Event::PointerMoved(Pos2::new(item.x, reset.y))]); + click_at(&mut app, reset); + assert!(app.ui.task_bar_hidden_actions.is_empty(), "{:?}", app.ui.task_bar_hidden_actions); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Offset Path"), "{texts:?}"); +} + +/// On a canvas too short for every action, More Options lists the ones that don't fit; an action +/// turned off in Bar Actions is listed neither there nor on the bar, and the others still are. +#[test] +fn an_action_turned_off_is_not_listed_in_more_options() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let a = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 120, "height": 100})).unwrap()); + let b = id(app.run("shape.ellipse", json!({"x": 70, "y": 60, "width": 50, "height": 50})).unwrap()); + select(&mut app, &[a, b]); + let size = vec2(160.0, 150.0); + // More Options' list, opened on a new context, and what the bar itself shows. + let listed = |app: &mut VectorcraftApp| { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let (on_bar, r, _) = bar_texts_on_screen(app, &ctx, size, 3); + let more = r.min + vec2(9.0 + 4.0 + 6.0 + 15.0, 7.0 + 15.0); + let press = |pressed| Event::PointerButton { pos: more, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + let screen = Rect::from_min_size(Pos2::ZERO, size); + let mut texts = vec![]; + for events in [vec![Event::PointerMoved(more)], vec![press(true)], vec![press(false)], vec![]] { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| canvas::show(app, ui)); + out.textures_delta.clear(); + texts = shapes_text(&out.shapes.iter().map(|c| c.shape.clone()).collect::>()); + } + assert!(texts.iter().any(|(t, _)| t.trim() == "Hide Bar"), "More Options opens: {texts:?}"); + let names = |t: &[(String, Rect)]| t.iter().map(|(t, _)| t.trim().to_string()).collect::>(); + (names(&on_bar), names(&texts)) + }; + let (on_bar, menu) = listed(&mut app); + for label in ["Unite", "Duplicate"] { + assert!(!on_bar.iter().any(|t| t == label) && menu.iter().any(|t| t == label), "{label} in More Options: {menu:?}"); + } + show_action(&mut app, "unite", false); + let (on_bar, menu) = listed(&mut app); + assert!(!on_bar.iter().any(|t| t == "Unite") && !menu.iter().any(|t| t == "Unite"), "{on_bar:?} {menu:?}"); + assert!(on_bar.iter().chain(&menu).any(|t| t == "Duplicate"), "Duplicate is still offered: {on_bar:?} {menu:?}"); +} + +/// Every action and chip the bar offers, for every kind of selection and tool, has an id in Bar +/// Actions, and with all of them turned off the bar shows none of them but still shows, with More +/// Options. That covers Connect and Join (both `join`), the actions matched by the tool they switch +/// to (`editPath`, `drawPencil`, `smoothToolOptions`), the Smooth tool's Fidelity, Dynamic Text, +/// an Image Trace object's Expand, the Type tool's Fill with type selected and while it edits +/// type, and the Artboard tool's actions. +#[test] +fn every_action_the_bar_offers_can_be_turned_off() { + let dir = crate::tests_folder::Folder::new("ui-taskbar-actions"); + let line = |app: &mut VectorcraftApp| { + id(app.run("path.create", json!({"anchors": [{"x": 50, "y": 200}, {"x": 150, "y": 80}, {"x": 250, "y": 200}]})).unwrap()) + }; + let two = |app: &mut VectorcraftApp| { + let a = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 120, "height": 100})).unwrap()); + let b = id(app.run("shape.ellipse", json!({"x": 70, "y": 60, "width": 50, "height": 50})).unwrap()); + select(app, &[a, b]); + }; + type Setup<'a> = Box; + let cases: Vec<(&str, Setup, &[&str])> = vec![ + ( + "an open path", + Box::new(|app| { + let l = line(app); + select(app, &[l]); + }), + &["join", "editPath", "offsetPath", "simplify", "duplicate"], + ), + ( + "a path the Direct Selection tool selects whole", + Box::new(|app| { + let l = line(app); + select(app, &[l]); + app.run("tool.select", json!({"tool": "directSelection"})).unwrap(); + }), + &["join", "convertToCorner", "convertToSmooth", "simplify", "smooth", "duplicate"], + ), + ( + "anchors picked out", + Box::new(|app| { + let l = line(app); + app.run("tool.select", json!({"tool": "directSelection"})).unwrap(); + app.run("select.anchors", json!({"id": l, "anchors": [[0, 1]]})).unwrap(); + }), + &["removeAnchorPoints", "join", "cutPath", "convertToCorner", "convertToSmooth"], + ), + ("two paths", Box::new(|app| two(app)), &["group", "unite", "duplicate"]), + ( + "a group", + Box::new(|app| { + two(app); + app.run("object.group", json!({})).unwrap(); + }), + &["ungroup", "isolate", "duplicate"], + ), + ( + "a compound path", + Box::new(|app| { + two(app); + app.run("object.compoundPath.make", json!({})).unwrap(); + }), + &["editPath", "releaseCompoundPath", "duplicate"], + ), + ( + "a clipping group", + Box::new(|app| { + two(app); + let g = id(app.run("object.clippingMask.make", json!({})).unwrap()); + select(app, &[g]); + }), + &["editClippingPath", "releaseClippingMask", "duplicate"], + ), + ( + "point type", + Box::new(|app| { + let t = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello"})).unwrap()); + select(app, &[t]); + }), + &["createOutlines", "convertToAreaType", "dynamicText", "fill", "stroke", "lock"], + ), + ( + "the Type tool with type selected", + Box::new(|app| { + let t = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello"})).unwrap()); + select(app, &[t]); + app.run("tool.select", json!({"tool": "type"})).unwrap(); + }), + &["fill"], + ), + ( + "the Type tool editing type", + Box::new(|app| { + edited_type(app, "type"); + }), + &["fill"], + ), + ( + "area type", + Box::new(|app| { + let t = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello"})).unwrap()); + select(app, &[t]); + app.run("type.convertToAreaType", json!({})).unwrap(); + select(app, &[t]); + }), + &["createOutlines", "convertToPointType", "dynamicText"], + ), + ( + "type on a closed path", + Box::new(|app| { + let circle = id(app.run("path.create", json!({"d": "M100 300 A100 100 0 1 1 300 300 A100 100 0 1 1 100 300 Z"})).unwrap()); + let t = id(app.run("text.createInPath", json!({"path": circle, "mode": "onPath", "text": "Round", "at": [90, 300]})).unwrap()); + select(app, &[t]); + }), + &["createOutlines", "typeOnPathOptions", "centerOnTop", "centerOnBottom", "dynamicText"], + ), + ( + "an Image Trace object", + Box::new(|app| { + place_image(app, &dir); + app.run("imageTrace.make", json!({"params": {}})).unwrap(); + }), + &["expand", "duplicate"], + ), + ( + "an image", + Box::new(|app| { + place_image(app, &dir); + }), + &["imageTrace", "cropImage", "removeBackground", "duplicate"], + ), + ( + "an image with a path", + Box::new(|app| { + let img = place_image(app, &dir); + let r = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60})).unwrap()); + select(app, &[img, r]); + }), + &["group", "makeClippingMask", "duplicate"], + ), + ( + "a blank canvas", + Box::new(|app| { + let board = app.session.active().unwrap().doc.artboards[0].rect; + bar(app); + let view = app.view_mut().unwrap(); + (view.center, view.zoom) = (board.center(), 0.5); + }), + &["drawPencil", "placeImage"], + ), + ( + "a shape tool after drawing", + Box::new(|app| { + drag_with(app, "rectangle", (60.0, 60.0), (120.0, 120.0)); + }), + &["editPath"], + ), + ( + "the Smooth tool", + Box::new(|app| { + let e = id(app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 120, "height": 80})).unwrap()); + select(app, &[e]); + app.run("tool.select", json!({"tool": "smooth"})).unwrap(); + }), + &["fidelity", "smoothToolOptions"], + ), + ( + "the Artboard tool", + Box::new(|app| { + app.run("artboard.new", json!({"x": 420, "y": 0, "width": 200, "height": 200})).unwrap(); + app.run("tool.select", json!({"tool": "artboard"})).unwrap(); + }), + &["resizeArtboard", "duplicateArtboards", "rearrangeArtboards", "exportArtboards"], + ), + ]; + for (case, setup, expected) in cases { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + setup(&mut app); + let (ctx, _) = bar(&mut app); + let offered: Vec<(&str, Option<&str>)> = canvas::task_bar_offered(&ctx).into_iter().map(|(label, action, _)| (label, action)).collect(); + assert!(canvas::task_bar_rect(&ctx).is_some() && !offered.is_empty(), "{case}: the bar shows actions"); + for (label, action) in &offered { + assert!(action.is_some(), "{case}: {label} has no id in Bar Actions"); + } + let ids: Vec<&str> = offered.iter().filter_map(|(_, a)| *a).collect(); + for action in expected.iter() { + assert!(ids.contains(action), "{case}: {action} in {ids:?}"); + } + for action in &ids { + show_action(&mut app, action, false); + } + let (ctx, texts) = bar_texts(&mut app); + for (label, _) in &offered { + assert!(!has(&texts, label), "{case}: {label} is off: {texts:?}"); + } + // The bar still shows, with More Options, where Bar Actions turns them back on. + assert!(canvas::task_bar_rect(&ctx).is_some(), "{case}: the bar still shows"); + let names: Vec = buttons(&mut app).1.into_iter().map(|(n, _)| n).collect(); + assert!(names.iter().any(|n| n == "More Options"), "{case}: {names:?}"); + for (label, _) in &offered { + assert!(!names.iter().any(|n| n == label), "{case}: {label} is off: {names:?}"); + } + } +} + +/// Bar Actions lists a field's name without its colon, as each language writes it, and an item +/// that opens a dialog without its ellipsis. +#[test] +fn bar_actions_list_names_without_a_colon_or_an_ellipsis() { + let lang = |code| crate::i18n::Lang::from_code(code).unwrap(); + for (code, label, name) in + [("en", "Fidelity:", "Fidelity"), ("en", "Tool Options…", "Tool Options"), ("fr", "Fidelity:", "Fidélité"), ("ja", "Fidelity:", "精度")] + .into_iter() + .chain([("zh-hans", "Fidelity:", "精确度"), ("zh-hant", "Fidelity:", "精確度"), ("zh-hans", "Tool Options…", "工具选项")]) + { + let label = crate::i18n::tr(lang(code), label); + assert_eq!(canvas::bar_action_name(label), name, "{code}: {label:?}"); + } + assert_eq!(canvas::bar_action_name("Duplicate"), "Duplicate"); + assert_eq!(canvas::bar_action_name("Tool Options..."), "Tool Options"); + assert_eq!(canvas::bar_action_name("Offset Path."), "Offset Path."); + // The colon and the ellipsis go in either order, with or without a space between them. + for label in [ + "Tool Options...:", + "Tool Options... :", + "Tool Options: ...", + "Tool Options …:", + "Tool Options… :", + "Tool Options…\u{a0}:", + "Tool Options...\u{202f}:", + ] { + assert_eq!(canvas::bar_action_name(label), "Tool Options", "{label:?}"); + } +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 0924ab152d..f7935c2fd5 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -37,7 +37,7 @@ pub const BASIC: &[(&str, &[&[&str]])] = &[ ( "Shapes", &[ - &["rectangle", "roundedRectangle", "star", "lineSegment", "arc", "spiral", "rectangularGrid", "polarGrid", "flare"], + &["rectangle", "roundedRectangle", "star", "lineSegment", "arc", "threePointArc", "spiral", "rectangularGrid", "polarGrid", "flare"], &["ellipse", "circle", "curvatureCircle"], &["polygon"], &["shaper"], @@ -475,6 +475,8 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result crate::dialogs::shapes::open_options(app, tool), + // 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 // selected, the first one's settings, and OK draws the selected flares again. "flare" => Ok(crate::dialogs::flare_options::open(app, None)), diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 3ec5d25613..090156e861 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -27,11 +27,11 @@ pub use blend::{ reference_point_named, }; pub use buttons::{ - SPLIT_ARROW, flat_button, flat_button_fit, icon_button, icon_button_enabled, menu_item, menu_item_name, paint_icon_button, primary_button, - primary_button_enabled, secondary_button, split_button, split_button_named, toggle_icon, + SPLIT_ARROW, flat_button, flat_button_fit, icon_button, icon_button_enabled, menu_item, menu_item_hint, menu_item_name, paint_icon_button, + primary_button, primary_button_enabled, secondary_button, split_button, split_button_named, toggle_icon, }; pub(crate) use buttons::{ - button_width, flat_button_fit_width, icon_button_info, paint_icon_button_named, primary_button_width, secondary_button_width, + button_width, flat_button_fit_width, icon_button_info, menu_item_response, paint_icon_button_named, primary_button_width, secondary_button_width, }; #[cfg(test)] use chips::gradient_chip_colors; @@ -39,16 +39,18 @@ pub use chips::{ProxyClicks, chip_button, chip_button_named, fill_stroke_proxy, pub use color::{ FieldAxis, Live, MarkerResponse, RingResponse, SliderValue, WheelAxes, WheelResponse, channel_slider, channel_slider_named, channel_slider_stepped, channel_slider_valued, color_field, color_mesh, color_slider, color_slider_named, color_slider_stepped, - color_slider_valued, harmony_wheel, hex_field, hex_field_named, hsb32, hue_ring, region_texture, ring_markers, ring_square, segment_color, - segment_color_on, segmented_wheel, stepped_area, wheel_of, + color_slider_valued, harmony_wheel, hex_field, hex_field_named, hsb32, hue_ring, recolor_wheel, region_texture, ring_markers, ring_square, + segment_color, segment_color_on, segmented_wheel, stepped_area, wheel_of, }; -pub(crate) use color::{HEX_FIELD_CHARS, focus_by_pointer, hex_text, pointer_phase}; +pub(crate) use color::{HEX_FIELD_CHARS, color_rail_bar, focus_by_pointer, hex_text, pointer_phase}; pub use drag::{ PanelDrag, RowClick, SwatchRows, apply_row_click, art_drag_doc, art_drop, doc_preview, drag_art, drag_ghost, drag_source, drop_target_outline, ghost_row, row_click, }; #[cfg(test)] use dropdowns::combo_button_id; +#[cfg(test)] +pub(crate) use dropdowns::top_popup_shapes; pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field_named, combo_named, field_focused_in, menu_min_width, popover_is_open}; pub use dropdowns::{ dropdown, dropdown_icon_names, dropdown_icon_names_sized, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, diff --git a/crates/ui-egui/src/widgets/buttons.rs b/crates/ui-egui/src/widgets/buttons.rs index 19062eaf4c..0de8ded5e1 100644 --- a/crates/ui-egui/src/widgets/buttons.rs +++ b/crates/ui-egui/src/widgets/buttons.rs @@ -213,9 +213,30 @@ pub fn menu_item(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> bool menu_item_name(ui, tl!(label), enabled, checked) } +/// [`menu_item`] that returns the row's response, for a caller that needs to know how it was +/// clicked. +pub(crate) fn menu_item_response(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> egui::Response { + menu_item_name_response(ui, tl!(label), enabled, checked) +} + /// [`menu_item`] for a name that is user or file data (a library, a recent URL), never translated. /// Like the menu bar's items, the row lights up under the pointer. pub fn menu_item_name(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> bool { + menu_item_name_response(ui, label, enabled, checked).clicked() +} + +/// [`menu_item_name`] that returns the row's response. +fn menu_item_name_response(ui: &mut Ui, label: &str, enabled: bool, checked: bool) -> egui::Response { let text = if checked { format!("✓ {label}") } else { format!(" {label}") }; - ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(text).size(12.5)).frame_when_inactive(false)).clicked() + ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(text).size(12.5)).frame_when_inactive(false)) +} + +/// [`menu_item`] that shows `hint` under the pointer while the row is disabled, to say why it is +/// gray. +pub fn menu_item_hint(ui: &mut Ui, label: &str, enabled: bool, checked: bool, hint: &str) -> bool { + let label = tl!(label); + let text = if checked { format!("✓ {label}") } else { format!(" {label}") }; + ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(text).size(12.5)).frame_when_inactive(false)) + .on_disabled_hover_text(tl!(hint)) + .clicked() } diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index 882e236363..a14689b57c 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -279,6 +279,11 @@ fn rail_step(ui: &Ui, id: egui::Id, focused: bool, always: bool, s: &SliderValue (v != from || (end && v != s.value) || (always && asked)).then_some(if exact { v } else { round_to(v, STEP_DECIMALS).clamp(lo, hi) }) } +/// The colored bar inside the rail `rect` of [`color_slider_stepped`] and its siblings. +pub(crate) fn color_rail_bar(rect: Rect) -> Rect { + Rect::from_min_size(pos2(rect.left() + 4.0, rect.top() + 4.0), vec2(rect.width() - 8.0, 7.0)) +} + /// The rail of [`color_slider_valued`] with the id `id`: its response, the new value from 0 to 1 /// that a click or drag gives and the phase. fn color_rail( @@ -292,7 +297,7 @@ fn color_rail( ) -> (Response, Option, Live) { let t = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(vec2(width, 22.0), Sense::hover()); - let bar = Rect::from_min_size(pos2(rect.left() + 4.0, rect.top() + 4.0), vec2(width - 8.0, 7.0)); + let bar = color_rail_bar(rect); let resp = ui.interact(rect, id, Sense::click_and_drag()); gradient_strip(ui, bar, (bar.width() / 2.0).ceil().max(2.0) as usize, false, track); ui.painter().rect_stroke(bar, 0.0, Stroke::new(1.0, t.border), StrokeKind::Outside); @@ -1097,6 +1102,12 @@ pub struct WheelResponse { /// A click on the wheel: the color whose marker is within reach of it (if any), and the hue /// (degrees) and the saturation (or brightness) under the pointer (1 past the wheel's edge). pub clicked: Option<(Option, [f32; 2])>, + /// A right-click on the wheel, or on a marker past its edge: the color whose marker is within + /// reach of it (if any), the color on whose line from the center it is (when it is on no + /// marker), and the hue (degrees) and saturation under the pointer. + pub secondary: Option<(Option, Option, [f32; 2])>, + /// The wheel's own response, for a right-click menu. + pub response: Option, } /// The harmony wheel of Recolor Artwork's Edit tab and the Color Themes panel: a hue and saturation @@ -1104,25 +1115,60 @@ pub struct WheelResponse { /// marker per colour joined to the centre (the selected colour, `base`, larger) and a Brightness /// slider for the selected colour below it. pub fn harmony_wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option) -> WheelResponse { - wheel_of(ui, id, size, colors, base, false, WheelAxes::HueSaturation) + wheel_of(ui, id, size, colors, base, base, false, WheelAxes::HueSaturation) } -/// [`harmony_wheel`] drawn as solid patches (24 hues by 5 saturations, each in its -/// [`segment_color`]). The markers sit at their colors' own hue and +/// Recolor Artwork's wheel: [`harmony_wheel`] with the base color's marker (`base`) larger and the +/// selected color's (`selected`, when another) ringed, at the selected color's brightness, with the +/// Brightness slider for it. With `segmented` it is drawn as solid patches (24 hues by 5 +/// saturations, each in its [`segment_color`]); the markers sit at their colors' own hue and /// saturation, and a drag moves them as freely as on the smooth wheel. -pub fn segmented_wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option) -> WheelResponse { - wheel_of(ui, id, size, colors, base, true, WheelAxes::HueSaturation) +#[allow(clippy::too_many_arguments)] +pub fn recolor_wheel( + ui: &mut Ui, + id: &str, + size: f32, + colors: &[Color], + base: Option, + selected: Option, + segmented: bool, + axes: WheelAxes, +) -> WheelResponse { + wheel_of(ui, id, size, colors, base, selected.or(base), segmented, axes) } -/// [`harmony_wheel`], or with `segmented` [`segmented_wheel`], showing `axes`. With +/// The distance from `p` to the segment from `a` to `b`. +fn segment_distance(p: egui::Pos2, a: egui::Pos2, b: egui::Pos2) -> f32 { + let ab = b - a; + let len2 = ab.length_sq(); + let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 }; + p.distance(a + ab * t) +} + +pub fn segmented_wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option) -> WheelResponse { + wheel_of(ui, id, size, colors, base, base, true, WheelAxes::HueSaturation) +} + +/// [`harmony_wheel`], [`recolor_wheel`], or with `segmented` [`segmented_wheel`], showing `axes`. The +/// big marker is `base`'s, and the wheel's background and the slider under it are `selected`'s. With /// [`WheelAxes::HueBrightness`] the distance from the center is brightness (black at the center, /// full brightness at the edge, a ring of patches per 20% on the segmented wheel), the wheel is drawn /// at the selected colour's saturation (full without one), a marker drag sets hue and brightness, /// and the slider under the wheel is a Saturation slider. -pub fn wheel_of(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option, segmented: bool, axes: WheelAxes) -> WheelResponse { +#[allow(clippy::too_many_arguments)] +pub fn wheel_of( + ui: &mut Ui, + id: &str, + size: f32, + colors: &[Color], + base: Option, + selected: Option, + segmented: bool, + axes: WheelAxes, +) -> WheelResponse { let t = Tokens::get(ui.ctx()); let mut out = WheelResponse::default(); - let base_hsb = base.and_then(|b| colors.get(b)).map(Color::to_hsb); + let base_hsb = selected.and_then(|b| colors.get(b)).map(Color::to_hsb); let (radial, other) = (axes.radial(), axes.other()); // The component the wheel does not show: the slider's value, and the wheel's background at it. let o = base_hsb.map_or(1.0, |c| c[other]); @@ -1144,6 +1190,24 @@ pub fn wheel_of(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option painter.line_segment([c, p], Stroke::new(1.0, Color32::from_white_alpha(160))); painter.circle(p, if big { 8.0 } else { 5.5 }, crate::panels::c32(col), Stroke::new(1.5, Color32::WHITE)); painter.circle_stroke(p, if big { 9.0 } else { 6.5 }, Stroke::new(1.0, Color32::BLACK)); + if Some(i) == selected && selected != base { + painter.circle_stroke(p, 8.5, Stroke::new(1.5, t.accent)); + } + } + // A right-click: the marker under it, or else the line from the center to a marker. + if resp.secondary_clicked() + && let Some(p) = resp.interact_pointer_pos() + { + let near = colors.iter().map(at).enumerate().map(|(i, m)| (i, m.distance(p))).filter(|x| x.1 <= 14.0).min_by(|a, b| a.1.total_cmp(&b.1)); + let dv = p - c; + if dv.length() <= r || near.is_some() { + let line = near.is_none().then(|| { + let on = colors.iter().map(at).enumerate().map(|(i, m)| (i, segment_distance(p, c, m))).filter(|x| x.1 <= 4.0); + on.min_by(|a, b| a.1.total_cmp(&b.1)).map(|x| x.0) + }); + let h = (-dv.y).atan2(dv.x).to_degrees().rem_euclid(360.0); + out.secondary = Some((near.map(|x| x.0), line.flatten(), [h, (dv.length() / r).clamp(0.0, 1.0)])); + } } // Drag a marker: the nearest one within reach of the press. let drag = ui.scope_id().with((id, "drag")); @@ -1173,6 +1237,7 @@ pub fn wheel_of(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option } let name = if segmented { tl!("Segmented color wheel") } else { tl!("Color wheel") }; resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Slider, ui.is_enabled(), name)); + out.response = Some(resp); }); ui.add_space(6.0); ui.horizontal(|ui| { @@ -1181,7 +1246,7 @@ pub fn wheel_of(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option ui.add_sized([70.0, 22.0], egui::Label::new(egui::RichText::new(name).color(t.text_dim))); // Screen readers get the value in percent, as the Color panel's HSB fields show it. let shown = SliderValue::field((f64::from(o) * 100.0).round(), 0.0..=100.0, "%", 0); - if let (Some(b), Some(hsb)) = (base, base_hsb) + if let (Some(b), Some(hsb)) = (selected, base_hsb) && let (Some(nv), _) = color_slider_valued(ui, (id, key), name, Some(shown), o, size, &|x| { let [h, s, v] = axes.hsb(hsb[0], hsb[radial], x); crate::panels::c32(&Color::from_hsb(h, s, v)) diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index 1baf1f4094..b440007a80 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -149,9 +149,10 @@ fn option_row<'a>(ui: &mut Ui, enabled: bool, selected: bool, atoms: impl egui:: response } -/// The id [`craft_ui::ComboBox::from_id_salt`] gives its button in this `Ui`: `from_id_salt` -/// stores `IdSalt::new(salt)` and hashes it once more with the scope, so the app must hash `id` -/// the same way to read the button's focus and open state before it is drawn. +/// The id of the button of [`combo_atoms_named`] in this `Ui`, the one +/// [`craft_ui::ComboBox::from_id_salt`] gives its button: `from_id_salt` stores +/// `IdSalt::new(salt)` and hashes it once more with the scope. The app reads the button's focus and +/// open state with it before the button is drawn. pub(super) fn combo_button_id(ui: &Ui, id: &impl std::hash::Hash) -> egui::Id { ui.make_persistent_id(egui::IdSalt::new(HashOnly(id))) } @@ -206,9 +207,8 @@ fn combo_atoms_named<'a, R>( if opening { ui.data_mut(|d| d.insert_temp(opened_key, pass)); } - // The menu measures itself against the whole screen on the pass it opens and takes - // the room beside its field on the next one, so the current option is scrolled into - // view on both. + // The list is laid out unseen to measure it on the pass it opens and placed on the + // next one, so the current option is scrolled into view on both. let settling = ui.data(|d| d.get_temp::(opened_key)).is_some_and(|p| pass <= p + 1); // A list drawn inside this one's rows finds its own record, and this one's comes back after it. let outer = if settling { OPENING.replace(Some(Opening::default())) } else { OPENING.take() }; @@ -238,17 +238,14 @@ fn combo_atoms_named<'a, R>( chosen }; let enter_for_combo = ui.memory(|m| m.has_focus(button_id)) || craft_ui::ComboBox::is_open(ui.ctx(), button_id); - let response = craft_ui::ComboBox::from_id_salt(HashOnly(&id)) - .selected_text(current) - .width(width - 4.0) - .height(ui.spacing().combo_height) - .show_ui(ui, list); + let response = combo_button(ui, button_id, current, width - 4.0); + let shown = combo_list(ui, &response, list); // The button or open list handles Enter before the modal can accept it. if enter_for_combo { ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); } - let _ = name_field(label_field(response.response.clone(), label), name); - let chosen = response.inner.flatten(); + let _ = name_field(label_field(response, label), name); + let chosen = shown.flatten(); // egui closes the list on a click of the pointer only: an option picked with Space or // Enter closes it here, and the combo gives the keyboard back, so that Enter reaches the // dialog's OK (#2789). @@ -261,6 +258,178 @@ fn combo_atoms_named<'a, R>( .inner } +/// The button of [`combo_atoms_named`] with the id `button_id`, at least `width` wide, showing +/// `current`: [`craft_ui::ComboBox`]'s button, with its look, its tooltip for a value cut short and +/// its role for screen readers. It is drawn here so that its list opens in [`combo_list`]. +fn combo_button<'a>(ui: &mut Ui, button_id: egui::Id, current: impl egui::IntoAtoms<'a>, width: f32) -> Response { + use egui::class::HasClasses as _; + use egui::{AtomExt as _, NumExt as _}; + let open = egui::Popup::is_id_open(ui.ctx(), button_id.with("popup")); + let mut classes = egui::class::Classes::default(); + classes.add_class(craft_ui::ComboBox::CLASS); + classes.set_class(craft_ui::ComboBox::CLASS_OPEN, open); + let egui::widget_style::ButtonStyle { atom_layout } = ui.widget_style(button_id, &classes); + let visuals = if open { + ui.visuals().widgets.open + } else if let Some(response) = ui.ctx().read_response(button_id) { + *ui.style().interact(&response) + } else { + ui.visuals().widgets.inactive + }; + let min_size = vec2(width, 0.0).at_least(atom_layout.min_size); + let current = current.into_atoms(); + let text = current.text().map(String::from).unwrap_or_default(); + let rtl = ui.style().right_to_left; + // The combo box's arrow: a downward triangle. + let arrow = egui::Atom::paint(Vec2::splat(ui.spacing().icon_width), move |ui, args| { + let rect = args.rect.expand(visuals.expansion); + let rect = Rect::from_center_size(rect.center(), vec2(rect.width() * 0.7, rect.height() * 0.45)); + ui.painter().add(egui::Shape::rotated_triangle(rect, 0.0, visuals.fg_stroke.color)); + }) + .atom_grow(true) + .atom_align(if rtl { egui::Align2::LEFT_CENTER } else { egui::Align2::RIGHT_CENTER }); + let button = atom_layout + .apply( + egui::WidgetAtom::new((current, arrow)) + .id(button_id) + .sense(Sense::click()) + .fallback_font(egui::TextStyle::Button) + .wrap_mode(ui.wrap_mode()) + .direction(if rtl { egui::Direction::RightToLeft } else { egui::Direction::LeftToRight }), + ) + .min_size(min_size) + .measure(ui, ui.available_size()); + let elided = button.container.iter_texts().any(|galley| galley.elided); + let response = button.allocate(ui).paint(ui).response; + // A value cut short shows in full on hover, as a truncated `Label`'s does. + let response = if elided { + response.on_hover_ui(|ui| { + ui.set_max_width(ui.spacing().tooltip_width); + ui.add(egui::Label::new(text.as_str()).wrap()); + }) + } else { + response + }; + response.widget_info(|| egui::WidgetInfo { + enabled: ui.is_enabled(), + current_text_value: Some(text.clone()), + ..egui::WidgetInfo::new(egui::Role::ComboBox) + }); + response +} + +/// The list of [`combo_atoms_named`] while it is open, drawn by `list` in a popup of its own that +/// opens from `button` and takes the whole list whenever the window has room for it (#5941): below +/// the button when it fits there, above it when it fits there instead, and otherwise moved up from +/// below, over the button, until it ends at the bottom bars. It stays above the bottom bars +/// ([`menu_floor`]), and a list taller than the room above them scrolls. A click closes +/// the list, except a click on its scroll bar, which scrolls it. Returns what `list` returned, or +/// `None` while the list is closed. +fn combo_list(ui: &Ui, button: &Response, list: impl FnOnce(&mut Ui) -> R) -> Option { + let ctx = ui.ctx(); + let id = button.id.with("popup"); + let style = egui::style::StyleModifier::new(|style| { + egui::containers::menu::menu_style(style); + style.spacing.scroll = list_scroll_style(); + }); + // The id of the list's scroll area. egui senses its vertical bar under the area's id with the + // axis, 1, and names the widget a click went to at the start of the pass. + let area_key = id.with("scroll-area-id"); + let on_bar = + ctx.data(|d| d.get_temp::(area_key)).is_some_and(|area| ctx.interaction_snapshot(|s| s.clicked == Some(area.with(1_usize)))); + let close = if on_bar { egui::PopupCloseBehavior::IgnoreClicks } else { egui::PopupCloseBehavior::CloseOnClick }; + let popup = egui::Popup::menu(button).id(id).width(button.rect.width()).style(style.clone()).close_behavior(close); + let screen = ctx.content_rect(); + // The list stops above the bottom bars, as other menus do (#2086). + let floor = menu_floor(ctx).min(screen.bottom()); + // The room on each side of the rect the popup opens from: the part of the button in view. + let anchor = popup.get_anchor_rect().unwrap_or(button.rect); + let below = floor - anchor.bottom(); + let above = anchor.top() - screen.top(); + // The list's size from its last pass: egui lays a popup out unseen on the pass it opens, so the + // list is measured before it is placed. A right-to-left layout lines the list up with the + // button's right edge, as egui's menus do. + let rtl = ui.style().right_to_left; + let expected = popup.get_expected_size(); + let (align, popup) = match expected { + Some(size) if size.y > below && size.y <= above => (if rtl { egui::RectAlign::TOP_END } else { egui::RectAlign::TOP_START }, popup), + // A list too tall for either side moves up from below until it ends at the floor. + Some(size) if size.y > below => { + let top = (floor - size.y).max(screen.top()); + let from = Rect::from_min_max(egui::pos2(anchor.left(), top), egui::pos2(anchor.right(), top)); + (if rtl { egui::RectAlign::BOTTOM_END } else { egui::RectAlign::BOTTOM_START }, popup.anchor(from)) + } + _ => (if rtl { egui::RectAlign::BOTTOM_END } else { egui::RectAlign::BOTTOM_START }, popup), + }; + let mut popup_style = (*ctx.global_style()).clone(); + style.apply(&mut popup_style); + let margins = egui::Frame::popup(&popup_style).total_margin().sum(); + let height = (floor - screen.top() - margins.y).max(ui.spacing().interact_size.y); + // A list that was wider than the window keeps its scroll bar in view: until it closes, it is no + // wider than it measured or than the window, its names cut short and shown in full on hover. + // Only a size measured while the list is open counts: egui keeps the last one after it closes. + // The width it needs is its rows' width on the last pass before it was narrowed, with its + // margins, and the bar's column while the rows scroll. + let too_wide_key = id.with("too-wide"); + let natural_key = id.with("natural-width"); + let scrolls_key = id.with("scrolls"); + let open_last_pass = ctx.read_response(id).is_some(); + if popup.get_expected_size().is_some_and(|size| open_last_pass && size.x > screen.width()) { + // The first measurement is kept: later ones are of the list already narrowed. + ctx.data_mut(|d| { + if d.get_temp::(too_wide_key).is_none() { + let rows = d.get_temp::(natural_key).unwrap_or(screen.width()); + d.insert_temp(too_wide_key, rows); + } + }); + } + let (measured, scrolls) = ctx.data(|d| (d.get_temp::(too_wide_key), d.get_temp::(scrolls_key).unwrap_or(false))); + let too_wide = measured.is_some(); + let shown = popup.align(align).align_alternatives(&[]).show(|ui| { + if let Some(rows) = measured { + let bar = if scrolls { list_scroll_style().allocated_width() } else { 0.0 }; + ui.set_max_width((rows + bar).min(screen.width() - margins.x).max(0.0)); + } + ui.set_min_width(ui.available_width()); + // A popup offers its contents the height it had on its last pass; the list is offered the + // window's instead. + ui.set_max_height(height); + // Labels widen a narrow list rather than wrap, as in egui's combo box. + ui.style_mut().wrap_mode = Some(if too_wide { egui::TextWrapMode::Truncate } else { egui::TextWrapMode::Extend }); + let painted = ui.ctx().graphics(|g| g.get(ui.layer_id()).map_or(0, |shapes| shapes.all_entries().len())); + let shown = egui::ScrollArea::vertical().max_height(height).show(ui, list); + if too_wide { + show_shortened_rows(ui, painted); + } + ui.data_mut(|d| { + if !too_wide { + d.insert_temp(natural_key, shown.content_size.x); + } + d.insert_temp(scrolls_key, shown.content_size.y > shown.inner_rect.height()); + d.insert_temp(area_key, shown.id); + }); + shown.inner + }); + if shown.is_some() { + ctx.accesskit_node_builder(id, |node| node.set_role(egui::Role::ListBox)); + } else { + ctx.data_mut(|d| { + d.remove::(too_wide_key); + d.remove::(natural_key); + d.remove::(scrolls_key); + }); + } + shown.map(|r| r.inner) +} + +/// The shapes painted so far in this pass on the topmost popup that was shown in the last one, such +/// as an open dropdown list, without what lies under it. Read at the end of a test's UI. +#[cfg(test)] +pub(crate) fn top_popup_shapes(ctx: &egui::Context) -> Vec { + let top = ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last()); + top.map_or_else(Vec::new, |layer| ctx.graphics(|g| g.get(layer).map(|p| p.all_entries().cloned().collect()).unwrap_or_default())) +} + /// The recessed combo box of [`dropdown`] showing `current`, whose menu keeps a search field and /// filters in place over a list that scrolls (the font menu and the shortcut import's target /// picker, #555). `menu` shows the menu with one of [`craft_ui::combo::Menu`]'s header forms and diff --git a/crates/ui-egui/src/widgets/look_tests.rs b/crates/ui-egui/src/widgets/look_tests.rs index 4ee9e6f412..286be3f10c 100644 --- a/crates/ui-egui/src/widgets/look_tests.rs +++ b/crates/ui-egui/src/widgets/look_tests.rs @@ -133,10 +133,13 @@ fn a_dropdown_in_a_short_window_opens_with_its_current_option_in_view() { for (height, above, current) in [(260.0, 117.0, 19), (260.0, 117.0, 10), (180.0, 77.0, 10), (180.0, 77.0, 3)] { let ctx = themed(Default::default()); let field = std::cell::Cell::new(Rect::NOTHING); + let popup = std::cell::RefCell::new(vec![]); let mut add = |ui: &mut Ui| { ui.add_space(above); field.set(ui.horizontal(|ui| dropdown_names(ui, "short-list", labels[current], &labels, 160.0)).response.rect); + popup.replace(super::top_popup_shapes(ui.ctx())); }; + // The shapes of the open list, without the field under it. let mut run = |time: f64, events: Vec| { let raw = egui::RawInput { time: Some(time), @@ -146,7 +149,7 @@ fn a_dropdown_in_a_short_window_opens_with_its_current_option_in_view() { }; let mut out = ctx.run_ui(raw, &mut add); out.textures_delta.clear(); - out.shapes + popup.take() }; run(0.0, vec![]); let at = field.get().center(); @@ -206,6 +209,7 @@ fn own_rows_reopen(height: f32, above: f32, wheel: f32, row: &str) { let ctx = themed(Default::default()); let field = std::cell::Cell::new(Rect::NOTHING); let current = std::cell::RefCell::new(String::from("Row 00")); + let popup = std::cell::RefCell::new(vec![]); let mut add = |ui: &mut Ui| { ui.add_space(above); let shown = current.borrow().clone(); @@ -224,8 +228,10 @@ fn own_rows_reopen(height: f32, above: f32, wheel: f32, row: &str) { current.replace(items[i].clone()); } field.set(r.response.rect); + popup.replace(super::top_popup_shapes(ui.ctx())); }; let mut time = 0.0; + // The shapes of the open list, without the field under it. let mut run = |events: Vec| { time += 0.1; let raw = egui::RawInput { @@ -236,7 +242,7 @@ fn own_rows_reopen(height: f32, above: f32, wheel: f32, row: &str) { }; let mut out = ctx.run_ui(raw, &mut add); out.textures_delta.clear(); - out.shapes + popup.take() }; // The rows that show whole, with their tops: inside the open list and the clip they are painted // in. @@ -298,10 +304,12 @@ fn own_rows_reopen(height: f32, above: f32, wheel: f32, row: &str) { } let scrolled = rows(clipped); assert!(has(&scrolled, row), "{case}: the wheel scrolls {row} into view: {scrolled:?}"); - // Closed and opened again twice: each time its rows are where they were when it closed. + // Closed and opened again twice: each time its rows are where they were when it closed. Escape + // closes it: a list taller than the room beside its field covers the field. + let escape = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; for time in ["first", "second"] { - run(vec![egui::Event::PointerMoved(at), press(true)]); - run(vec![press(false)]); + run(vec![escape(true)]); + run(vec![escape(false)]); run(vec![]); let reopened = rows(open(&mut run)); assert_eq!(reopened, scrolled, "{case}: the list opens again where it was scrolled, the {time} time"); @@ -804,6 +812,517 @@ fn kerning_reads_parentheses_around_its_text_with_a_manual_value_too() { } } +/// Long dropdown lists use the window's room instead of stopping at `combo_height` (200 pt), and +/// show a solid scroll bar without hovering when the list still overflows. +#[test] +fn a_long_dropdown_uses_window_room_and_shows_its_scroll_bar_when_clipped() { + let items: Vec = (0..20).map(|i| format!("Format {i:02}")).collect(); + let labels: Vec<&str> = items.iter().map(String::as_str).collect(); + let run = |win_h: f32| { + let ctx = themed(Default::default()); + let button_rect = std::cell::Cell::new(Rect::NOTHING); + let mut draw = |ui: &mut Ui| { + ui.add_space(16.0); + ui.horizontal(|ui| { + ui.add_space(16.0); + let before = ui.next_widget_position(); + let _ = dropdown_names(ui, "long-formats", labels[0], &labels, 160.0); + button_rect.set(Rect::from_min_size(before, vec2(160.0, 26.0))); + }); + }; + let mut step = |time: f64, events: Vec| { + let raw = egui::RawInput { + time: Some(time), + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, win_h))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, &mut draw); + out.textures_delta.clear(); + out.shapes + }; + step(0.0, vec![]); + let at = button_rect.get().center(); + let click = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + step(0.1, vec![egui::Event::PointerMoved(at), click(true)]); + step(0.2, vec![click(false)]); + // Move the pointer away so the scroll bar is dormant, not hovered, and let the popup settle. + step(0.3, vec![egui::Event::PointerMoved(pos2(350.0, 10.0))]); + let mut clipped = vec![]; + for i in 4..10 { + clipped = step(f64::from(i) * 0.1, vec![]); + } + (ctx, clipped) + }; + + // In a tall window, all 20 items show without stopping at the 200 pt cap. + let (_tall_ctx, tall_shapes) = run(720.0); + let mut texts = vec![]; + fn collect_text(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| collect_text(s, out)), + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + _ => {} + } + } + for c in &tall_shapes { + collect_text(&c.shape, &mut texts); + } + assert!(texts.iter().any(|t| t == "Format 19"), "the 20th option is shown without scrolling: {texts:?}"); + + // In a short window where the list overflows, a solid scroll bar is drawn even while dormant. + let (short_ctx, short_shapes) = run(220.0); + let mut short_texts = vec![]; + for c in &short_shapes { + collect_text(&c.shape, &mut short_texts); + } + assert!(!short_texts.iter().any(|t| t == "Format 19"), "the list overflows the 220 pt window"); + let popup = short_ctx + .memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id))) + .expect("the popup is open"); + let mut bar_rects = vec![]; + fn collect_rects(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| collect_rects(s, out)), + egui::Shape::Rect(r) => out.push(r.clone()), + _ => {} + } + } + for c in &short_shapes { + collect_rects(&c.shape, &mut bar_rects); + } + let has_scroll_bar = bar_rects.iter().any(|r| { + r.fill != Color32::TRANSPARENT + && r.rect.width() <= list_scroll_style().bar_width + 1.0 + && r.rect.height() >= 12.0 + && r.rect.height() < popup.height() + && r.rect.right() <= popup.right() + && r.rect.left() >= popup.right() - list_scroll_style().allocated_width() - 8.0 + }); + assert!(has_scroll_bar, "the overflowing dropdown draws its scroll bar without hover in {popup:?}"); +} + +// #5941: a drop-down list stopped at the room on one side of its field, so a window with room for +// the whole list still cut it short. The list opens below its field when it fits there, above it +// when it fits there instead, and otherwise moves up from below into the window over its field; +// each time every option shows whole, inside the window. +#[test] +fn a_dropdown_list_shows_every_option_when_the_window_has_room() { + let items: Vec = (0..20).map(|i| format!("Option {i:02}")).collect(); + let labels: Vec<&str> = items.iter().map(String::as_str).collect(); + // (window height, space above the field, where the list goes) + for (height, above, side) in [(700.0, 16.0, "below"), (700.0, 650.0, "above"), (640.0, 300.0, "over")] { + let case = format!("{height} pt window, field {above} pt down"); + let ctx = themed(Default::default()); + let field = std::cell::Cell::new(Rect::NOTHING); + let popup = std::cell::RefCell::new(vec![]); + let mut add = |ui: &mut Ui| { + ui.add_space(above); + field.set(ui.horizontal(|ui| dropdown_names(ui, "fit-list", labels[0], &labels, 160.0)).response.rect); + popup.replace(super::top_popup_shapes(ui.ctx())); + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(400.0, height)); + // The shapes of the open list, without the field under it. + let mut run = |time: f64, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }, &mut add); + out.textures_delta.clear(); + popup.take() + }; + run(0.0, vec![]); + let at = field.get().center(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(0.1, vec![egui::Event::PointerMoved(at), press(true)]); + run(0.2, vec![press(false)]); + run(0.3, vec![egui::Event::PointerMoved(pos2(390.0, 2.0))]); + let mut clipped = vec![]; + for i in 4..10 { + clipped = run(f64::from(i) * 0.1, vec![]); + } + let list = ctx + .memory(|m| { + m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id)) + }) + .expect("the list is open"); + assert!(screen.contains_rect(list), "{case}: the list {list:?} is inside the window"); + let field = field.get(); + // The list opens from the button, 1 pt inside the field's border. + match side { + "below" => assert!(list.top() >= field.bottom() - 1.5, "{case}: the list {list:?} opens below the field {field:?}"), + "above" => assert!(list.bottom() <= field.top() + 1.5, "{case}: the list {list:?} opens above the field {field:?}"), + _ => assert!(list.top() < field.bottom() && list.bottom() > field.top(), "{case}: the list {list:?} covers the field {field:?}"), + } + let mut texts = vec![]; + fn flat(s: &egui::Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, clip, out)), + egui::Shape::Text(t) => out.push((t.galley.text().to_owned(), t.visual_bounding_rect(), clip)), + _ => {} + } + } + clipped.iter().for_each(|c| flat(&c.shape, c.clip_rect, &mut texts)); + let whole: Vec<&str> = labels + .iter() + .copied() + .filter(|name| { + texts.iter().any(|(s, r, clip)| s == name && list.contains_rect(*r) && r.top() >= clip.top() && r.bottom() <= clip.bottom()) + }) + .collect(); + assert_eq!(whole, labels, "{case}: every option shows whole in {list:?}"); + } +} + +// #5941: a drop-down list stops above the bottom bars, as other menus do (#2086). In a 700 pt window +// whose bars start at 640 pt, the list opens below a field near the top, and from a field in the +// middle it moves up over the field until it ends at the bars; each time every option shows whole. +#[test] +fn a_dropdown_list_stops_above_the_bottom_bars() { + let items: Vec = (0..20).map(|i| format!("Option {i:02}")).collect(); + let labels: Vec<&str> = items.iter().map(String::as_str).collect(); + let floor = 640.0; + for above in [16.0, 300.0] { + let case = format!("field {above} pt down"); + let ctx = themed(Default::default()); + let field = std::cell::Cell::new(Rect::NOTHING); + let popup = std::cell::RefCell::new(vec![]); + let mut add = |ui: &mut Ui| { + set_menu_floor(ui.ctx(), floor); + ui.add_space(above); + field.set(ui.horizontal(|ui| dropdown_names(ui, "floor-list", labels[0], &labels, 160.0)).response.rect); + popup.replace(super::top_popup_shapes(ui.ctx())); + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 700.0)); + let mut run = |time: f64, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }, &mut add); + out.textures_delta.clear(); + popup.take() + }; + run(0.0, vec![]); + let at = field.get().center(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(0.1, vec![egui::Event::PointerMoved(at), press(true)]); + run(0.2, vec![press(false)]); + run(0.3, vec![egui::Event::PointerMoved(pos2(390.0, 2.0))]); + let mut clipped = vec![]; + for i in 4..10 { + clipped = run(f64::from(i) * 0.1, vec![]); + } + let list = ctx + .memory(|m| { + m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id)) + }) + .expect("the list is open"); + assert!(list.top() >= 0.0 && list.bottom() <= floor + 0.5, "{case}: the list {list:?} ends above the bars at {floor}"); + let mut texts = vec![]; + fn flat(s: &egui::Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, clip, out)), + egui::Shape::Text(t) => out.push((t.galley.text().to_owned(), t.visual_bounding_rect(), clip)), + _ => {} + } + } + clipped.iter().for_each(|c| flat(&c.shape, c.clip_rect, &mut texts)); + let whole: Vec<&str> = labels + .iter() + .copied() + .filter(|name| { + texts.iter().any(|(s, r, clip)| s == name && list.contains_rect(*r) && r.top() >= clip.top() && r.bottom() <= clip.bottom()) + }) + .collect(); + assert_eq!(whole, labels, "{case}: every option shows whole in {list:?}"); + } +} + +// #5941: a click on the scroll bar's track of an open drop-down list scrolls it and leaves it open, +// so an option it scrolled into view can be picked. A list closed by that click would open again +// with its current option in view. +#[test] +fn a_click_on_a_dropdown_lists_scroll_bar_scrolls_it_and_leaves_it_open() { + let items: Vec = (0..40).map(|i| format!("Option {i:02}")).collect(); + let labels: Vec<&str> = items.iter().map(String::as_str).collect(); + let ctx = themed(Default::default()); + let field = std::cell::Cell::new(Rect::NOTHING); + let picked = std::cell::Cell::new(None); + let popup = std::cell::RefCell::new(vec![]); + let mut add = |ui: &mut Ui| { + ui.add_space(16.0); + let r = ui.horizontal(|ui| dropdown_names(ui, "bar-click", labels[0], &labels, 160.0)); + field.set(r.response.rect); + if let Some(i) = r.inner { + picked.set(Some(i)); + } + popup.replace(super::top_popup_shapes(ui.ctx())); + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let mut time = 0.0; + // The options that show whole on the open list, with their rects, and the scroll bar's rects. + let mut run = |events: Vec| { + time += 0.1; + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }, &mut add); + out.textures_delta.clear(); + let (mut texts, mut bars) = (vec![], vec![]); + fn flat(s: &egui::Shape, clip: Rect, out: &mut Vec<(String, Rect)>, bars: &mut Vec) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, clip, out, bars)), + egui::Shape::Text(t) => { + let r = t.visual_bounding_rect(); + if r.top() >= clip.top() && r.bottom() <= clip.bottom() { + out.push((t.galley.text().to_owned(), r)); + } + } + egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => bars.push(r.rect), + _ => {} + } + } + popup.take().iter().for_each(|c| flat(&c.shape, c.clip_rect, &mut texts, &mut bars)); + (texts, bars) + }; + let list_rect = || { + ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id))) + }; + let click = + |at: Pos2, pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(vec![]); + let at = field.get().center(); + run(vec![egui::Event::PointerMoved(at), click(at, true)]); + run(vec![click(at, false)]); + let (mut before, mut bars) = (vec![], vec![]); + for _ in 0..4 { + (before, bars) = run(vec![]); + } + assert!(list_rect().is_some(), "the list is open"); + assert!(before.iter().any(|(s, _)| s == "Option 00"), "the list opens at its first option: {before:?}"); + // The track, below the handle: near the bottom of the tallest bar rect drawn (the track). + let bar = bars + .iter() + .copied() + .max_by(|a, b| a.height().total_cmp(&b.height())) + .unwrap_or_else(|| panic!("the list {:?} draws its scroll bar: {before:?}", list_rect())); + let track = pos2(bar.center().x, bar.bottom() - 6.0); + run(vec![egui::Event::PointerMoved(track), click(track, true)]); + run(vec![]); + // The button is let go just past the bar's edge, closer than a drag, and the pointer then moves + // sideways onto the rows, in the same pass. + let let_go = pos2(bar.right() + 1.0, track.y); + let onto_row = before.first().map(|(_, r)| pos2(r.center().x, track.y)).expect("a row shows"); + run(vec![egui::Event::PointerMoved(let_go), click(let_go, false), egui::Event::PointerMoved(onto_row)]); + let mut after = vec![]; + for _ in 0..4 { + (after, _) = run(vec![]); + } + assert!(list_rect().is_some(), "a click on the scroll bar leaves the list open"); + let new = after + .iter() + .find(|(s, _)| !before.iter().any(|(b, _)| b == s)) + .cloned() + .unwrap_or_else(|| panic!("the click scrolled options into view: {after:?}")); + let row = new.1.center(); + run(vec![egui::Event::PointerMoved(row), click(row, true)]); + run(vec![click(row, false)]); + run(vec![]); + let index = labels.iter().position(|l| *l == new.0); + assert_eq!(picked.get(), index, "the option scrolled into view is picked: {}", new.0); + assert!(list_rect().is_none(), "picking an option closes the list"); +} + +// #5941: a drop-down list with an option wider than the window ran past the window's right edge, +// and its scroll bar with it. The list stays inside the window and its bar shows; the long option's +// name is cut short. +#[test] +fn a_dropdown_list_wider_than_the_window_keeps_its_scroll_bar_in_view() { + let mut items: Vec = (0..40).map(|i| format!("Option {i:02}")).collect(); + items[1] = "Option 01, whose name is much wider than this window".into(); + let labels: Vec<&str> = items.iter().map(String::as_str).collect(); + let short: Vec<&str> = labels.iter().copied().filter(|l| l.len() < 10).collect(); + let two: Vec<&str> = labels[..2].to_vec(); + // Which list the field offers: 0 all, 1 the short names, 2 the first two. + let offered = std::cell::Cell::new(0); + let ctx = themed(Default::default()); + let field = std::cell::Cell::new(Rect::NOTHING); + let popup = std::cell::RefCell::new(vec![]); + let mut add = |ui: &mut Ui| { + ui.add_space(16.0); + let options = [&labels, &short, &two][offered.get()]; + field.set(ui.horizontal(|ui| dropdown_names(ui, "wide-list", options[0], options, 160.0)).response.rect); + popup.replace(super::top_popup_shapes(ui.ctx())); + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(220.0, 300.0)); + let window = std::cell::Cell::new(screen); + let mut time = 0.0; + // The texts painted on the open list with their clip rects, and the scroll bar's rects. + let mut run = |events: Vec| { + time += 0.1; + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(window.get()), events, ..Default::default() }, &mut add); + out.textures_delta.clear(); + let (mut texts, mut bars) = (vec![], vec![]); + fn flat(s: &egui::Shape, clip: Rect, texts: &mut Vec<(String, bool)>, bars: &mut Vec) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, clip, texts, bars)), + egui::Shape::Text(t) => texts.push((t.galley.text().to_owned(), t.galley.elided)), + egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => bars.push(r.rect.intersect(clip)), + _ => {} + } + } + popup.take().iter().for_each(|c| flat(&c.shape, c.clip_rect, &mut texts, &mut bars)); + (texts, bars) + }; + run(vec![]); + let at = field.get().center(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(vec![egui::Event::PointerMoved(at), press(true)]); + run(vec![press(false)]); + run(vec![egui::Event::PointerMoved(pos2(210.0, 290.0))]); + let (mut texts, mut bars) = (vec![], vec![]); + for _ in 0..6 { + (texts, bars) = run(vec![]); + } + let list_rect = || { + ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id))) + }; + let list = list_rect().expect("the list is open"); + assert!(screen.contains_rect(list), "the list {list:?} is inside the window"); + assert!( + bars.iter().any(|b| b.width() > 0.0 && screen.contains_rect(*b) && list.contains_rect(*b)), + "the bar shows in the list {list:?}: {bars:?}" + ); + assert!(texts.iter().any(|(s, elided)| *elided && s.starts_with("Option 01")), "the long name is cut short: {texts:?}"); + // The window grows while the list is open: the list grows as wide as its names need, and no + // wider. + window.set(Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 300.0))); + for _ in 0..6 { + (texts, _) = run(vec![]); + } + let grown = list_rect().expect("the list is still open"); + assert!(grown.width() < 500.0, "the list {grown:?} stays as wide as its names need"); + assert!(texts.iter().any(|(s, elided)| !*elided && s == labels[1]), "the long name shows in full: {texts:?}"); + // Narrowed and widened again, it comes back to the same width. + for size in [screen.size(), vec2(1000.0, 300.0)] { + window.set(Rect::from_min_size(Pos2::ZERO, size)); + for _ in 0..6 { + run(vec![]); + } + } + let again = list_rect().expect("the list is still open"); + assert!((again.width() - grown.width()).abs() < 0.5, "the list is as wide as before: {again:?}, {grown:?}"); + // Closed, the window narrowed again and the long option gone: the list opens as narrow as its + // names, not as wide as the window. + let escape = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + run(vec![escape(true)]); + run(vec![escape(false)]); + assert!(list_rect().is_none(), "Escape closes the list"); + window.set(screen); + offered.set(1); + run(vec![]); + let at = field.get().center(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(vec![egui::Event::PointerMoved(at), press(true)]); + run(vec![press(false)]); + run(vec![egui::Event::PointerMoved(pos2(210.0, 290.0))]); + let mut widths = vec![]; + for _ in 0..4 { + run(vec![]); + widths.push(list_rect().expect("the list is open").width()); + } + assert!(widths.iter().all(|w| *w < 180.0), "the list of short names stays narrow: {widths:?}"); + // Opened in a wide window, narrowed and widened again: it comes back to the width it opened at, + // the long list that scrolls and a list of two that does not. + for (which, count) in [(0, "40"), (2, "2")] { + run(vec![escape(true)]); + run(vec![escape(false)]); + offered.set(which); + window.set(Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 300.0))); + run(vec![]); + run(vec![egui::Event::PointerMoved(at), press(true)]); + run(vec![press(false)]); + run(vec![egui::Event::PointerMoved(pos2(990.0, 290.0))]); + for _ in 0..6 { + run(vec![]); + } + let opened = list_rect().expect("the list is open"); + for size in [screen.size(), vec2(1000.0, 300.0)] { + window.set(Rect::from_min_size(Pos2::ZERO, size)); + for _ in 0..6 { + run(vec![]); + } + } + let restored = list_rect().expect("the list is still open"); + // Within the half point that egui rounds a popup's position to. + assert!((restored.width() - opened.width()).abs() < 0.5, "{count} options: the list is as wide as it opened: {restored:?}, {opened:?}"); + } + // Opened in a narrow window tall enough for every option, then made wide and short: the list + // scrolls now, and its bar's column comes on top of the long name, which shows in full. + run(vec![escape(true)]); + run(vec![escape(false)]); + offered.set(0); + window.set(Rect::from_min_size(Pos2::ZERO, vec2(220.0, 1400.0))); + run(vec![]); + run(vec![egui::Event::PointerMoved(at), press(true)]); + run(vec![press(false)]); + run(vec![egui::Event::PointerMoved(pos2(210.0, 1390.0))]); + for _ in 0..6 { + run(vec![]); + } + window.set(Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 300.0))); + for _ in 0..6 { + (texts, _) = run(vec![]); + } + assert!(texts.iter().any(|(s, elided)| !*elided && s == labels[1]), "the long name shows in full beside the bar: {texts:?}"); +} + +// #5941: in a drop-down list narrowed to the window, an option whose name is cut short shows the +// full name in a tooltip while the pointer rests on it. +#[test] +fn a_dropdown_option_cut_short_shows_its_full_name_on_hover() { + let mut items: Vec = (0..10).map(|i| format!("Option {i:02}")).collect(); + items[1] = "Option 01, whose name is much wider than this window".into(); + let labels: Vec<&str> = items.iter().map(String::as_str).collect(); + let ctx = themed(Default::default()); + let field = std::cell::Cell::new(Rect::NOTHING); + let mut add = |ui: &mut Ui| { + ui.add_space(16.0); + field.set(ui.horizontal(|ui| dropdown_names(ui, "hover-list", labels[0], &labels, 160.0)).response.rect); + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(220.0, 300.0)); + let mut time = 0.0; + // Every text painted, on any layer, with its rect and whether it was cut short. + let mut run = |events: Vec| { + time += 0.1; + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }, &mut add); + out.textures_delta.clear(); + let mut texts = vec![]; + fn flat(s: &egui::Shape, out: &mut Vec<(String, Rect, bool)>) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, out)), + egui::Shape::Text(t) => out.push((t.galley.text().to_owned(), t.visual_bounding_rect(), t.galley.elided)), + _ => {} + } + } + out.shapes.iter().for_each(|c| flat(&c.shape, &mut texts)); + texts + }; + run(vec![]); + let at = field.get().center(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(vec![egui::Event::PointerMoved(at), press(true)]); + run(vec![press(false)]); + run(vec![egui::Event::PointerMoved(pos2(210.0, 290.0))]); + let mut texts = vec![]; + for _ in 0..6 { + texts = run(vec![]); + } + let full = |texts: &[(String, Rect, bool)]| texts.iter().any(|(s, _, elided)| !*elided && s == labels[1]); + assert!(!full(&texts), "the long name is not shown in full before the hover: {texts:?}"); + let row = texts + .iter() + .find(|(s, _, elided)| *elided && s.starts_with("Option 01")) + .map(|(_, r, _)| r.center()) + .unwrap_or_else(|| panic!("the long name is cut short: {texts:?}")); + run(vec![egui::Event::PointerMoved(row)]); + for _ in 0..10 { + texts = run(vec![]); + } + assert!(full(&texts), "the full name shows on hover: {texts:?}"); +} + /// Enter on text that reads as no number in a range field refuses it as a unit field does: the /// field flashes and an open dialog is not confirmed with the old value. #[test] diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs index e3ce74bcbf..c409b6b71a 100644 --- a/crates/ui-egui/src/workspaces.rs +++ b/crates/ui-egui/src/workspaces.rs @@ -42,6 +42,10 @@ pub struct Workspace { pub toolbar_compact: bool, pub toolbar_advanced: bool, pub task_bar: bool, + /// The Contextual Task Bar's actions and chips its Bar Actions has off (built-in workspaces, and + /// workspaces saved without this field: none). + #[serde(skip_serializing_if = "std::collections::BTreeSet::is_empty", deserialize_with = "crate::canvas::read_hidden_task_bar_actions")] + pub task_bar_hidden_actions: std::collections::BTreeSet, pub dock: bool, pub dock_tab: DockTab, /// The dock's tabbed group is collapsed to icons (built-in workspaces: expanded). @@ -208,6 +212,7 @@ pub fn capture(ui: &UiState, name: &str) -> Workspace { toolbar_compact: ui.toolbar_compact, toolbar_advanced: ui.toolbar_advanced, task_bar: ui.task_bar, + task_bar_hidden_actions: ui.task_bar_hidden_actions.clone(), dock: ui.dock, dock_tab: ui.dock_tab, dock_collapsed: ui.dock_collapsed, @@ -247,6 +252,7 @@ pub fn apply(ui: &mut UiState, w: &Workspace) { ui.toolbar_compact = w.toolbar_compact; ui.toolbar_advanced = w.toolbar_advanced; ui.task_bar = w.task_bar; + ui.task_bar_hidden_actions = w.task_bar_hidden_actions.clone(); ui.dock = w.dock; ui.tab_hid = None; ui.dock_tab = w.dock_tab; @@ -949,4 +955,42 @@ mod tests { let read: UiState = serde_json::from_value(prefs).unwrap(); assert!(read.control_bar_hidden_groups.is_empty(), "older preferences show every group"); } + + /// A workspace keeps the Contextual Task Bar's actions its Bar Actions has off: switching + /// brings each workspace's back, Reset turns a built-in workspace's on again, and they survive + /// the preferences' JSON. A workspace saved without them, or with ids the bar does not have, + /// shows every action, or the ones it names that the bar has. + #[test] + fn saved_workspaces_restore_the_task_bar_actions() { + let hidden = |ids: &[&str]| ids.iter().map(|s| s.to_string()).collect::>(); + let mut ui = UiState { task_bar_hidden_actions: hidden(&["duplicate", "fill"]), ..Default::default() }; + save_as(&mut ui, "Lean").unwrap(); + switch(&mut ui, ESSENTIALS).unwrap(); + assert!(ui.task_bar_hidden_actions.is_empty(), "Essentials shows every action"); + ui.task_bar_hidden_actions = hidden(&["simplify"]); + switch(&mut ui, "Lean").unwrap(); + assert_eq!(ui.task_bar_hidden_actions, hidden(&["duplicate", "fill"]), "the saved workspace's actions"); + switch(&mut ui, ESSENTIALS).unwrap(); + assert_eq!(ui.task_bar_hidden_actions, hidden(&["simplify"]), "Essentials as it was left"); + reset(&mut ui); + assert!(ui.task_bar_hidden_actions.is_empty(), "Reset Essentials shows every action again"); + switch(&mut ui, "Lean").unwrap(); + let json = serde_json::to_value(&ui).unwrap(); + assert_eq!(json["custom_workspaces"][0]["taskBarHiddenActions"], serde_json::json!(["duplicate", "fill"])); + let back: UiState = serde_json::from_value(json).unwrap(); + assert_eq!(back.task_bar_hidden_actions, hidden(&["duplicate", "fill"]), "kept in the preferences"); + assert_eq!(back.custom_workspaces[0].task_bar_hidden_actions, hidden(&["duplicate", "fill"]), "kept with the workspace"); + let mut old = serde_json::to_value(&back.custom_workspaces[0]).unwrap(); + assert!(old.as_object_mut().unwrap().remove("taskBarHiddenActions").is_some()); + let old: Workspace = serde_json::from_value(old).unwrap(); + apply(&mut ui, &old); + assert!(ui.task_bar_hidden_actions.is_empty(), "an older workspace shows every action"); + let mut prefs = serde_json::to_value(&back).unwrap(); + prefs["custom_workspaces"][0]["taskBarHiddenActions"] = serde_json::json!(["fill", "teleport", 3]); + let read: UiState = serde_json::from_value(prefs.clone()).unwrap(); + assert_eq!(read.custom_workspaces[0].task_bar_hidden_actions, hidden(&["fill"]), "ids the bar does not have are dropped"); + prefs["custom_workspaces"][0]["taskBarHiddenActions"] = serde_json::json!("fill"); + let read: UiState = serde_json::from_value(prefs).unwrap(); + assert!(read.custom_workspaces[0].task_bar_hidden_actions.is_empty(), "a value that is not a list shows every action"); + } } diff --git a/crates/ui-egui/tests/image_trace_ignore_sampler.rs b/crates/ui-egui/tests/image_trace_ignore_sampler.rs new file mode 100644 index 0000000000..fec0805f58 --- /dev/null +++ b/crates/ui-egui/tests/image_trace_ignore_sampler.rs @@ -0,0 +1,1445 @@ +//! Image Trace Ignore Color's real panel button, tool callback and canvas presentation. +//! All APIs used here exist on the pre-fix base; the first regression fails on the missing button. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::time::{Duration, Instant}; + +use egui::{Event, PointerButton, Pos2, RawInput, Rect, vec2}; +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeId, NodeKind, TraceView}; +use vectorcraft_engine::Session; +use vectorcraft_geom::Point; +use vectorcraft_tools::{PointerEvent, PointerKind}; +use vectorcraft_ui_egui::{CacheKey, VectorcraftApp, canvas, trace_runs}; + +const SAMPLE_TIP: &str = "Eyedropper: click the source image to sample the ignored color"; + +fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> egui::FullOutput { + let mut raw = RawInput { events, focused: true, screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1400.0))), ..Default::default() }; + // raw_input_hook already begins the host iteration; do not begin a second one. + app.raw_input_hook(ctx, &mut raw); + ctx.run_ui(raw, |ui| { + app.tick(ui.ctx()); + app.ui(ui); + }) +} + +fn settle(app: &mut VectorcraftApp, ctx: &egui::Context) { + let deadline = Instant::now() + Duration::from_secs(10); + loop { + trace_runs::poll(app); + frame(app, ctx, vec![]).textures_delta.clear(); + if !trace_runs::any_running(app) { + break; + } + assert!(Instant::now() < deadline, "the tiny fixture's background trace did not finish"); + std::thread::sleep(Duration::from_millis(5)); + } + for _ in 0..2 { + frame(app, ctx, vec![]).textures_delta.clear(); + } +} + +fn click_control(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { + let mut found = None; + for _ in 0..3 { + let mut out = frame(app, ctx, vec![]); + if let Some(update) = &out.platform_output.accesskit_update { + found = update.nodes.iter().find(|(_, node)| node.label() == Some(label)).and_then(|(_, node)| node.bounds()); + } + out.textures_delta.clear(); + if found.is_some() { + break; + } + } + let bounds = found.unwrap_or_else(|| panic!("missing accessible Image Trace control: {label}")); + let at = egui::pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, ctx, vec![Event::PointerMoved(at)]).textures_delta.clear(); + frame(app, ctx, vec![press(true)]).textures_delta.clear(); + frame(app, ctx, vec![press(false)]).textures_delta.clear(); + settle(app, ctx); +} + +fn fixture(live_trace: bool, rgb: [u8; 3], preview: bool) -> (VectorcraftApp, egui::Context) { + fixture_with_transparent_edge(live_trace, rgb, preview, false) +} + +fn fixture_with_transparent_edge(live_trace: bool, rgb: [u8; 3], preview: bool, transparent: bool) -> (VectorcraftApp, egui::Context) { + vectorcraft_ui_egui::i18n::set_current(vectorcraft_ui_egui::i18n::Lang::EN); + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let pixels: Vec = (0..400) + .flat_map(|i| { + if transparent && i % 20 == 19 { + [0; 4] + } else if i % 20 < 10 { + [rgb[0], rgb[1], rgb[2], 255] + } else { + [255; 4] + } + }) + .collect(); + let image = + craft_image_codecs::Image::from_raw(20, 20, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, pixels).unwrap(); + let png = craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + app.run( + "file.place", + json!({"name": "sampler-original.png", "dataBase64": vectorcraft_format::base64_encode(&png), "link": false, "at": [200, 150]}), + ) + .unwrap(); + if live_trace { + app.run( + "imageTrace.make", + json!({"preset": "Default", "params": {"mode": "blackAndWhite", "threshold": 127, "noise": 1, "ignoreWhite": false}}), + ) + .unwrap(); + } + app.select_tool("selection"); + app.ui.image_trace_preview = preview; + app.ui.image_trace_advanced = true; + app.ui.task_bar = false; + app.ui.view.rulers = false; + app.session.prefs.monitor_profile_display = false; + app.canvas.worker_started = true; // the existing same-thread CPU canvas route + // An ordinary dock column gives Advanced the full window height without an auxiliary OS viewport. + app.run("window.panel.dock", json!({"panel": "imageTrace", "side": "End", "collapsed": false})).unwrap(); + app.run("window.panel.activate", json!({"panel": "imageTrace"})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + for _ in 0..8 { + frame(&mut app, &ctx, vec![]).textures_delta.clear(); + } + click_control(&mut app, &ctx, "Ignore Color"); + (app, ctx) +} + +fn selected(app: &VectorcraftApp) -> Node { + let state = app.session.active().unwrap(); + state.doc.node(state.selection.objects[0]).unwrap().clone() +} + +fn settings(app: &VectorcraftApp) -> Value { + selected(app).extras().trace.as_deref().unwrap().clone() +} + +fn source_point(app: &VectorcraftApp, x: f64) -> Point { + let selected = selected(app); + let original = selected.children().and_then(|children| children.first()).map_or(&selected, |child| child.as_ref()); + let NodeKind::Image(image) = &original.kind else { panic!("selected source image") }; + image.xf * Point::new(f64::from(image.width) * x, f64::from(image.height) * 0.5) +} + +fn sample(app: &mut VectorcraftApp, ctx: &egui::Context, point: Point) { + click_control(app, ctx, SAMPLE_TIP); + assert_eq!(app.session.tool_id(), "eyedropper", "the actual panel button arms sampling"); + let view = app.view_info(); + canvas::dispatch(app, &PointerEvent::new(PointerKind::Down, point.x, point.y), view); + settle(app, ctx); +} + +fn press_armed_canvas(app: &mut VectorcraftApp, ctx: &egui::Context, point: Point) { + assert_eq!(app.session.tool_id(), "eyedropper", "this is a continuation of the existing armed pick"); + let view = app.view_info(); + canvas::dispatch(app, &PointerEvent::new(PointerKind::Down, point.x, point.y), view); + canvas::dispatch(app, &PointerEvent::new(PointerKind::Up, point.x, point.y), view); + settle(app, ctx); +} + +#[test] +fn samples_original_trace_pixels_without_painting() { + let (mut app, ctx) = fixture(true, [37; 3], false); + let point = source_point(&app, 0.25); + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let paint = app.session.paint.clone(); + click_control(&mut app, &ctx, SAMPLE_TIP); + assert_eq!(app.session.tool_id(), "eyedropper"); + let at = canvas::Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), ctx.zoom_factor()).to_screen(point); + assert!(app.canvas_rect.unwrap().contains(at)); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![Event::PointerMoved(at), press(true)]).textures_delta.clear(); + frame(&mut app, &ctx, vec![press(false)]).textures_delta.clear(); + settle(&mut app, &ctx); + assert_eq!(app.session.tool_id(), "selection"); + assert_eq!(app.session.paint, paint); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, document, "Preview off leaves the document unchanged"); + assert_eq!(state.selection, selection); + assert_eq!(state.revision, revision); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + click_control(&mut app, &ctx, "Trace"); + assert_eq!(settings(&app)["params"]["ignoreColor"], "#252525", "persist the original gray, not the black tracing result"); +} + +#[test] +fn colored_placed_image_and_live_trace_keep_preview_off_drafts_until_trace() { + for live_trace in [false, true] { + let (mut app, ctx) = fixture(live_trace, [37, 83, 149], false); + let point = source_point(&app, 0.25); + let id = selected(&app).id; + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let paint = app.session.paint.clone(); + sample(&mut app, &ctx, point); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, document, "placed/live={live_trace}: sample only the panel draft"); + assert_eq!(state.selection, selection); + assert_eq!(state.revision, revision); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + assert_eq!(app.session.paint, paint); + app.run("select.none", json!({})).unwrap(); + settle(&mut app, &ctx); + app.run("select.set", json!({"ids": [id.0]})).unwrap(); + settle(&mut app, &ctx); + click_control(&mut app, &ctx, "Trace"); + assert_eq!(settings(&app)["params"]["ignoreColor"], "#255395", "the raw non-gray draft survives the selection round trip"); + assert_eq!(settings(&app)["preset"], "Custom"); + assert_eq!(app.session.active().unwrap().history.undo.len(), history.0 + 1, "Trace creates the only edit"); + } +} + +#[test] +fn preview_traces_once_and_undo_redo_restore_the_results() { + let (mut app, ctx) = fixture(true, [37, 83, 149], true); + let point = source_point(&app, 0.25); + let state = app.session.active().unwrap(); + let (before, selection, steps) = (state.doc.clone(), state.selection.clone(), state.history.undo.len()); + let paint = app.session.paint.clone(); + let view = selected(&app).trace_view(); + sample(&mut app, &ctx, point); + let after = app.session.active().unwrap().doc.clone(); + assert_ne!(after, before); + assert_eq!(settings(&app)["params"]["ignoreColor"], "#255395"); + assert_eq!(settings(&app)["preset"], "Custom"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); + // The existing imageTrace.make replaces the trace group and selects its new ID. + // Keep the logical trace selected, rather than requiring the removed group's ID. + let mut traced_selection = selection.clone(); + traced_selection.set([selected(&app).id]); + assert_eq!(app.session.active().unwrap().selection, traced_selection); + assert!(after.node(selection.objects[0]).is_none()); + assert_eq!(app.session.paint, paint); + assert_eq!(selected(&app).trace_view(), view); + assert_eq!(app.session.tool_id(), "selection"); + settle(&mut app, &ctx); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "later frames do not retrace"); + app.run("edit.undo", json!({})).unwrap(); + settle(&mut app, &ctx); + assert_eq!(app.session.active().unwrap().doc, before); + assert_eq!(app.session.active().unwrap().selection, selection); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps); + app.run("edit.redo", json!({})).unwrap(); + settle(&mut app, &ctx); + assert_eq!(app.session.active().unwrap().doc, after); + assert_eq!(app.session.active().unwrap().selection, traced_selection); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1); +} + +#[test] +fn escape_and_explicit_tool_choice_do_not_sample_or_paint() { + for exit in ["escape", "rectangle", "eyedropper"] { + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + let old_color = settings(&app)["params"]["ignoreColor"].clone(); + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let paint = app.session.paint.clone(); + click_control(&mut app, &ctx, SAMPLE_TIP); + assert_eq!(app.session.tool_id(), "eyedropper"); + match exit { + "escape" => { + let key = |pressed| Event::Key { + key: egui::Key::Escape, + physical_key: Some(egui::Key::Escape), + pressed, + repeat: false, + modifiers: egui::Modifiers::NONE, + }; + // Full public input path: claims/ends are observed before tool_key, and + // Escape's requests are applied only if the tool claims the key. + frame(&mut app, &ctx, vec![key(true)]).textures_delta.clear(); + frame(&mut app, &ctx, vec![key(false)]).textures_delta.clear(); + } + chosen => app.select_tool(chosen), + } + let expected = if exit == "escape" { "selection" } else { exit }; + assert_eq!(app.session.tool_id(), expected, "{exit}: restore or respect the explicit choice"); + assert!(app.session.tool_options_of("eyedropper")["imageTraceIgnoreColor"].is_null()); + settle(&mut app, &ctx); + assert!(app.canvas.key.as_ref().unwrap().trace_source.is_none()); + assert_eq!(app.session.paint, paint); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, document); + assert_eq!(state.selection, selection, "{exit}: Escape does not fall through to deselect"); + assert_eq!(state.revision, revision); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + click_control(&mut app, &ctx, "Trace"); + assert_eq!(settings(&app)["params"]["ignoreColor"], old_color, "{exit}: no hidden draft color was sampled"); + } +} + +#[test] +fn outside_and_transparent_misses_stay_armed_until_an_opaque_source_pixel_is_picked() { + for live_trace in [false, true] { + let (mut app, ctx) = fixture_with_transparent_edge(live_trace, [37, 83, 149], false, true); + let hit = source_point(&app, 0.25); + let outside = source_point(&app, -0.25); + let transparent = source_point(&app, 0.975); + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let paint = app.session.paint.clone(); + let node = selected(&app); + let original = if live_trace { node.children().unwrap()[0].as_ref() } else { &node }; + let NodeKind::Image(image) = &original.kind else { panic!("original fixture image") }; + let blob = &state.doc.images[&image.key]; + let keep = |_: f64, _: f64| true; + assert_eq!( + blob.sample_pixels(&[(Some([0.95, 0.5, 1.0, 0.55]), 1, &keep)]), + Some(vec![vec![[0; 4]]]), + "the missed point is really transparent in the source" + ); + assert!(blob.sample_object(19.5, 10.0, (image.width, image.height), 1).is_none(), "a transparent source pixel has no color to pick"); + click_control(&mut app, &ctx, SAMPLE_TIP); + let binding = app.session.tool_options()["imageTraceIgnoreColor"].clone(); + assert!(!binding.is_null()); + for miss in [outside, transparent] { + press_armed_canvas(&mut app, &ctx, miss); + assert_eq!(app.session.tool_id(), "eyedropper", "live={live_trace}: a miss stays armed"); + assert!(app.ui.trace_ignore_sampler.is_some()); + assert_eq!(app.session.tool_options()["imageTraceIgnoreColor"], binding); + assert_eq!(app.session.tool_options()["stop"], "selection"); + assert_eq!(app.session.paint, paint); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, document); + assert_eq!(state.selection, selection); + assert_eq!(state.revision, revision); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + } + press_armed_canvas(&mut app, &ctx, hit); + assert_eq!(app.session.tool_id(), "selection", "the valid pick restores the previous tool"); + assert!(app.ui.trace_ignore_sampler.is_none()); + assert!(app.session.tool_options_of("eyedropper")["imageTraceIgnoreColor"].is_null()); + assert_eq!(app.session.paint, paint); + assert_eq!(app.session.active().unwrap().doc, document, "Preview off keeps the accepted color in the draft"); + click_control(&mut app, &ctx, "Trace"); + assert_eq!(settings(&app)["params"]["ignoreColor"], "#255395", "the next valid source pixel completes the same armed pick"); + } +} + +#[test] +fn stale_target_click_is_consumed_before_the_restored_tool_can_select_or_paint() { + for invalidation in ["selection", "document", "revision_round_trip"] { + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + let point = source_point(&app, 0.25); + let old_document = app.session.active().unwrap().doc.clone(); + let old_uid = app.session.active().unwrap().uid; + let armed_revision = app.session.active().unwrap().revision; + click_control(&mut app, &ctx, SAMPLE_TIP); + match invalidation { + "selection" => { + app.run("select.none", json!({})).unwrap(); + } + "document" => { + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + } + _ => { + app.run("imageTrace.setView", json!({"view": TraceView::Outlines.id()})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc, old_document); + assert_ne!(app.session.active().unwrap().revision, armed_revision); + } + } + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let paint = app.session.paint.clone(); + // No UI refresh intervenes: this must exercise the real dispatch stale-Down guard. + let view = app.view_info(); + canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::Down, point.x, point.y), view); + assert_eq!(app.session.tool_id(), "selection", "{invalidation}: restore prior tool"); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, document); + assert_eq!(state.selection, selection, "the stale click cannot reselect the source"); + assert_eq!(state.revision, revision); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + assert_eq!(app.session.paint, paint); + assert_eq!(app.session.documents().iter().find(|d| d.uid == old_uid).unwrap().doc, old_document); + settle(&mut app, &ctx); + assert!(app.canvas.key.as_ref().unwrap().trace_source.is_none()); + } +} + +#[test] +fn a_stale_sampler_and_canvas_press_in_one_frame_do_not_reselect_the_source() { + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + let point = source_point(&app, 0.25); + let target = selected(&app).id; + click_control(&mut app, &ctx, SAMPLE_TIP); + app.run("select.none", json!({})).unwrap(); + // The last real layout supplies the canvas rect and view. Canvas itself records this + // context's zoom_factor as its UI-coordinate scale before routing input. + let at = canvas::Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), ctx.zoom_factor()).to_screen(point); + assert!(app.canvas_rect.unwrap().contains(at)); + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let paint = app.session.paint.clone(); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![Event::PointerMoved(at), press(true)]).textures_delta.clear(); + assert_eq!(app.session.tool_id(), "selection"); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, document); + assert_eq!(state.selection, selection, "the press in the cancellation frame is consumed"); + assert_eq!(state.revision, revision); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + assert_eq!(app.session.paint, paint); + frame(&mut app, &ctx, vec![press(false)]).textures_delta.clear(); + assert!(app.session.active().unwrap().selection.objects.is_empty()); + // Positive control: the same ordinary, unarmed click really hits and selects this trace. + frame(&mut app, &ctx, vec![Event::PointerMoved(at), press(true)]).textures_delta.clear(); + frame(&mut app, &ctx, vec![press(false)]).textures_delta.clear(); + assert_eq!(app.session.active().unwrap().selection.objects, vec![target]); +} + +/// A stale sampler consumes its second press, including the release's double-click action. +#[test] +fn a_consumed_stale_sampler_press_does_not_complete_a_double_click() { + // Run the legitimate control first: this geometry and these real UI frames must isolate. + check_sampler_double_click(false); + check_sampler_double_click(true); +} + +fn frame_at(app: &mut VectorcraftApp, ctx: &egui::Context, time: f64, events: Vec) { + let mut raw = RawInput { + time: Some(time), + events, + focused: true, + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1600.0, 1400.0))), + ..Default::default() + }; + app.raw_input_hook(ctx, &mut raw); + let mut out = ctx.run_ui(raw, |ui| { + app.tick(ui.ctx()); + app.ui(ui); + }); + out.textures_delta.clear(); + assert_eq!(ctx.time(), time, "the real UI frame uses the supplied gesture time"); +} + +fn check_next_ordinary_double_click(app: &mut VectorcraftApp, ctx: &egui::Context, at: Pos2, group: NodeId, next: f64, step: f64) { + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame_at(app, ctx, next, vec![Event::PointerMoved(at), press(true)]); + frame_at(app, ctx, next + step, vec![press(false)]); + assert!(!ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().selection.objects, vec![group], "the next ordinary first click selects the group"); + assert_eq!(app.session.active().unwrap().isolation, None); + frame_at(app, ctx, next + 3.0 * step, vec![press(true)]); + frame_at(app, ctx, next + 4.0 * step, vec![press(false)]); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().isolation, Some(group), "the next ordinary double-click still isolates the group"); +} + +fn check_sampler_double_click(sampler: bool) { + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + let source = selected(&app).id; + app.session.prefs.double_click_to_isolate = true; + let first = app.run("shape.rectangle", json!({"x": 100, "y": 140, "width": 20, "height": 20})).unwrap()["id"].clone(); + let second = app.run("shape.rectangle", json!({"x": 120, "y": 140, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [first.clone(), second.clone()], "color": "#cc3322"})).unwrap(); + app.run("select.set", json!({"ids": [first, second]})).unwrap(); + let group = NodeId(app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [source.0]})).unwrap(); + settle(&mut app, &ctx); + let point = Point::new(110.0, 150.0); + assert!(point.x < source_point(&app, 0.0).x - 40.0, "the group is outside the source image"); + if sampler { + click_control(&mut app, &ctx, SAMPLE_TIP); + assert_eq!(app.session.tool_id(), "eyedropper"); + assert!(app.ui.trace_ignore_sampler.is_some()); + } + let at = canvas::Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), ctx.zoom_factor()).to_screen(point); + assert!(app.canvas_rect.unwrap().contains(at)); + let (delay, hold) = ctx.options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_duration)); + assert!(delay.is_finite() && delay > 0.0 && hold.is_finite() && hold > 0.0); + let step = delay.min(hold) / 8.0; + // Leave the panel-button click outside the interval; only these two canvas clicks count. + let start = ctx.time() + delay + 1.0; + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame_at(&mut app, &ctx, start, vec![Event::PointerMoved(at), press(true)]); + frame_at(&mut app, &ctx, start + step, vec![press(false)]); + assert!(!ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary)), "the first canvas click is single"); + assert_eq!(app.session.active().unwrap().isolation, None); + + if sampler { + assert_eq!(app.session.tool_id(), "eyedropper", "the first click is a source-image miss"); + assert!(app.ui.trace_ignore_sampler.is_some(), "the miss keeps sampling armed"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![source], "the miss does not select the group"); + // No intervening UI frame: canvas refresh must consume the stale second press. + app.run("select.none", json!({})).unwrap(); + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let paint = app.session.paint.clone(); + frame_at(&mut app, &ctx, start + 3.0 * step, vec![press(true)]); + assert_eq!(app.session.tool_id(), "selection"); + assert!(app.ui.trace_ignore_sampler.is_none()); + assert_eq!(app.session.active().unwrap().selection, selection, "the second press was consumed"); + frame_at(&mut app, &ctx, start + 4.0 * step, vec![press(false)]); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary)), "egui recognizes the timed release as a double-click"); + let state = app.session.active().unwrap(); + assert_eq!(state.isolation, None, "the release of the consumed press must not isolate the group"); + assert_eq!(state.doc, document); + assert_eq!(state.selection, selection); + assert_eq!(state.revision, revision); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + assert_eq!(app.session.paint, paint); + assert_eq!(app.session.tool_id(), "selection"); + // The consumed release must not take the next independent ordinary gesture with it. + let next = start + 4.0 * step + delay + 1.0; + check_next_ordinary_double_click(&mut app, &ctx, at, group, next, step); + } else { + assert_eq!(app.session.active().unwrap().selection.objects, vec![group], "the ordinary first click really selects the group"); + frame_at(&mut app, &ctx, start + 3.0 * step, vec![press(true)]); + frame_at(&mut app, &ctx, start + 4.0 * step, vec![press(false)]); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().isolation, Some(group), "the legitimate unarmed double-click isolates the same group"); + } +} + +fn capture_canvas(app: &mut VectorcraftApp, ctx: &egui::Context) -> (vectorcraft_render::Rendered, CacheKey) { + app.canvas.key = None; // force a complete upload, not a partial delta requiring reconstruction + let mut out = frame(app, ctx, vec![]); + let id = app.canvas.texture.as_ref().expect("real canvas texture").id(); + let upload = + out.textures_delta.set.iter().find(|(texture, _)| **texture == id).and_then(|(_, updates)| updates.last()).expect("CPU canvas upload"); + assert!(upload.pos.is_none()); + let egui::ImageData::Color(image) = &upload.image; + let rendered = vectorcraft_render::Rendered { + width: image.width() as u32, + height: image.height() as u32, + pixels: image.pixels.iter().flat_map(|c| c.to_array()).collect(), + }; + let key = app.canvas.key.as_ref().unwrap().clone(); + out.textures_delta.clear(); + (rendered, key) +} + +fn pixel_at(image: &vectorcraft_render::Rendered, key: &CacheKey, point: Point) -> [u8; 4] { + assert!(key.pixel.is_none() && key.rot == 0.0, "fixture uses the ordinary unrotated canvas"); + let x = (f64::from(image.width) * 0.5 + (point.x - key.cx) * key.zoom * f64::from(key.ppp)).floor(); + let y = (f64::from(image.height) * 0.5 + (point.y - key.cy) * key.zoom * f64::from(key.ppp)).floor(); + assert!(x >= 0.0 && x < f64::from(image.width) && y >= 0.0 && y < f64::from(image.height)); + let at = ((y as usize * image.width as usize) + x as usize) * 4; + image.pixels[at..at + 4].try_into().unwrap() +} + +#[test] +fn actual_canvas_keeps_its_displayed_view_while_the_original_pixels_are_sampled() { + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + let point = source_point(&app, 0.25); + let control = source_point(&app, 0.75); + let target: NodeId = selected(&app).id; + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let uid = state.uid; + let original = state.doc.node(target).unwrap().children().unwrap()[0].clone(); + assert!(!original.visible, "the live trace retains its hidden original"); + let NodeKind::Image(image) = &original.kind else { panic!("original image") }; + let blob = state.doc.images.get(&image.key).unwrap(); + assert_eq!( + blob.sample_object(f64::from(image.width) * 0.25, f64::from(image.height) * 0.5, (image.width, image.height), 1), + Some([37, 83, 149, 255]) + ); + let stored = settings(&app); + let (before, before_key) = capture_canvas(&mut app, &ctx); + assert_eq!(pixel_at(&before, &before_key, point), [0, 0, 0, 255]); + assert_eq!(pixel_at(&before, &before_key, control), [255; 4]); + click_control(&mut app, &ctx, SAMPLE_TIP); + let (armed, armed_key) = capture_canvas(&mut app, &ctx); + assert!(!ctx.input(|i| i.pointer.any_down()), "the button press has ended"); + assert_eq!(armed_key.trace_source, before_key.trace_source, "arming does not override the existing eye hold or trace View"); + assert_eq!(armed.pixels, before.pixels, "sampling original pixels does not change the displayed tracing result"); + assert_eq!(pixel_at(&armed, &armed_key, point), [0, 0, 0, 255]); + assert_eq!(pixel_at(&armed, &armed_key, control), [255; 4]); + press_armed_canvas(&mut app, &ctx, point); + assert_eq!(app.session.tool_id(), "selection"); + let (restored, restored_key) = capture_canvas(&mut app, &ctx); + assert!(restored_key.trace_source.is_none()); + assert_eq!(restored.pixels, before.pixels, "the valid Preview-off pick leaves the displayed result unchanged"); + assert_eq!(settings(&app), stored, "the stored View and trace settings are unchanged"); + let state = app.session.active().unwrap(); + assert_eq!((state.uid, state.revision), (uid, revision)); + assert_eq!(state.doc, document); + assert_eq!(state.selection, selection); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + click_control(&mut app, &ctx, "Trace"); + assert_eq!( + settings(&app)["params"]["ignoreColor"], + "#255395", + "the source color is sampled while the canvas still shows its black tracing result" + ); +} + +/// Cancelling while Cmd/Ctrl borrows Selection also clears the parked eyedropper's one-shot. +#[test] +fn cancelling_a_borrowed_sampler_clears_the_restored_eyedropper() { + fn loan_frame(app: &mut VectorcraftApp, ctx: &egui::Context, mut events: Vec) -> egui::FullOutput { + events.insert(0, Event::ModifiersChanged(egui::Modifiers { ctrl: true, command: true, ..Default::default() })); + frame(app, ctx, events) + } + + fn borrow_and_release(app: &mut VectorcraftApp, ctx: &egui::Context, point: Point, stale: bool) { + let modifiers = vectorcraft_tools::Mods { cmd: true, ..Default::default() }; + assert_eq!(app.session.lent_tool_id(&modifiers), Some("selection"), "exercise the real engine loan"); + let at = canvas::Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), ctx.zoom_factor()).to_screen(point); + assert!(app.canvas_rect.unwrap().contains(at)); + let press = |pressed| Event::PointerButton { + pos: at, + button: PointerButton::Primary, + pressed, + modifiers: egui::Modifiers { ctrl: true, command: true, ..Default::default() }, + }; + loan_frame(app, ctx, vec![Event::PointerMoved(at), press(true)]).textures_delta.clear(); + assert_eq!(app.session.tool_id(), "selection", "the eyedropper is now parked in Session::lender"); + if stale { + app.run("select.none", json!({})).unwrap(); + } + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let paint = app.session.paint.clone(); + loan_frame(app, ctx, vec![]).textures_delta.clear(); + assert_eq!(app.session.tool_id(), "selection", "cancellation respects the borrowed gesture"); + assert!(app.ui.trace_ignore_sampler.is_none(), "the real frame ends the UI-owned sampler"); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, document); + assert_eq!(state.selection, selection); + assert_eq!(state.revision, revision); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + assert_eq!(app.session.paint, paint, "cancelling a parked sampler does not paint"); + loan_frame(app, ctx, vec![press(false)]).textures_delta.clear(); + frame(app, ctx, vec![Event::ModifiersChanged(egui::Modifiers::NONE)]).textures_delta.clear(); + assert_eq!(app.session.tool_id(), "eyedropper", "ordinary engine loan restoration is retained"); + } + + fn ordinary_sample(app: &mut VectorcraftApp, ctx: &egui::Context, point: Point) -> (usize, usize, u64) { + app.run("select.none", json!({})).unwrap(); + app.run("paint.setFill", json!({"color": "#e020c0"})).unwrap(); + assert!(app.session.fill_active); + let state = app.session.active().unwrap(); + let (document, selection, revision) = (state.doc.clone(), state.selection.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let old_paint = app.session.paint.clone(); + let view = app.view_info(); + let down = PointerEvent::new(PointerKind::Down, point.x, point.y).with_mods(vectorcraft_tools::Mods { shift: true, ..Default::default() }); + canvas::dispatch(app, &down, view); + canvas::dispatch(app, &PointerEvent::new(PointerKind::Up, point.x, point.y), view); + frame(app, ctx, vec![]).textures_delta.clear(); + assert_eq!(app.session.tool_id(), "eyedropper", "a normal sample does not consume a stale one-shot or switch tools"); + assert_ne!(app.session.paint, old_paint, "the normal color sample actually runs"); + assert_eq!(app.session.paint.fill, vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK)); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, document, "with no selection a normal sample changes only paint defaults"); + assert_eq!(state.selection, selection); + (state.history.undo.len() - history.0, state.history.redo.len().abs_diff(history.1), state.revision - revision) + } + + for stale in [false, true] { + // The same ordinary loan is the control for legitimate selection/default/history work. + let (mut control, control_ctx) = fixture(true, [37, 83, 149], false); + let control_point = source_point(&control, 0.25); + let control_target = selected(&control).id; + let control_revision = control.session.active().unwrap().revision; + let control_document = control.session.active().unwrap().doc.clone(); + let control_history = { + let state = control.session.active().unwrap(); + (state.history.undo.len(), state.history.redo.len()) + }; + control.select_tool("eyedropper"); + borrow_and_release(&mut control, &control_ctx, control_point, stale); + let expected_selection: Vec = control.session.active().unwrap().selection.objects.iter().map(|id| *id == control_target).collect(); + let expected_revision_delta = control.session.active().unwrap().revision - control_revision; + assert_eq!(control.session.active().unwrap().doc, control_document); + assert_eq!((control.session.active().unwrap().history.undo.len(), control.session.active().unwrap().history.redo.len()), control_history); + let expected_paint = control.session.paint.clone(); + let expected_sample_effects = ordinary_sample(&mut control, &control_ctx, control_point); + + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + let point = source_point(&app, 0.25); + let target = selected(&app).id; + let state = app.session.active().unwrap(); + let (document, revision) = (state.doc.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + click_control(&mut app, &ctx, SAMPLE_TIP); + assert_eq!(app.session.tool_id(), "eyedropper"); + assert!(!app.session.tool_options()["imageTraceIgnoreColor"].is_null()); + borrow_and_release(&mut app, &ctx, point, stale); + assert!(app.session.tool_options()["imageTraceIgnoreColor"].is_null(), "stale={stale}: the returned lender must not stay armed"); + assert!(app.session.tool_options()["stop"].is_null(), "stale={stale}: no ghost return-tool action"); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, document); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + assert_eq!(state.selection.objects.iter().map(|id| *id == target).collect::>(), expected_selection); + assert_eq!(state.revision - revision, expected_revision_delta); + assert_eq!(app.session.paint, expected_paint, "only the ordinary borrowed gesture's default changes are permitted"); + assert_eq!(ordinary_sample(&mut app, &ctx, point), expected_sample_effects, "the next real click follows the ordinary eyedropper path"); + } +} + +fn review_gesture_group_fixture() -> (VectorcraftApp, egui::Context, Point, NodeId) { + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + let source = selected(&app).id; + app.session.prefs.double_click_to_isolate = true; + let first = app.run("shape.rectangle", json!({"x": 100, "y": 140, "width": 20, "height": 20})).unwrap()["id"].clone(); + let second = app.run("shape.rectangle", json!({"x": 120, "y": 140, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [first.clone(), second.clone()], "color": "#cc3322"})).unwrap(); + app.run("select.set", json!({"ids": [first, second]})).unwrap(); + let group = NodeId(app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [source.0]})).unwrap(); + settle(&mut app, &ctx); + let point = Point::new(110.0, 150.0); + assert!(point.x < source_point(&app, 0.0).x - 40.0, "the gesture group is outside the sampled image"); + (app, ctx, point, group) +} + +fn review_gesture_screen(app: &VectorcraftApp, ctx: &egui::Context, point: Point) -> Pos2 { + let rect = app.canvas_rect.unwrap(); + let at = canvas::Xf::at(rect, app.view().unwrap(), ctx.zoom_factor()).to_screen(point); + assert!(rect.contains(at), "the real canvas contains the gesture point"); + at +} + +fn review_gesture_times(ctx: &egui::Context) -> (f64, f64) { + let (delay, hold) = ctx.options(|o| (o.input_options.max_double_click_delay, o.input_options.max_click_duration)); + assert!(delay.is_finite() && delay > 0.0 && hold.is_finite() && hold > 0.0); + (ctx.time() + delay + 1.0, delay.min(hold) / 8.0) +} + +fn review_gesture_press(app: &mut VectorcraftApp, ctx: &egui::Context, at: Pos2, time: f64) { + let event = Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Default::default() }; + frame_at(app, ctx, time, vec![Event::PointerMoved(at), event]); +} + +fn review_gesture_release(app: &mut VectorcraftApp, ctx: &egui::Context, at: Pos2, time: f64) { + let event = Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Default::default() }; + frame_at(app, ctx, time, vec![event]); +} + +fn review_gesture_state(app: &VectorcraftApp) -> impl PartialEq + std::fmt::Debug + use<> { + let state = app.session.active().unwrap(); + ( + state.doc.clone(), + state.selection.clone(), + state.revision, + (state.history.undo.len(), state.history.redo.len()), + app.session.paint.clone(), + state.isolation, + ) +} + +fn review_gesture_observation(app: &VectorcraftApp, ctx: &egui::Context) -> (bool, bool, Vec, Option) { + let state = app.session.active().unwrap(); + ( + ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary)), + ctx.input(|i| i.pointer.button_triple_clicked(PointerButton::Primary)), + state.selection.objects.clone(), + state.isolation, + ) +} + +fn review_gesture_ordinary_pair(app: &mut VectorcraftApp, ctx: &egui::Context, first: Pos2, second: Pos2, group: NodeId) { + let (start, step) = review_gesture_times(ctx); + review_gesture_press(app, ctx, first, start); + review_gesture_release(app, ctx, first, start + step); + assert!(!ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().selection.objects, vec![group], "the ordinary first click selects the group"); + assert_eq!(app.session.active().unwrap().isolation, None); + review_gesture_press(app, ctx, second, start + 3.0 * step); + frame_at(app, ctx, start + 3.5 * step, vec![]); + review_gesture_release(app, ctx, second, start + 4.0 * step); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().isolation, Some(group), "the ordinary held double-click isolates the group"); +} + +#[test] +fn review_followup_sampler_cancelled_mid_hold_keeps_release_owned() { + let (mut control, control_ctx, control_point, control_group) = review_gesture_group_fixture(); + let control_at = review_gesture_screen(&control, &control_ctx, control_point); + review_gesture_ordinary_pair(&mut control, &control_ctx, control_at, control_at, control_group); + + let (mut app, ctx, point, _) = review_gesture_group_fixture(); + let source = selected(&app).id; + click_control(&mut app, &ctx, SAMPLE_TIP); + let at = review_gesture_screen(&app, &ctx, point); + let (start, step) = review_gesture_times(&ctx); + review_gesture_press(&mut app, &ctx, at, start); + review_gesture_release(&mut app, &ctx, at, start + step); + assert_eq!(app.session.tool_id(), "eyedropper"); + assert!(app.ui.trace_ignore_sampler.is_some(), "the first canvas click is a sampler miss"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![source]); + assert_eq!(app.session.active().unwrap().isolation, None); + review_gesture_press(&mut app, &ctx, at, start + 3.0 * step); + assert!(app.ui.trace_ignore_sampler.is_some(), "the second Down still belongs to the valid sampler"); + app.run("select.none", json!({})).unwrap(); + let expected = review_gesture_state(&app); + frame_at(&mut app, &ctx, start + 3.5 * step, vec![]); + assert!(ctx.input(|i| i.pointer.primary_down())); + assert!(!ctx.input(|i| i.pointer.primary_pressed())); + assert_eq!(app.session.tool_id(), "selection"); + assert!(app.ui.trace_ignore_sampler.is_none(), "the held frame cancelled the invalid binding"); + review_gesture_release(&mut app, &ctx, at, start + 4.0 * step); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(review_gesture_state(&app), expected, "a mid-hold cancellation must retain ownership through release"); + assert_eq!(app.session.tool_id(), "selection"); +} + +#[test] +fn review_followup_consumed_prefix_keeps_two_fresh_clicks_single_then_double() { + let (mut control, control_ctx, control_point, control_group) = review_gesture_group_fixture(); + let control_at = review_gesture_screen(&control, &control_ctx, control_point); + review_gesture_ordinary_pair(&mut control, &control_ctx, control_at, control_at, control_group); + + let (mut app, ctx, point, group) = review_gesture_group_fixture(); + click_control(&mut app, &ctx, SAMPLE_TIP); + app.run("select.none", json!({})).unwrap(); + let at = review_gesture_screen(&app, &ctx, point); + let expected = review_gesture_state(&app); + let (start, step) = review_gesture_times(&ctx); + review_gesture_press(&mut app, &ctx, at, start); + review_gesture_release(&mut app, &ctx, at, start + step); + assert!(!ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(review_gesture_state(&app), expected, "the single stale prefix itself is consumed"); + assert_eq!(app.session.tool_id(), "selection"); + + review_gesture_press(&mut app, &ctx, at, start + 3.0 * step); + review_gesture_release(&mut app, &ctx, at, start + 4.0 * step); + let first = review_gesture_observation(&app, &ctx); + // Always run the second fresh click, even when the first app-level oracle was wrong. + review_gesture_press(&mut app, &ctx, at, start + 6.0 * step); + review_gesture_release(&mut app, &ctx, at, start + 7.0 * step); + let second = review_gesture_observation(&app, &ctx); + assert!(first.0 && !first.1 && !second.0 && second.1, "expected raw Double then Triple: first={first:?}, second={second:?}"); + assert!( + first.2 == vec![group] && first.3.is_none() && second.3 == Some(group), + "fresh clicks must select without isolation, then isolate: first={first:?}, second={second:?}" + ); +} + +fn review_gesture_enclose_source(app: &mut VectorcraftApp, source: NodeId) -> NodeId { + let background = app.run("shape.rectangle", json!({"x": 50, "y": 30, "width": 300, "height": 240})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [background.clone()], "color": "#e020c0"})).unwrap(); + app.run("select.set", json!({"ids": [source.0, background]})).unwrap(); + let group = NodeId(app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [source.0]})).unwrap(); + group +} + +fn review_gesture_original_pixels(app: &VectorcraftApp) { + let trace = selected(app); + let original = trace.children().unwrap()[0].as_ref(); + let NodeKind::Image(image) = &original.kind else { panic!("the fixture retains its original image") }; + let state = app.session.active().unwrap(); + let blob = &state.doc.images[&image.key]; + assert!(blob.sample_object(19.5, 10.0, (image.width, image.height), 1).is_none(), "the first point is really transparent"); + assert_eq!( + blob.sample_object(5.0, 10.0, (image.width, image.height), 1), + Some([37, 83, 149, 255]), + "the second point has a distinct nonwhite source color" + ); +} + +fn review_gesture_close_pair(app: &VectorcraftApp, ctx: &egui::Context, miss: Point, hit: Point) -> (Pos2, Pos2) { + let miss = review_gesture_screen(app, ctx, miss); + let hit = review_gesture_screen(app, ctx, hit); + let distance = ctx.options(|o| o.input_options.max_click_dist); + assert!(distance.is_finite() && distance > 0.0); + assert!(miss.distance_sq(hit) < distance * distance, "the actual transformed miss/hit pair satisfies egui's click distance"); + (miss, hit) +} + +fn review_gesture_completion_fixture() -> (VectorcraftApp, egui::Context, Point, Point, NodeId) { + let (mut app, ctx) = fixture_with_transparent_edge(true, [37, 83, 149], false, true); + let source = selected(&app).id; + review_gesture_original_pixels(&app); + app.session.prefs.double_click_to_isolate = true; + let group = review_gesture_enclose_source(&mut app, source); + // view.setZoom takes display percent; use its public 10% setting, then assert actual geometry. + app.run("view.setZoom", json!({"zoom": 10.0, "center": [200, 150]})).unwrap(); + settle(&mut app, &ctx); + let miss = source_point(&app, 0.975); + let hit = source_point(&app, 0.25); + (app, ctx, miss, hit, group) +} + +#[test] +fn review_followup_valid_sampler_down_completes_without_lending_its_release() { + let (mut control, control_ctx, control_miss, control_hit, control_group) = review_gesture_completion_fixture(); + control.run("select.none", json!({})).unwrap(); + settle(&mut control, &control_ctx); + let (control_miss, control_hit) = review_gesture_close_pair(&control, &control_ctx, control_miss, control_hit); + review_gesture_ordinary_pair(&mut control, &control_ctx, control_miss, control_hit, control_group); + + let (mut app, ctx, miss, hit, _) = review_gesture_completion_fixture(); + click_control(&mut app, &ctx, SAMPLE_TIP); + let (miss, hit) = review_gesture_close_pair(&app, &ctx, miss, hit); + let (start, step) = review_gesture_times(&ctx); + review_gesture_press(&mut app, &ctx, miss, start); + review_gesture_release(&mut app, &ctx, miss, start + step); + assert_eq!(app.session.tool_id(), "eyedropper"); + assert!(app.ui.trace_ignore_sampler.is_some(), "the transparent first click keeps the sampler armed"); + let expected = review_gesture_state(&app); + review_gesture_press(&mut app, &ctx, hit, start + 3.0 * step); + assert_eq!(app.session.tool_id(), "selection", "the opaque Down completes sampling and restores the tool"); + assert!(app.ui.trace_ignore_sampler.is_none()); + assert_eq!(review_gesture_state(&app), expected, "Preview off sampling changes only the panel draft"); + review_gesture_release(&mut app, &ctx, hit, start + 4.0 * step); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(review_gesture_state(&app), expected, "a completed sampler still owns its matching release"); + assert_eq!(app.session.tool_id(), "selection"); + // A fix that merely cancels the valid Down must not pass without accepting its actual color. + click_control(&mut app, &ctx, "Trace"); + assert_eq!(settings(&app)["params"]["ignoreColor"], "#255395", "Trace persists the real opaque source sample"); + assert_eq!(settings(&app)["params"]["ignoreWhite"], true); +} + +fn review_preset_checkbox(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) -> bool { + for _ in 0..3 { + let mut output = frame(app, ctx, vec![]); + let checked = output.platform_output.accesskit_update.as_ref().and_then(|update| { + update.nodes.iter().find(|(_, node)| node.label() == Some(label) && node.role() == egui::accesskit::Role::CheckBox).and_then( + |(_, node)| match node.toggled() { + Some(egui::accesskit::Toggled::True) => Some(true), + Some(egui::accesskit::Toggled::False) => Some(false), + _ => None, + }, + ) + }); + output.textures_delta.clear(); + if let Some(checked) = checked { + return checked; + } + } + panic!("fixture: missing accessible Image Trace checkbox state: {label}"); +} + +fn review_preset_assert_shown(app: &mut VectorcraftApp, ctx: &egui::Context, preset: &str) { + fn contains(shape: &egui::Shape, text: &str) -> bool { + match shape { + egui::Shape::Text(drawn) => drawn.galley.text() == text, + egui::Shape::Vec(shapes) => shapes.iter().any(|shape| contains(shape, text)), + _ => false, + } + } + let mut output = frame(app, ctx, vec![]); + let shown = output.shapes.iter().any(|clipped| contains(&clipped.shape, preset)); + output.textures_delta.clear(); + assert!(shown, "fixture: the real Preset control must show {preset}"); +} + +fn review_preset_click_opaque_source(app: &mut VectorcraftApp, ctx: &egui::Context) { + let point = source_point(app, 0.25); + let source = selected(app); + let original = source.children().and_then(|children| children.first()).unwrap(); + let NodeKind::Image(image) = &original.kind else { panic!("fixture: the live trace retains its original image") }; + assert_eq!( + app.session.active().unwrap().doc.images[&image.key].sample_object( + f64::from(image.width) * 0.25, + f64::from(image.height) * 0.5, + (image.width, image.height), + 1, + ), + Some([37, 83, 149, 255]), + "fixture: the actual canvas point is an opaque original pixel" + ); + let at = canvas::Xf::at(app.canvas_rect.unwrap(), app.view().unwrap(), ctx.zoom_factor()).to_screen(point); + assert!(app.canvas_rect.unwrap().contains(at), "fixture: the source point lies on the actual canvas"); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, ctx, vec![Event::PointerMoved(at), press(true)]).textures_delta.clear(); + frame(app, ctx, vec![press(false)]).textures_delta.clear(); + settle(app, ctx); +} + +fn review_preset_enhanced_on_control() { + // Legitimate control first: the real Enhanced pair retains Ignore Color and a valid pick. + let (mut control, control_ctx) = fixture(true, [37, 83, 149], false); + click_control(&mut control, &control_ctx, "Black and White"); + review_preset_assert_shown(&mut control, &control_ctx, "Black and White Logo"); + assert!(review_preset_checkbox(&mut control, &control_ctx, "Ignore Color")); + let enhanced = review_preset_checkbox(&mut control, &control_ctx, "Enhanced"); + click_control(&mut control, &control_ctx, SAMPLE_TIP); + assert_eq!(control.session.tool_id(), "eyedropper"); + assert!(control.ui.trace_ignore_sampler.is_some()); + click_control(&mut control, &control_ctx, "Enhanced"); + assert_ne!(review_preset_checkbox(&mut control, &control_ctx, "Enhanced"), enhanced, "fixture: the real Enhanced checkbox changed"); + assert!(review_preset_checkbox(&mut control, &control_ctx, "Ignore Color"), "Enhanced keeps this preset's Ignore Color on"); + assert!(control.ui.trace_ignore_sampler.is_some(), "an on-to-on settings change keeps the pick armed"); + assert_eq!(control.session.tool_id(), "eyedropper"); + assert!(!control.session.tool_options()["imageTraceIgnoreColor"].is_null()); + review_preset_click_opaque_source(&mut control, &control_ctx); + assert!(control.ui.trace_ignore_sampler.is_none(), "the opaque pick completes normally"); + assert_eq!(control.session.tool_id(), "selection"); + click_control(&mut control, &control_ctx, "Trace"); + assert_eq!(settings(&control)["params"]["ignoreWhite"], true); + assert_eq!(settings(&control)["params"]["ignoreColor"], "#255395", "the on-to-on control really accepted the source color"); +} + +#[test] +fn review_followup_preset_off_cancels_sampler_but_enhanced_on_keeps_it() { + review_preset_enhanced_on_control(); + + // Separate causal fixture: Preview off leaves the target/revision valid when a preset turns Ignore Color off. + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + let presets = app.run("imageTrace.presets", json!({})).unwrap(); + let expected = presets["presets"].as_array().unwrap().iter().find(|preset| preset["name"] == "High Fidelity Photo").unwrap()["params"].clone(); + assert_eq!(expected["ignoreWhite"], false, "fixture: High Color's public preset disables Ignore Color"); + assert_ne!(expected["ignoreColor"], "#255395"); + click_control(&mut app, &ctx, "Black and White"); + assert!(review_preset_checkbox(&mut app, &ctx, "Ignore Color")); + click_control(&mut app, &ctx, SAMPLE_TIP); + assert!(app.ui.trace_ignore_sampler.is_some()); + assert_eq!(app.session.tool_id(), "eyedropper"); + let state = app.session.active().unwrap(); + let (document, revision) = (state.doc.clone(), state.revision); + let history = (state.history.undo.len(), state.history.redo.len()); + let paint = app.session.paint.clone(); + click_control(&mut app, &ctx, "High Color"); + review_preset_assert_shown(&mut app, &ctx, "High Fidelity Photo"); + assert!(!review_preset_checkbox(&mut app, &ctx, "Ignore Color"), "the actual preset button made Ignore Color off"); + let state = app.session.active().unwrap(); + assert_eq!(state.doc, document, "Preview off changes the panel draft, not the document"); + assert_eq!(state.revision, revision, "the sampler target binding was not invalidated by a trace"); + assert_eq!((state.history.undo.len(), state.history.redo.len()), history); + assert!(app.ui.trace_ignore_sampler.is_none(), "choosing an Ignore Color-off preset must cancel the armed sampler"); + assert_eq!(app.session.tool_id(), "selection", "cancelling the panel pick restores the previous tool"); + assert!(app.session.tool_options_of("eyedropper")["imageTraceIgnoreColor"].is_null()); + review_preset_click_opaque_source(&mut app, &ctx); + assert!(app.ui.trace_ignore_sampler.is_none()); + assert_eq!(app.session.tool_id(), "selection"); + assert_eq!(app.session.paint, paint); + review_preset_assert_shown(&mut app, &ctx, "High Fidelity Photo"); + assert!(!review_preset_checkbox(&mut app, &ctx, "Ignore Color")); + click_control(&mut app, &ctx, "Trace"); + assert_eq!(settings(&app)["preset"], "High Fidelity Photo", "the following opaque canvas click cannot turn the off preset into Custom"); + assert_eq!(settings(&app)["params"], expected, "the hidden pick cannot replace the off preset's ignored color"); +} + +#[test] +fn review_followup_release_position_survives_a_later_hover_move() { + let (mut app, ctx, point, group) = review_gesture_group_fixture(); + click_control(&mut app, &ctx, SAMPLE_TIP); + app.run("select.none", json!({})).unwrap(); + let at = review_gesture_screen(&app, &ctx, point); + let hover = at + vec2(80.0, 0.0); + assert!(app.canvas_rect.unwrap().contains(hover)); + assert!(at.distance(hover) > ctx.options(|o| o.input_options.max_click_dist)); + let expected = review_gesture_state(&app); + let (start, step) = review_gesture_times(&ctx); + review_gesture_press(&mut app, &ctx, at, start); + review_gesture_release(&mut app, &ctx, at, start + step); + assert_eq!(review_gesture_state(&app), expected, "the stale prefix is consumed"); + review_gesture_press(&mut app, &ctx, at, start + 3.0 * step); + frame_at( + &mut app, + &ctx, + start + 4.0 * step, + vec![ + Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Default::default() }, + Event::PointerMoved(hover), + ], + ); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(ctx.input(|i| i.pointer.interact_pos()), Some(hover)); + assert_eq!(app.session.active().unwrap().selection.objects, vec![group]); + assert_eq!(app.session.active().unwrap().isolation, None, "the first fresh click remains single"); + review_gesture_press(&mut app, &ctx, at, start + 6.0 * step); + review_gesture_release(&mut app, &ctx, at, start + 7.0 * step); + assert!(ctx.input(|i| i.pointer.button_triple_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().isolation, Some(group), "the fresh pair uses release positions, not subsequent hover positions"); +} + +fn review_596866_button(at: Pos2, pressed: bool) -> Event { + Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() } +} + +fn review_596866_owned_release_then_press(coalesced: bool) { + let (mut app, ctx, point, group) = review_gesture_group_fixture(); + click_control(&mut app, &ctx, SAMPLE_TIP); + app.run("select.none", json!({})).unwrap(); + let at = review_gesture_screen(&app, &ctx, point); + let (start, step) = review_gesture_times(&ctx); + review_gesture_press(&mut app, &ctx, at, start); + assert_eq!(app.session.tool_id(), "selection"); + assert!(app.ui.trace_ignore_sampler.is_none()); + assert!(ctx.input(|i| i.pointer.primary_down())); + let document = app.session.active().unwrap().doc.clone(); + let paint = app.session.paint.clone(); + let history = (app.session.active().unwrap().history.undo.len(), app.session.active().unwrap().history.redo.len()); + if coalesced { + frame_at(&mut app, &ctx, start + step, vec![review_596866_button(at, false), review_596866_button(at, true)]); + assert!(ctx.input(|i| i.pointer.primary_released() && i.pointer.primary_pressed() && i.pointer.primary_down())); + } else { + review_gesture_release(&mut app, &ctx, at, start + step); + assert_eq!(app.session.active().unwrap().selection.objects, Vec::::new(), "CONTROL: the owned Up remains consumed"); + review_gesture_press(&mut app, &ctx, at, start + 3.0 * step); + } + let before_release = review_gesture_observation(&app, &ctx); + review_gesture_release(&mut app, &ctx, at, start + 4.0 * step); + let after_release = review_gesture_observation(&app, &ctx); + assert!(after_release.0 && !after_release.1, "the owned prefix and one fresh click form egui's raw Double"); + assert!( + before_release.2 == vec![group] && before_release.3.is_none() && after_release.2 == vec![group] && after_release.3.is_none(), + "coalesced={coalesced}: the first fresh click must select without isolation: before={before_release:?}, after={after_release:?}" + ); + assert_eq!(app.session.active().unwrap().doc, document); + assert_eq!(app.session.paint, paint); + assert_eq!((app.session.active().unwrap().history.undo.len(), app.session.active().unwrap().history.redo.len()), history); + if !coalesced { + review_gesture_press(&mut app, &ctx, at, start + 6.0 * step); + review_gesture_release(&mut app, &ctx, at, start + 7.0 * step); + assert_eq!(app.session.active().unwrap().isolation, Some(group), "CONTROL: the second fresh click still isolates"); + } +} + +#[test] +fn review_596866_owned_up_then_new_down_in_one_frame_keeps_the_next_click_single() { + review_596866_owned_release_then_press(false); + review_596866_owned_release_then_press(true); +} + +#[test] +fn review_596866_second_corrected_release_uses_its_release_position() { + let (mut control, control_ctx, control_point, control_group) = review_gesture_group_fixture(); + let control_at = review_gesture_screen(&control, &control_ctx, control_point); + review_gesture_ordinary_pair(&mut control, &control_ctx, control_at, control_at, control_group); + + let (mut app, ctx, point, group) = review_gesture_group_fixture(); + click_control(&mut app, &ctx, SAMPLE_TIP); + app.run("select.none", json!({})).unwrap(); + let at = review_gesture_screen(&app, &ctx, point); + let hover = review_gesture_screen(&app, &ctx, Point::new(340.0, 250.0)); + assert!(at.distance(hover) > ctx.options(|o| o.input_options.max_click_dist)); + let expected = review_gesture_state(&app); + let (start, step) = review_gesture_times(&ctx); + review_gesture_press(&mut app, &ctx, at, start); + review_gesture_release(&mut app, &ctx, at, start + step); + assert_eq!(review_gesture_state(&app), expected, "the stale prefix is consumed"); + review_gesture_press(&mut app, &ctx, at, start + 3.0 * step); + review_gesture_release(&mut app, &ctx, at, start + 4.0 * step); + assert_eq!(app.session.active().unwrap().selection.objects, vec![group]); + assert_eq!(app.session.active().unwrap().isolation, None, "the first fresh click is single"); + review_gesture_press(&mut app, &ctx, at, start + 6.0 * step); + frame_at(&mut app, &ctx, start + 7.0 * step, vec![review_596866_button(at, false), Event::PointerMoved(hover)]); + assert!(ctx.input(|i| i.pointer.button_triple_clicked(PointerButton::Primary))); + assert_eq!(ctx.input(|i| i.pointer.interact_pos()), Some(hover)); + assert_eq!( + app.session.active().unwrap().isolation, + Some(group), + "the corrected Double belongs to its release on the group, not the later blank hover" + ); +} + +fn review_596866_bound_point(app: &VectorcraftApp, target: NodeId) -> Point { + let state = app.session.active().unwrap(); + let node = state.doc.node(target).unwrap(); + let original = node.children().and_then(|children| children.first()).map_or(node, |child| child.as_ref()); + let NodeKind::Image(image) = &original.kind else { panic!("the retained binding has a source image") }; + image.xf * Point::new(f64::from(image.width) * 0.25, f64::from(image.height) * 0.5) +} + +fn review_596866_source_image(app: &VectorcraftApp, target: NodeId) -> NodeId { + let state = app.session.active().unwrap(); + let node = state.doc.node(target).unwrap(); + let original = node.children().and_then(|children| children.first()).map_or(node, |child| child.as_ref()); + assert!(matches!(original.kind, NodeKind::Image(_)), "the retained binding has an original source image"); + original.id +} + +fn review_596866_pick_binding(app: &mut VectorcraftApp, ctx: &egui::Context) -> NodeId { + click_control(app, ctx, SAMPLE_TIP); + let target = app.ui.trace_ignore_sampler.as_ref().unwrap().target; + let source = review_596866_source_image(app, target); + let point = review_596866_bound_point(app, target); + let at = review_gesture_screen(app, ctx, point); + let (start, step) = review_gesture_times(ctx); + review_gesture_press(app, ctx, at, start); + review_gesture_release(app, ctx, at, start + step); + settle(app, ctx); + assert!(app.ui.trace_ignore_sampler.is_none(), "an opaque original pixel completes the pick"); + source +} + +fn review_596866_ignore_color(app: &VectorcraftApp, source: NodeId) -> Value { + let doc = &app.session.active().unwrap().doc; + assert!(matches!(doc.node(source).unwrap().kind, NodeKind::Image(_)), "retrace retains the original source image identity"); + let trace = doc.node(doc.parent_of(source).unwrap()).unwrap(); + assert_eq!(trace.children().unwrap().first().unwrap().id, source, "the source remains the trace's first child"); + trace.extras().trace.as_ref().expect("the source's current parent is an Image Trace")["params"]["ignoreColor"].clone() +} + +fn review_596866_nested_trace_selection() -> (VectorcraftApp, egui::Context, NodeId, NodeId) { + let (mut app, ctx) = fixture(true, [37, 83, 149], true); + let first = selected(&app).id; + let parent = review_gesture_enclose_source(&mut app, first); + let bytes = { + let state = app.session.active().unwrap(); + let original = state.doc.node(first).unwrap().children().unwrap()[0].as_ref(); + let NodeKind::Image(image) = &original.kind else { panic!("the first trace retains its input") }; + state.doc.images[&image.key].bytes.clone() + }; + app.run( + "file.place", + json!({"name": "second-sampler-source.png", "dataBase64": vectorcraft_format::base64_encode(&bytes), "link": false, "at": [280, 150]}), + ) + .unwrap(); + app.run("imageTrace.make", json!({"preset": "Default", "params": {"mode": "blackAndWhite", "threshold": 127, "noise": 1, "ignoreWhite": true}})) + .unwrap(); + let second = selected(&app).id; + assert_ne!(first, second); + app.run("select.set", json!({"ids": [parent.0, first.0, second.0]})).unwrap(); + settle(&mut app, &ctx); + let state = app.session.active().unwrap(); + assert_eq!(state.selection.objects, vec![parent, first, second], "CONTROL: the public selection keeps the ordinary ancestor and nested trace"); + assert!(state.doc.node(parent).unwrap().extras().trace.is_none(), "the selected ancestor is not itself traceable"); + assert_eq!(state.doc.paint_order([first, second]), vec![first, second], "the nested trace precedes the top-level trace"); + (app, ctx, first, second) +} + +#[test] +fn review_596866_preview_retraces_the_retained_sampler_binding() { + let (mut control, control_ctx) = fixture(true, [37, 83, 149], true); + let control_source = review_596866_pick_binding(&mut control, &control_ctx); + assert_eq!(review_596866_ignore_color(&control, control_source), "#255395", "CONTROL: a single trace receives its sampled color"); + + let (mut app, ctx, first, second) = review_596866_nested_trace_selection(); + click_control(&mut app, &ctx, SAMPLE_TIP); + let bound = app.ui.trace_ignore_sampler.as_ref().unwrap().target; + assert!(bound == first || bound == second); + let other = if bound == first { second } else { first }; + let other_before = app.session.active().unwrap().doc.node(other).unwrap().clone(); + let bound_source = review_596866_source_image(&app, bound); + assert_ne!(review_596866_ignore_color(&app, bound_source), "#255395", "CONTROL: the sample must change the bound trace's stored color"); + let point = review_596866_bound_point(&app, bound); + let at = review_gesture_screen(&app, &ctx, point); + let (start, step) = review_gesture_times(&ctx); + review_gesture_press(&mut app, &ctx, at, start); + review_gesture_release(&mut app, &ctx, at, start + step); + settle(&mut app, &ctx); + let bound_color = review_596866_ignore_color(&app, bound_source); + let other_after = app.session.active().unwrap().doc.node(other).cloned(); + assert!( + bound_color == "#255395" && other_after.as_ref() == Some(&other_before), + "Preview must update only retained sampler target {bound:?}: bound_color={bound_color}, other_changed_or_missing={}", + other_after.as_ref() != Some(&other_before) + ); +} + +fn review_596866_grid_visible(app: &VectorcraftApp) -> bool { + vectorcraft_tools::distort::perspective::PerspectiveGrid::current(&app.session.active().unwrap().doc).visible +} + +fn review_596866_hidden_grid_fixture() -> (VectorcraftApp, egui::Context) { + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + app.select_tool("perspectiveGrid"); + assert!(review_596866_grid_visible(&app), "CONTROL: a deliberate fresh tool choice shows the grid"); + app.run("perspective.grid.show", json!({"visible": false})).unwrap(); + settle(&mut app, &ctx); + assert_eq!(app.session.tool_id(), "perspectiveGrid"); + assert!(!review_596866_grid_visible(&app)); + (app, ctx) +} + +#[test] +fn review_596866_successful_pick_preserves_a_hidden_perspective_grid() { + let (mut control, _) = review_596866_hidden_grid_fixture(); + let revision = control.session.active().unwrap().revision; + control.select_tool("perspectiveGrid"); + assert!(review_596866_grid_visible(&control), "CONTROL: explicitly choosing the tool again still shows the grid"); + assert!(control.session.active().unwrap().revision > revision); + + let (mut app, ctx) = review_596866_hidden_grid_fixture(); + let expected = review_gesture_state(&app); + let source = review_596866_pick_binding(&mut app, &ctx); + assert_eq!(app.session.tool_id(), "perspectiveGrid"); + let observed = review_gesture_state(&app); + let visible = review_596866_grid_visible(&app); + click_control(&mut app, &ctx, "Trace"); + assert_eq!(review_596866_ignore_color(&app, source), "#255395", "CONTROL: the valid Preview-off pick really changed the panel draft"); + assert!(!visible, "returning from the temporary sampler must not show the hidden grid"); + assert_eq!(observed, expected, "the Preview-off pick must not change document, selection, revision, history or paint"); +} + +fn review_596866_coalesced_fresh_suffix(dragged: bool) { + let (mut app, ctx, point, group) = review_gesture_group_fixture(); + click_control(&mut app, &ctx, SAMPLE_TIP); + app.run("select.none", json!({})).unwrap(); + let at = review_gesture_screen(&app, &ctx, point); + let distance = ctx.options(|o| o.input_options.max_click_dist); + let away = at + vec2(distance + 8.0, 0.0); + assert!(away.distance(at) > distance && app.canvas_rect.unwrap().contains(away)); + let (start, step) = review_gesture_times(&ctx); + review_gesture_press(&mut app, &ctx, at, start); + assert_eq!(app.session.tool_id(), "selection"); + assert!(app.ui.trace_ignore_sampler.is_none() && ctx.input(|i| i.pointer.primary_down())); + let mut events = vec![review_596866_button(at, false), review_596866_button(at, true)]; + if dragged { + events.extend([Event::PointerMoved(away), Event::PointerMoved(at)]); + } + events.push(review_596866_button(at, false)); + frame_at(&mut app, &ctx, start + step, events); + assert!(ctx.input(|i| i.pointer.primary_pressed() && i.pointer.primary_released() && !i.pointer.primary_down())); + assert!(ctx.input(|i| i.pointer.button_clicked(PointerButton::Primary)), "the old owned release really contributed a raw click"); + assert_eq!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary)), !dragged, "only the valid fresh suffix is a second raw click"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![group], "the fresh Down still selects the group"); + assert_eq!(app.session.active().unwrap().isolation, None, "neither the first fresh click nor an out-and-back drag may isolate"); + // The ordinary tool receives its Up in the next empty frame; no document/history oracle + // forbids legitimate drag completion work. + frame_at(&mut app, &ctx, start + 2.0 * step, vec![]); + assert_eq!(app.session.active().unwrap().isolation, None); + review_gesture_press(&mut app, &ctx, at, start + 3.0 * step); + review_gesture_release(&mut app, &ctx, at, start + 4.0 * step); + if dragged { + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().selection.objects, vec![group]); + assert_eq!(app.session.active().unwrap().isolation, None, "the invalid suffix must not advance ordinary click history"); + review_gesture_press(&mut app, &ctx, at, start + 6.0 * step); + review_gesture_release(&mut app, &ctx, at, start + 7.0 * step); + } + assert!(ctx.input(|i| i.pointer.button_triple_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().isolation, Some(group), "the second qualifying ordinary click still isolates: dragged={dragged}"); +} + +#[test] +fn review_596866_coalesced_fresh_release_qualifies_its_own_click() { + review_596866_coalesced_fresh_suffix(false); + review_596866_coalesced_fresh_suffix(true); +} + +fn review_597048_key(pressed: bool) -> Event { + Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() } +} + +#[test] +fn review_597048_escape_returns_to_a_hidden_grid_without_fresh_activation() { + let (mut control, _) = review_596866_hidden_grid_fixture(); + control.select_tool("perspectiveGrid"); + assert!(review_596866_grid_visible(&control), "CONTROL: explicit fresh selection still shows the grid"); + let (mut app, ctx) = review_596866_hidden_grid_fixture(); + let expected = review_gesture_state(&app); + click_control(&mut app, &ctx, SAMPLE_TIP); + assert_eq!(app.session.tool_id(), "eyedropper"); + frame(&mut app, &ctx, vec![review_597048_key(true)]).textures_delta.clear(); + frame(&mut app, &ctx, vec![review_597048_key(false)]).textures_delta.clear(); + assert!(app.ui.trace_ignore_sampler.is_none()); + assert_eq!(app.session.tool_id(), "perspectiveGrid"); + assert!(!review_596866_grid_visible(&app), "Escape returns without revealing the grid"); + assert_eq!(review_gesture_state(&app), expected, "cancellation changes no document, revision, history, selection or paint"); +} + +fn review_597048_down_pixel(later_move: bool) { + let (mut app, ctx) = fixture(true, [37, 83, 149], false); + let source = review_596866_source_image(&app, selected(&app).id); + let pressed = review_gesture_screen(&app, &ctx, source_point(&app, 0.25)); + let hover = review_gesture_screen(&app, &ctx, source_point(&app, 0.75)); + assert_ne!(pressed, hover); + let expected = review_gesture_state(&app); + click_control(&mut app, &ctx, SAMPLE_TIP); + let mut events = vec![Event::PointerMoved(pressed), review_596866_button(pressed, true)]; + if later_move { + events.push(Event::PointerMoved(hover)); + } + frame(&mut app, &ctx, events).textures_delta.clear(); + assert_eq!(ctx.input(|i| i.pointer.interact_pos()), Some(if later_move { hover } else { pressed })); + assert_eq!(app.session.tool_id(), "selection"); + assert!(app.ui.trace_ignore_sampler.is_none()); + assert_eq!(review_gesture_state(&app), expected, "Preview off stores a panel draft only"); + frame(&mut app, &ctx, vec![review_596866_button(if later_move { hover } else { pressed }, false)]).textures_delta.clear(); + click_control(&mut app, &ctx, "Trace"); + assert_eq!(review_596866_ignore_color(&app, source), "#255395", "the sampled pixel belongs to Down, later_move={later_move}"); +} + +#[test] +fn review_597048_sampler_uses_down_pixel_before_a_later_move() { + review_597048_down_pixel(false); + review_597048_down_pixel(true); +} + +fn review_597048_coalesced_pair(sampler_prefix: bool) { + let (mut app, ctx, point, group) = review_gesture_group_fixture(); + let at = review_gesture_screen(&app, &ctx, point); + if sampler_prefix { + click_control(&mut app, &ctx, SAMPLE_TIP); + } + app.run("select.none", json!({})).unwrap(); + let (start, step) = review_gesture_times(&ctx); + if sampler_prefix { + let expected = review_gesture_state(&app); + review_gesture_press(&mut app, &ctx, at, start); + review_gesture_release(&mut app, &ctx, at, start + step); + assert_eq!(review_gesture_state(&app), expected, "the stale prefix was consumed in the earlier frame"); + } + frame_at( + &mut app, + &ctx, + start + 3.0 * step, + vec![ + Event::PointerMoved(at), + review_596866_button(at, true), + review_596866_button(at, false), + review_596866_button(at, true), + review_596866_button(at, false), + ], + ); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert_eq!(ctx.input(|i| i.pointer.button_triple_clicked(PointerButton::Primary)), sampler_prefix); + assert_eq!(app.session.active().unwrap().isolation, Some(group), "two ordinary clicks isolate after an earlier-frame prefix"); + app.run("object.exitIsolation", json!({"all": true})).unwrap(); + review_gesture_press(&mut app, &ctx, at, start + 5.0 * step); + review_gesture_release(&mut app, &ctx, at, start + 6.0 * step); + assert!(ctx.input(|i| i.pointer.button_triple_clicked(PointerButton::Primary))); + assert_eq!(app.session.active().unwrap().isolation, None, "the next ordinary Triple must not inherit a corrected Double"); +} + +#[test] +fn review_597048_two_ordinary_clicks_in_one_frame_survive_sampler_correction() { + review_597048_coalesced_pair(false); + review_597048_coalesced_pair(true); +} + +#[test] +fn review_597048_a_later_drag_release_does_not_replace_a_qualified_double_click() { + let (mut control, control_ctx, point, group) = review_gesture_group_fixture(); + let at = review_gesture_screen(&control, &control_ctx, point); + review_gesture_ordinary_pair(&mut control, &control_ctx, at, at, group); + let (mut app, ctx, point, group) = review_gesture_group_fixture(); + app.run("select.none", json!({})).unwrap(); + let at = review_gesture_screen(&app, &ctx, point); + let blank = review_gesture_screen(&app, &ctx, Point::new(340.0, 250.0)); + let distance = ctx.options(|o| o.input_options.max_click_dist); + let away = blank + vec2(distance + 8.0, 0.0); + assert!(app.canvas_rect.unwrap().contains(away) && away.distance(blank) > distance); + let (start, step) = review_gesture_times(&ctx); + review_gesture_press(&mut app, &ctx, at, start); + review_gesture_release(&mut app, &ctx, at, start + step); + review_gesture_press(&mut app, &ctx, at, start + 3.0 * step); + frame_at( + &mut app, + &ctx, + start + 4.0 * step, + vec![ + review_596866_button(at, false), + Event::PointerMoved(blank), + review_596866_button(blank, true), + Event::PointerMoved(away), + review_596866_button(away, false), + ], + ); + assert!(ctx.input(|i| i.pointer.button_double_clicked(PointerButton::Primary))); + assert!(!ctx.input(|i| i.pointer.button_triple_clicked(PointerButton::Primary)), "the out-of-slop drag is not a third click"); + assert_eq!(ctx.input(|i| i.pointer.interact_pos()), Some(away)); + assert_eq!(app.session.active().unwrap().isolation, Some(group), "the qualified Double belongs to the earlier group release"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 2872068930..079b26ac0f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -276,6 +276,9 @@ point (the first stop or point when none is selected). `ui.colorWheel {view?, ch shows the wheel or the box (a color field with a channel strip at its right), picks the box's channel, shows the other colors of a harmony rule as markers on the wheel's ring, and shows or hides the color vision row; it returns the settings, and `ui.inspect` reports them as `ui.color_wheel`. +The key `sliders` shows OKLCH Sliders, HSL Sliders or +neither (`"oklch"`, `"hsl"` or `"none"`; `"oklch"` is an error while the active document's RGB space, its assigned +profile or else the working RGB space, is not sRGB), and the settings carry it too. Edit Colors dialogs: `ui.colorBalanceDialog` opens Adjust Colors (`colorBalance`: fields `mode` `gray`/`rgb`/`cmyk`/ `global`, the channels `r` `g` `b` / `c` `m` `y` `k` / `gray` / `tint` (global mode) from −100 to 100, `convert`, `fill`, `stroke`, @@ -300,18 +303,30 @@ luminosity}`, percent from -100 to 100, 0 by default). The dialog sends a non-ze colors; colors opened alone are saved as a group with the change. `display` sets how the Edit tab shows the new colors: `smooth` (the smooth wheel, also when unset; each opening starts there), `segmented` (a wheel of solid patches, 24 hues by 5 saturations, whose markers move as freely) or `bars` (a solid bar per recolored color in row order; a click -selects its row for the sliders and a drag moves the row without changing a color). `wheelTool` turns on a wheel tool -on either wheel: `add` (the Add Color tool) adds a click as a new color, the hue and saturation clicked at the base -color's brightness (the patch's color on the segmented wheel), in a new row with no current colors (`from: []`) and +selects its row for the sliders and a drag moves the row without changing a color; the moved row keeps the color group +swatch it took). `wheelTool` turns on a wheel tool +on either wheel: `add` (the Add Color tool) adds a click as a new color, the hue and saturation clicked at the selected +color's brightness (the base color's when none is selected; the patch's color on the segmented wheel), in a new row with no current colors (`from: []`) and `added: true` that becomes the selected row; `remove` (the Remove Color tool) removes the color of the marker clicked. `wheelAxes: "hueBrightness"` makes both wheels show hue and brightness: brightness runs from black at the center to -full at the edge, the wheel is drawn at the base color's saturation, a marker drag sets hue and brightness, the slider -under the wheel sets saturation, and Add Color adds the hue and brightness clicked at the base color's saturation. +full at the edge, the wheel is drawn at the selected color's saturation (the base color's when none is selected), a marker drag sets hue and brightness, the slider +under the wheel sets saturation, and Add Color adds the hue and brightness clicked at the selected color's saturation. `hueSaturation`, unset (each opening) or any other value shows hue and saturation; switching changes no color. A color bar's right-click menu has Remove Color too. The base color can't be removed. A removed color's row is dropped, unless it has current colors and art or a group is open: it then keeps them with `to: null`, that art keeps its colors, and the -group's swatch at that place is removed. A row with no current colors recolors no art; with a group, the new color of +group's swatch at that place is removed, unless the row is excluded: an excluded row with current colors leaves the group's swatch at its place as it is. A row with no current colors recolors no art; with a group, the new color of one with `added: true` that is not excluded is added to the group after the group's other colors, and a row made with New Row adds none. +The base color is the row with `base: true`, or the first color the Edit tab shows when no row has it; the harmony rules +build from it, and selecting another color for the sliders leaves it the base. A right-click on a wheel marker or a +color bar opens a menu with Set As Base Color (moves `base: true` to that row), Select Shade (a grid of the color's hue +at 7 saturations, 0% to 100%, by 7 brightnesses, 100% down to 14%; a click moves the color there as a drag of its +marker would, so linked colors follow), Color Picker and Remove Color; the base color's menu has neither Set As Base +Color nor Remove Color. A right-click elsewhere on either wheel offers Add New Color, which adds a color as the Add +Color tool does. A color added on the line from the center to a marker moves with that marker while the colors are +unlinked: the marker's row gets `tie: n` and the added row `follows: n`, and dragging the marker, or Select Shade on +it, moves every row that follows its `tie` by the same change. Set Current Color As Base Color, before the color chips, +makes the selected color the base. The rows keep these marks when Randomize (`recolor.randomize`) or Prominent Colors +(`recolor.weigh`) changes them, and the rows the dialog sends `recolor.apply` leave `base`, `tie` and `follows` out. `groupStorage` shows the Color Groups list (true when the dialog opens); setting `group` to a color group's name makes it the group being edited, as opening on it does, and refuses a name no group has; `groupAction` (`save`, `new` or `delete`) runs the list's Save Changes, New Color Group or Delete button on the next frame, or first on confirm (see diff --git a/docs/dimensions.md b/docs/dimensions.md index e90e4ecf20..7acc2155f6 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -91,6 +91,12 @@ alignment). **Position** is **Away from the Line** (the label on the far side of from the object) or **Between Line and Object**; **Alignment** is **Left**, **Center** or **Right** along the line. **Save** keeps them for new dimensions; existing ones don't change. +**Arrow Style** lists **Filled**, **Open**, **Tick** and **None**, then every other built-in +arrowhead of the Stroke panel, each with a drawn preview before its name. Custom arrowheads are not +listed. A version that has the arrowhead in the Stroke panel but not in Arrow Style keeps the saved +arrows of such a dimension until it draws the dimension again, and then draws **Filled** arrows. A +version without the arrowhead does not open the file. + Scale means **drawing : real size**, independent of zoom. At **1:10** a 1 in line on the page is labelled 10 in; at **10:1**, 0.1 in. It scales lengths, not angles or the size of text and arrows. diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index faf32952f7..05338818f1 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; 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: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group instead of reading as nested clipping groups that clip nothing or stop the editing data from being read; previously: PDF import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF export writes the document language as the catalog's `/Lang`, #3644; PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (`.ai` import: a stroke's arrowheads, the symbols its style names, come in as custom arrowheads with their tip on, or past, the path's end, as the drawn art places it, and the line stopping where the symbol's sample of it ends, #8188; PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; 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: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group instead of reading as nested clipping groups that clip nothing or stop the editing data from being read; previously: PDF import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF export writes the document language as the catalog's `/Lang`, #3644; PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art, #6570; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page, #3179; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). @@ -384,6 +384,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | `.ai` import: a stroke's arrowheads were left out, so lines came in without their heads (#8188). A Stroke Style filter's stroke dictionary names each end's head as a symbol of the file (`/GObjRef : (name) /SymbolArt ; (BSArrowBeginSymbol)` or `(BSArrowEndSymbol)`), with its scale in percent (`BSArrowEndScale`, and `BSArrowBeginScale` read the same way; 100 without one). As the files have it, such a symbol's art (y down, as symbols are read) points right along a straight, level sample of the line: an open stroked path with no fill, which ends where the line stops under the head. The rest of the art that paints is the head, its tip its rightmost point, at one symbol unit a head weight (the stroke's weight at the scale). The head comes in as a custom arrowhead with that outline and that stop (a custom head now carries an optional stop, else its line ends halfway along it, as before). Its placement is the one of the two (tip on the end of the path, or Extend, the tip past it by the line's length under the head) that gives the object its drawn art's bounds; the user's file has every tip on its path's end. A stroke keeps its drawn look when neither placement gives those bounds (heads on other subpaths, say) or both do while a head moves 0.2 pt or more between them (a line whose end lies inside the bounds of its other segments), when its symbol isn't read whole or isn't read as a head (no sample or more than one, a sample that isn't 1 pt wide, as in art stored at a Large Canvas scale, art other than paths, compound paths and groups such as a clip group, a group with fills or strokes of its own, effects, brushes, partial opacity or an opacity mask), when its dictionary holds another `BSArrow` entry beside heads, when a scale is outside 1–1000 %, or when the head's weight would be under the 0.25 pt least one VectorCraft draws; a graphic style with such a stroke isn't read rather than read without its heads, and one with heads takes them on the end of the path, so an object whose heads are read past its ends isn't linked to its listed style. Measured on a user's file of ten arrows (used locally, never committed): every line gets its heads, and drawn at 4× its pixels match the file's own page but for 3 of 9,825 inked ones (0.24.1: 1,232 differ). Tests `a_strokes_arrowhead_symbols_are_its_arrowheads`, `a_strokes_start_arrowhead_points_back_and_keeps_its_side`, `a_stroke_takes_both_heads_at_their_own_scales`, `heads_drawn_past_the_path_extend_it`, `arrowheads_this_does_not_read_keep_the_drawn_look`, `an_arrowhead_entry_without_heads_leaves_the_stroke_read` in `crates/eps/src/import/ai/tests.rs`, `heads_whose_placement_the_drawn_bounds_leave_open_keep_the_drawn_look`, `a_head_that_stays_put_leaves_a_moving_heads_placement_open`, `a_style_library_reads_the_heads_of_symbols_defined_after_its_styles` in it, `a_symbol_entry_cut_short_leaves_the_next_style_read` and `a_comment_inside_a_symbol_entry_is_skipped` in `crates/eps/src/import/ai/style/tests.rs`, `partly_transparent_or_masked_art_makes_no_head` in `crates/eps/src/import/ai/arrowhead.rs`, fuzzed by `ai_arrowhead_strokes_never_panic`; scores unchanged | | 2026-11-19 | minor | PDF import (#8549 follow-up): type filled and stroked after a page of type filled only came in as a filled object and a stroked one: since #8549 lines filled only are kept for a stroke pass too, and the glyphs of the lines finished past the 64 kept were remembered until the next stroke, so `2 Tr (Title) Tj` after more than 64 lines of type filled only took its first stroke for the start of a stroke pass over them, always once more than 4,096 glyphs had been finished so. Those glyphs are now forgotten when anything else is drawn (a path, an image, a Type 3 glyph's art, a change of blend mode or soft mask: nothing is drawn between an operator's fill pass and its stroke pass), and past the first 4,096 glyphs none are remembered instead of every stroke matching. A `TJ` over more lines than are kept still comes in as a filled object and a stroked one for each part, also when it ends where it began, and when a glyph kept as an outline comes before that (the line it starts keeps the glyphs of the lines finished). Remaining: with nothing drawn between them, type filled and stroked at exactly the place, font, size and text of a glyph filled only on a line finished so still comes in as a filled object and a stroked one, as the device can't tell its stroke pass from the start of one over that glyph. Tests: `type_filled_and_stroked_after_a_dense_page_of_filled_type_is_filled_and_stroked`, `type_filled_and_stroked_over_a_finished_glyph_after_a_path_is_filled_and_stroked`, `an_outline_glyph_in_a_tj_over_more_lines_than_are_kept_leaves_fill_and_stroke_apart`; scores and estimates unchanged. | | 2026-11-18 | minor | PDF import (#8543): type filled and stroked (text rendering modes 2 and 6) by a `TJ` whose kerning starts a new line part way through came in as four type objects, each part filled only and each part stroked only over it: the reader fills every glyph of the operator before it strokes them, and the line the first part was gathered on was finished before the stroke pass came back to it. Lines an operator's fill pass finishes while a stroke may still be drawn over them are now kept (up to 64 besides the open line, so a `TJ` over up to 65 lines: one over more stays a filled object and a stroked one for each part, as before) until the stroke pass goes past them, and the pass's strokes are held (up to 4096: a longer pass is matched a part at a time, each part to glyphs filled one right after another, never to one an operator before it filled) until it ends, then matched to the glyphs filled last, in the order they were filled, so each stroke finds the glyph it was filled as, also where the `TJ` draws a glyph again where it drew one (`[(A) -3500 (B) 4834 (A)] TJ`). Each part comes in as one type object filled and stroked, in the order drawn; also a `TJ` that jumps back and one whose kerning starts two new lines. In an `ActualText` span (whose stroke was lost) the replacement text stays one type object on the first glyph's line and in its style, now filled and stroked, also where the `TJ` draws a glyph again: the span's strokes are matched the same way. A stroke over no filled glyph (stroked type of its own) and the start and end of an `ActualText` span end a stroke pass: no stroke after them goes over a glyph filled before them, so none is drawn under type drawn after it, and a later span keeps its own replacement text. Stroke rendering stays stroke only, and translucent type stays a filled object and a stroked one. Tests: `a_tj_whose_kerning_starts_a_new_line_is_filled_and_stroked`, `a_tj_that_draws_a_glyph_again_where_it_drew_one_strokes_each_copy`, `a_stroked_tj_whose_kerning_starts_a_new_line_stays_stroke_only`, `a_translucent_tj_whose_kerning_starts_a_new_line_stays_fill_and_stroke_apart`, `a_long_stroke_pass_strokes_its_own_glyphs_not_one_filled_before`, `a_stroke_after_stroked_type_of_its_own_does_not_join_a_glyph_filled_before`, `a_stroke_in_an_actual_text_span_does_not_take_an_earlier_spans_glyph`, `a_tj_that_draws_a_glyph_again_in_an_actual_text_span_strokes_the_replacement`, `a_tj_over_more_lines_than_are_kept_comes_in_as_fill_and_stroke_apart`, `a_tj_over_more_lines_than_are_kept_that_ends_where_it_began_stays_fill_and_stroke_apart`, `type_after_a_tj_over_more_lines_than_are_kept_is_filled_and_stroked`; scores and estimates unchanged. | | 2026-11-18 | minor | PDF export (#3644): the document language chosen in Document Setup is written as the catalog's `/Lang` (BCP 47, `en-US` by default) and as XMP `dc:language`; a language without a tag writes none. Scores and estimates unchanged. | diff --git a/docs/gaps.md b/docs/gaps.md index 288296debf..9face55df8 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (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; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: 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: 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; 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: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; 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: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; 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; estimate 1–2 h → 0; 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: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; 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, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); 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; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; 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; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (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: 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; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: 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: 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; 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: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; 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: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; 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; estimate 1–2 h → 0; 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: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; 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, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); 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; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; 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; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Scissors snapping update (2026-11-11): with Alt released, hover and cuts use the Pen's path, alignment, intersection and anchor snaps (#6470). Scores and estimates unchanged. @@ -144,6 +144,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall macOS cursor delivery (#2292) is narrowed to a native host adapter using the existing artwork and aligned 1×/2× representations. Headless tests cover visible fallbacks, preparation and ownership; native focus/menu/handback timing, mixed displays, Spotlight and full-screen Spaces remain open validation work (see [hardware parity](hardware-parity.md)). This does not close the interaction-fidelity gap or change its score/estimate. +- **Temporary handle mirroring (#7842):** with Direct Selection, add Control (Command on macOS) after a direction-handle drag begins to mirror the opposite handle at equal length. This includes ordinary paths, type on a path and blend spines; a missing opposite handle is pulled out while the modifier is held. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without the modifier. Letting go returns to the drag's normal handle behavior, Shift constrains before mirroring, and Alt takes independent-handle priority. The existing Control/Command-before-press Selection-tool loan is unchanged, and the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again. This does not add a persistent coupling mode or change Pen, mesh or warp gestures; the broader G1 scope and estimates remain. + - **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. @@ -557,6 +559,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi run hyphenates in its own language (Character panel). English, eleven Indian languages, Bulgarian, Turkish and Russian have break points, and German, Polish, Portuguese and Italian have them in builds that embed their patterns; other languages stay whole apart from the Exceptions list (#394, #4947). +- **Done (2026-11-19):** Links panel row context menu: right-clicking a link row presents an item context menu offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, and Embed Image / Unembed…; right-clicking an unselected row selects it first, preserving selection if already part of a multi-selection. Tests in `crates/ui-egui/src/panels/tests_links.rs`. - **Done (2026-11-18, #8592):** Layers panel guide and blend spine row context menus: right-clicking a ruler guide row shows Hide / Show, Lock / Unlock, Release Guides, Delete and Locate Object / Locate Layer (selecting an unselected editable guide or preserving a multi-guide selection); right-clicking a blend spine row selects the blend and shows Select, Blend Options…, Reverse Spine, Reverse Front to Back, Expand, Release and Locate Object / Locate Layer. Tests in `crates/ui-egui/src/panels/layers/tests.rs`. - **Done (2026-11-14):** Layers panel row context menu: right-clicking a layer, group, or object row shows a context menu (Options…, Duplicate, Delete, Lock Others / Unlock All, Hide Others / Show All, Locate Object, Collect for Export) with proper selection behavior and Undo/Redo tracking. Tests in `crates/ui-egui/src/panels/layers/tests.rs`. - **Done (2026-11-18):** Layers panel guide row context menu: right-clicking a guide row presents specialized actions (Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show). Clicking "Release Guide" converts the guide back to a normal unpainted path using `view.guides.release` in one undo step. Tests in `crates/ui-egui/src/panels/layers/tests.rs`. @@ -715,8 +718,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi libraries ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html)): Window › Brush Libraries and the Brushes panel's Brush Libraries Menu open each library in a library panel of - its own (thirteen original libraries generated in code: Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes (one - bristle brush for each tip shape), Pattern Borders, Scatter Shapes, Stipple (Fine, Dense, Soft and Bold dot textures), Game Trails, Energy Beams, Dry Media (grainy chalk, pencil, crayon and charcoal art brushes), Tech Circuit (Circuit Trace, Bus Lines and Terminal Nodes) and Arrows (Solid, Open, Double, Chevron and Dashed Arrow); User Defined; Other Library… reads the brushes of any document VectorCraft opens); a + its own (fourteen original libraries generated in code: Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes (one + bristle brush for each tip shape), Pattern Borders, Scatter Shapes, Stipple (Fine, Dense, Soft and Bold dot textures), Game Trails, Energy Beams, Dry Media (grainy chalk, pencil, crayon and charcoal art brushes), Tech Circuit (Circuit Trace, Bus Lines and Terminal Nodes), Engraving (Fine, Dense, Tapered and Broken Hatching) and Arrows (Solid, Open, Double, Chevron and Dashed Arrow); User Defined; Other Library… reads the brushes of any document VectorCraft opens); a click adds a brush to the document's Brushes with the patterns, symbols and other resources its art uses, as one undo step (applied to the selected paths in the same step), dragging one onto a path adds and applies it and @@ -739,7 +742,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi painted with the texture effects, and Paper Cutouts with six original layered-paper styles, two colored cut edges and crisp cast shadows; User Defined; Other Library…; `graphicStyle.libraries`, `graphicStyle.addFromLibrary`). -- **Missing:** more built-in brush libraries beyond the eleven shipped (and further graphic-style libraries beyond the twelve shipped, and further symbol libraries beyond Basic +- **Missing:** more built-in brush libraries beyond the fourteen shipped (and further graphic-style libraries beyond the twelve shipped, and further symbol libraries beyond Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons and Weather Icons; original, generated in code, never Adobe's); dynamic symbols' `.ai` read and write. - **Estimate:** 3–13 h (estimated). @@ -956,6 +959,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…); right-clicking an unselected link row selects it first, and right-clicking within a multi-selection preserves it; headless tests in `crates/ui-egui/src/panels/tests_links.rs`; scores and estimates unchanged. | | 2026-11-18 | minor | G12: Layers panel context menu on guide rows (Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show); regression tests in `crates/ui-egui/src/panels/layers/tests.rs`; scores and estimates unchanged. | | 2026-11-18 | minor | G4 type: Retype phase 1 (#4934), `type.retype` for outlined text that exactly matches an available font; near matches, the ranked font list and images remain. Scores and estimates unchanged | | 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. | diff --git a/docs/mcp.md b/docs/mcp.md index c242a3c9be..9c4dbd7ce4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -689,6 +689,17 @@ each have a hue of their own (not `monochromatic`, `shades`, `complementary2`, ` `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, harmony, harmonyRule, vision}`, 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 +the box), and `"none"` hides them in any RGB space. `"oklch"` is an error while the active document's RGB space is +not sRGB: the profile assigned to the document when it has one, else the working RGB space of Edit › Color Settings. +`ui.colorWheel {"sliders": "hsl"}` shows HSL Sliders in their place: H, S and L rows with the hue (0 to 360°), +saturation and lightness (0 to 100 %) of the color's display sRGB, as CSS Color 4's `hsl()` defines them. +`color.convert {"color": "#ff0000", "to": "oklch"}` answers the color's OKLCH as `[L %, C, H°]` of its display sRGB. +A color outside sRGB (a Lab or CMYK color, an RGB color in a wider RGB space, or RGB numbers past 0 to 1) is clipped +to sRGB first. +The answer of `ui.colorWheel` and the settings also carry `sliders`. + `ui.colorWheel {"vision": true}` turns on the Color Wheel panel's Show Color Vision Preview, as its panel menu does: a row of four chips under the wheel or the box shows the current color through the protanopia, deuteranopia and tritanopia simulations of `view.proofSetup`, and for achromatopsia as the gray with the color's CIE L*. Each @@ -724,7 +735,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `press_key` | `{key, mods?}` | Remote: a real key event. Headless: runs the command or tool bound to that shortcut, or sends the key to the busy tool (digits too: `5` while dragging with the Perspective Selection tool; `e` while dragging a Selection or Group Selection marquee; `c` and `f` while dragging out an arc; `f`, `v`, `x` and `c` while dragging out a rectangular or polar grid). | | `type_text` | `{text}` | Remote only. | | `answer_dialog` | `{set?: [{field, value?}], action?}` | Remote only. Sets fields of the app's open dialog in the order given with one `ui.dialog.set {fields, action?}` (a missing `value` is `null`). The app stores all of them or none, then answers that same dialog with `action` in the same request: `confirm` (OK) or `cancel`. Another connection cannot open a dialog between the two steps. When the app refuses the `ui.dialog.set`, for example because no dialog is open, the call is an error and the dialog is not confirmed or canceled. `set` cannot change a `__` field other than the dialog's controls held under a `__` name (such as Save PDF's `__section` or the Preferences `__search`): the `__command` and `__params` of a `confirm` or `command` dialog, and every other `__` field that holds what OK acts on, are refused with "the `` dialog cannot set protected field ``", so OK runs what the dialog was opened for. `action` alone is sent as `ui.dialog.confirm` or `ui.dialog.cancel`. Give `set`, `action` or both; `set` holds at most 256 fields. `inspect_ui` shows the open dialog and its fields as `ui.dialog`. Returns `{dialog, result}`: the dialog after the fields were set (or `null`) and the reply to `confirm` or `cancel` (or `null`). After `invoke_menu` `app.quit`, `file.close` or `file.closeAll` replies `{"pending": "saveChanges"}`, `{action: "confirm"}` saves, `{set: [{field: "discard", value: true}], action: "confirm"}` closes without saving and `{action: "cancel"}` cancels the close or quit. | -| `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. UI commands such as `view.*` and `window.*` are in `command_list` with `ui: true`; running them needs the desktop app (`--connect`). | +| `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. UI commands such as `view.*` and `window.*` are in `command_list` with `ui: true`; running them needs the desktop app (`--connect`). The app refuses `attributes.openUrl`, `file.export.svg.browser`, `file.saveForWeb.browser` and `file.showPackage` for every control and MCP request, since each opens another app, so the headless error for them does not suggest `--connect`. | | `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. | | `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. An app that does not send the image back writes a window capture without `path` to a file in a new folder inside the system's temporary folder (on Unix only the user can open it); the server reads the file and then removes the folder, also when the capture or the read fails. | | `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`). Templates (`.vctemplate`, `.ait`, `.cdt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin."` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | @@ -825,6 +836,35 @@ from −100 to 100 and is 50 when left out with `lengthX` and `lengthY`, or 100 `` `baseAlong` must be one of x, y ``), as is a `slope` outside its range; the arc is not drawn and no undo step is added. +`shape.threePointArc {start: [x, y], end: [x, y], through?: [x, y], toward?: [x, y], at?: "start"|"end"}` draws an +open circular arc from `start` to `end` and selects it. With `through`, the arc passes through that point. With +`toward`, the arc leaves `start` heading toward that point, so the line from `start` to the point is the arc's tangent +there. With `at: "end"`, the line from `end` to the point is the tangent at `end` instead. `at` is `"start"` when left +out, and `at` with `through` is an error. The arc has no fill and the current stroke (black when the stroke is none), +its ends are exactly the two points (it is not pixel-aligned), and it has a smooth anchor at the `through` point and +further smooth anchors so that no curve of the path turns more than a quarter turn. The result is +`{id, cx, cy, radius, sweep}`: the circle's center and radius, and the arc's turn in degrees, positive clockwise on the +page. One undo removes the arc. The command returns an error and draws nothing when two of the points are the same, +when the third point lies on the line through the ends, when the arc would reach past the canvas, when a point is not +`[x, y]`, when both or neither of `through` and `toward` are given, when `at` is anything but `"start"` or `"end"`, and +when `at` is given with `through`. + +The Three-Point Arc tool, in the Line Segment tool's group after the Arc tool, runs this command. A drag from one end to +the other, or a click on each, places the ends; Shift keeps the second end at 45° steps from the first (from General › +Constrain Angle). A click on a third point, or a press dragged to it, then draws the arc through it. With the tool's +`direction` option on, the third point gives the direction the arc leaves the first end in; with `mods.alt`, the +direction is at the second end, and Shift keeps the direction at 45° steps. Three-Point Arc Tool Options (`tool.options`, +or a double-click on the tool) sets `direction` with its Third Point Sets Direction box, and +`]` (with or without Shift) switches it while the ends are placed; the option is saved with the preferences. Until the +third point is placed, the tool shows the arc as a dashed outline, its center as a small cross, the direction line in +direction mode and, with Measurement Labels on, the radius. Where no arc fits, the tool shows "Arc too large" by the +pointer (nothing while the pointer is on an end), and a click there draws nothing and keeps the ends. Escape, and an +edit, Undo or Redo made outside the tool, remove the ends. + +```json +{"name":"run_command","arguments":{"command":"shape.threePointArc","params":{"start":[0,0],"end":[80,0],"through":[40,-40]}}} +``` + While a spiral is being dragged out with the Spiral tool, a `drag` event with `mods.alt` or `mods.cmd` keeps the spiral's inner end at the distance from the center it had on the first modified `drag` event, and the outer end follows the pointer. With `mods.alt` alone, dragging outward adds whole winds of four segments and dragging inward removes @@ -1101,7 +1141,9 @@ art's colours (by default as global swatches the art links to). `swatch.move {names, to?, group?}` reorders swatches or moves them into or out of a colour group (as dragging them in the Swatches panel does); give colour group names instead to reorder the groups. Dropping a swatch on art in the app runs `paint.setFill` (or `paint.setStroke`, the active proxy) with `ids: [the object under the pointer]`. -The Swatches panel menu's commands: `swatch.addUsedColors {selection?, global?}`, `swatch.unused` (a query: the +The Swatches panel menu's commands: `swatch.addUsedColors {selection?, global?}` (Add Used Colors sends `{}`; Add +Selected Colors, on while art is selected, sends `{selection: true, global: true}`; a run with no new color records no +undo step; with Global Edit on, the other members keep their colors), `swatch.unused` (a query: the names Select All Unused selects; a spot swatch counts as used while an image placed from a DCS file has a plate of its ink), `swatch.merge {names}` (the first is kept; gradient stops linked to the others drop their process plates), `swatch.ungroup {name}`, `swatch.renameGroup {group, name}` (Color Group Options: renames the group alone @@ -1227,9 +1269,33 @@ Convert to Grayscale before the switch would give); other colors convert as usua colors that changed in the art, symbols, graph designs and pattern tiles; it does not count the colors of graphic styles and brushes. `edit.colorSettings`, `file.documentColorMode`, `color.convert`, `color.gamutCheck`, `color.loadProfile`, -`color.removeProfile`, `view.proofSetup`, `view.proofColors`, `view.overprintPreview`, `view.separationsPreview` and -`swatch.setSpot` reject a param of the wrong type, such as `"bpc": "no"`, `"on": 1`, `"to": 5` or `"colors": "#fff"`, -and change nothing. Omitting a param or giving null keeps its default. +`color.removeProfile`, `view.proofSetup`, `view.proofSetup.save`, `view.proofColors`, `view.overprintPreview`, +`view.separationsPreview` and `swatch.setSpot` reject a param of the wrong type, such as `"bpc": "no"`, `"on": 1`, +`"to": 5` or `"colors": "#fff"`, and change nothing. Omitting a param or giving null keeps its default. +View › Proof Setup › Customize… (`ui.proofSetupDialog`, dialog `proofSetup`) sets the custom proof through +`view.proofSetup`: `target` `"cmyk:"` or `"rgb:"` names any CMYK or RGB profile as the device to +simulate (a profile that is not loaded is an error), `preserveNumbers` sends the colors' numbers in the document's +space to the device unchanged instead of converting them with `intent` (each color as it is painted, and a placed +CMYK image's own inks; an RGB image's pixels go through their numbers in the document's space, and transparency mixes +the proofed colors on the device's paper), and +`simulateBlack` shows the device's black +as the dark gray it prints (`simulatePaper` does so too, on the paper's color; both act on CMYK devices only). The +reply carries `preserveNumbers` and `simulateBlack` with the other proof settings. +The dialog's Save… and Load… buttons save and load a custom proof setup +([Save or load a custom proof setup](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=148)). +The buttons and the saved setups in View › Proof Setup are desktop only; the web build has neither. Load…'s picker +starts in the Proof Setups folder once a save has made it. +`view.proofSetup.save {path}` writes the current proof setup, or the settings it is given as `view.proofSetup` takes +them, to a proof setup file without changing the proof view; the device must be `workingCmyk`, `cmyk:` or +`rgb:`. `view.proofSetup.load {path}` reads one back, makes it the proof setup and turns Proof Colors on; +`view.proofSetup.read {path}` only returns the file's settings, which is how Load… fills the dialog. All three take +`name` in place of `path` for a setup in the Proof Setups folder next to the preferences, and `view.proofSetup.list` lists the setups +there, at most 100, which View › Proof Setup shows below Customize…. The listing holds the files named +`.vcproof` whose name `name` accepts, the first 100 by name; `truncated` is true when more are there or an entry +could not be read or has a file name that is not valid Unicode, and a folder that cannot be read is an error. A name is +at most 100 characters without path characters. These are VectorCraft's own choices: the file is VectorCraft's own JSON format (extension `.vcproof`) of +at most 64 KiB, checked by size before it is read; a file whose device is a profile that is not loaded is refused +with an error naming the profile, and nothing changes. `view.separationsPreview {soloToggle: plate}` is the Separations panel's Alt-click on a plate's eye: it shows that plate alone, and when that plate is already the only one of the active document's plates shown, it shows every plate, spot plates included ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) @@ -1649,7 +1715,9 @@ A conic gradient (`kind: "conic"`, also accepted as `angle` or `conical`) sweeps draws the extent ellipse, aspect dot and center ring of a radial gradient, without a focal point; a `focal` given for a conic gradient is an error. A negative `aspect` mirrors the sweep (counterclockwise), as reflecting the object does; for the other kinds a negative `aspect` is an error. The Gradient panel's Aspect Ratio field and the aspect dot -keep a mirrored sweep mirrored. Dither and Method apply as they do to a linear gradient. PDF export writes it as a +keep a mirrored sweep mirrored. The default gradient for new art, and the Live Paint Bucket's, fits each object it +paints and keeps no aspect, so `paint.editGradient` with an `aspect` is an error when it edits no object (nothing +selected, the bucket's gradient without `ids`, or a fill edit of a Live Paint group without faces) and leaves the default as it was. Dither and Method apply as they do to a linear gradient. PDF export writes it as a function-based shading (type 1) whose calculator function turns the angle into the ramp, and PDF import reads a function-based shading whose color turns around the origin of its space back as a conic gradient, with its stops' opacity, also when the origin lies outside the painted area; in a PDF/A file, or with more than 97 stops on its @@ -2278,7 +2346,7 @@ naming the key, and leave the document and its undo history as they were: `opaci The blend and envelope commands refuse a string, a number or another value that is not true or false with `` `smooth` must be true or false ``, naming the key, and leave the document, its undo history and the options new blends and envelopes start with as they were: `smooth` in `object.blend.make` and `object.blend.options`; -`independent` and `link` in `object.blend.spine.moveAnchor`; `perpendicular` in `object.blend.spine.reshapeSegment`; `horizontal` +`independent`, `symmetric` and `link` in `object.blend.spine.moveAnchor`; `perpendicular` in `object.blend.spine.reshapeSegment`; `horizontal` in `object.envelope.makeWithWarp`, `resetWithWarp` and `options`, also when an `orientation` is given; `maintainShape` in `object.envelope.resetWithMesh`; `antiAlias`, `distortAppearance`, `distortLinearGradients` and `distortPatternFills` in `object.envelope.options`; and `editing` in `object.envelope.editContents`. A null is read as @@ -2659,7 +2727,8 @@ change anything outside the documents: `script.*` except `script.check`, `plugin `shortcutSet.*`, `help.*`, `print.*`, `library.*`, `importMatches.*`, `edit.undoGroup.*`, `file.recovery.*`, `stroke.widthProfile.*`, saving, importing or deleting a preset, `text.addFontFiles`, `text.findFontFiles`, `text.rescanFonts`, `links.findFiles`, `file.place.queue`, `color.loadProfile`, `color.removeProfile`, `file.print`, -`view.proofSetup`, `view.proofColors`, `view.overprintPreview` and `view.separationsPreview`. It also cannot run +`view.proofSetup`, `view.proofSetup.save`, `view.proofSetup.load`, `view.proofColors`, `view.overprintPreview` and +`view.separationsPreview`. It also cannot run `edit.clearHistory`: a run keeps each document's undo steps from before it and adds one. Calling one of these throws an error. With Data Recovery off for complex documents, a run in the web build does not start while a complex document has unsaved changes. @@ -3823,23 +3892,34 @@ already walks Image Trace. Short agent entry points: [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): `symbol.adjust` takes `method` (`userDefined`, `average` or `random`; not used by `shift`), `usePressure` with `points` as `[x, y, pressure]` (each point's pen pressure, 0..1, is the intensity there), and for `size` - `proportional` (true) and `affectsDensity` (false). `symbol.spray` takes `attributes` + `proportional` (true) and `affectsDensity` (false). With `tool: style`, the style goes on by the brush's strength at + each instance: one sample applies it in full only at the brush's center at intensity 10 or full pressure, and the + samples of a stroke add up (two samples at the center at intensity 5 apply it in full). With `alt`, `userDefined` + and `random` remove all of an instance's appearance items under the brush at once, whatever the brush's strength. + A `style` name the document + has no graphic style for counts as none (the document's first style after the default one). The Symbol Styler and the + Symbol Sprayer (its User Defined Style) send the style last clicked into the Graphic Styles panel's selection. `tool.setOption` on a symbolism tool refuses a `method` or + Symbol Sprayer option that is not one of its names, a non-number `diameter`, `intensity` or `density`, a + `diameter` outside 2..2000 or an `intensity` or `density` outside 1..10, a non-boolean switch, and a `symbol` or + `style` that is neither a name nor null, and sets none of the values. The options dialog's OK checks the same way + before it changes any symbol set's density. + `symbol.spray` takes `attributes` `{scrunch?, size?, spin?, screen?, stain?, style?}`, each `average` or `userDefined`, with `color`, `keepModel` and `style` for the User Defined stain and style (with `style: userDefined`, a `style` the document does not have is an error). `symbol.setDensity {from, to, ids?|id?}` gives the selected symbol sets a new Symbol Set Density. VectorCraft's own rules: - `random` gives each instance its own share of the tool's change for the whole stroke, from none of it to twice - it (the Spinner: a turn either way), the same each time the stroke is applied. + it (the Spinner: a turn either way; the Styler without `shift`: from none to the `userDefined` amount), the same + each time the stroke is applied. - `average` moves each instance's value toward the mean of the instances within the brush at that point: the Scruncher its distance from their middle toward their mean distance, the Sizer the geometric mean of their sizes on the page, whatever their symbols, the Spinner their mean direction, the Stainer and the Styler their mean amount, the Screener their mean opacity. `alt` does not reverse it. An instance already at the mean is left as it is, and no undo step is added when no instance changes. The Screener's average, and the opacity a sprayed instance takes as its average, can be below the 5% that the Screener otherwise stops at. - - With `userDefined` the Styler gives each instance under the brush the whole style, whatever the intensity or the - pen pressure; `random` scales each instance's share by the brush strength there. - - With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the - height) and one point resizes both. With `affectsDensity` an instance also moves away from the point as it grows + - With `proportional` false a drag resizes along its own direction: the width by the drag's horizontal share and + the height by its vertical share (a level drag the width, an upright one the height, a 45° drag both alike), and + one point resizes both. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. - A sprayed instance's `average` values are the means of the selected set's instances within `radius` of the stroke point: their spacing, size on the page (of any symbol), rotation and opacity, and the stain or style of @@ -3849,15 +3929,31 @@ already walks Image Trace. Short agent entry points: - `symbol.setDensity` moves each instance of a set along the line from the middle of the set's instances, to (1.15 − 0.1·`to`) / (1.15 − 0.1·`from`) of its distance from it (each factor at least 0.1), as one undo step, and adds none when no instance moves and every set already has density `to`. `from` is the density each set was - created at or last given, and the `from` passed applies only to a set without one (a group named "Symbol Set" by + created at or last given (a set duplicated has its source's, and a pasted set the one its source had at Copy), + and the `from` passed applies only to a set without one (a group named "Symbol Set" by hand); every set then has density `to`, also one whose instances do not move (one instance, or each locked). A locked or hidden instance stays where it is. It returns `{ids, count}`: the sets changed and the instances moved. - A `method` or an attribute outside these values, a point's third number that isn't a number (in `symbol.spray` too, which does not use it), a `from` or `to` of `symbol.setDensity` outside 1..10, or no symbol set among its - objects, is an error and changes nothing. + objects, is an error and changes nothing. `symbol.spray` takes a `density` number outside 1..10 as the nearer end. - Average leaves an instance without a size (a scale of 0) as it is; the other methods change it. A stroke that changes no instance counts none and adds no undo step. +- The symbolism tools with Shift held ([the manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=199), + [the CS6 reference](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=136)) send + `shift: true` with `symbol.adjust`: a Shift-click with the Symbol Shifter brings the instances under the brush + forward in the stacking order and Alt+Shift sends them backward; the Symbol Sizer keeps the set's density while it + resizes; the Symbol Stainer and the Symbol Styler keep the amount of stain or style and move the color or style + toward the current fill or the selected style. VectorCraft's own rules: + - The Shifter moves each instance within `radius` of any stroke point one place forward among its siblings (with + `alt`, one place backward), past the next one that is not under the brush, once for the whole stroke. It does not + move them on the canvas. It returns `{count}`, the instances that moved. + - The Sizer keeps each instance's center where it is, even with `affectsDensity`. + - The Stainer moves an instance's paint toward `color` by the tool's amount at its distance from the point, and the + Styler toward the style by the brush's strength there, whatever `method` is. A paint with no form between it and + the new one (a solid color and a pattern) takes the new one at once. An instance without a stain or style is left + as it is, and `alt` has no effect. + - No undo step is added when nothing moves or changes. - Dynamic symbols: an instance of a symbol whose `type` is `dynamic` changes the appearance of objects in the symbol's art for itself only and stays linked. `symbol.instance.setAppearance {id?, path, fill?, stroke?, opacity?, blend?}` names the object by `path`, child indices in paint order from the art's root down through its groups (`[]` is the @@ -5341,7 +5437,7 @@ without `groupColors`, its new color then joins `group` after the new colors of `recolor.randomize` and `recolor.weigh` keep such a row, and `recolor.randomize` keeps its `added`. A row without `from`, or with a current color that is not a color, is refused. With art selected, the Recolor Artwork dialog's New Row button (beside Merge) adds such a row above the first selected row, or at the top, with that row's new color, and selects it; Shift-click a row below it and Merge to move that row's colors into it (Merge keeps the topmost selected row's new color). An -empty row does not count toward Colors. While it is empty, the dialog's Edit tab does not show it (its sliders edit +empty row does not count toward Colors. While it is empty and not `added`, the dialog's Edit tab does not show it (its sliders edit the base color when the empty row is selected), the harmony rules, linked moves and the Color Theme Picker leave its new color as it is, and Save All Colors and a new color group saved from colors alone leave its new color out. With `limitTo`, a row's `tint` (a percentage, default 100) gives the art @@ -5392,7 +5488,7 @@ objects are read. As VectorCraft's own rule, each object read weighs the same, s among its pixels; the vector art a symbol instance places counts as one object, and each image it places counts on its own), and similar colors merge (k-means in Lab) into at most `colors` (1 to 64, default 5), each shown by its most used color in its own model. Picks that touch no art return no colors. In the Recolor Artwork dialog the picks are the `themePicks` field: the rows that aren't -excluded and hold current colors take the palette as their new colors in row order, the colors repeating when the rows outnumber them. +excluded and hold current colors or were added on the Edit tab take the palette as their new colors in row order, the colors repeating when the rows outnumber them. ```json {"name":"run_command","arguments":{"command":"recolor.pickTheme","params":{"picks":[{"at":[120,80]},{"rect":[200,40,320,140]}],"colors":4}}} @@ -5418,7 +5514,7 @@ bar sits under the Edit tab's wheel: each row with a share is a part as wide as the largest first. Dragging the edge between two parts moves width between them, and when the drag ends the widths become the `weights` field, which moves the rows' current colors and previews the result. The New Color Group menu beside the link button runs `swatch.newGroup` right away, as its own undo step: Save All Colors saves the new colors -of the rows that are not excluded and hold current colors, in row order, and Save Prominent Colors saves the bar's colors in the bar's order. +of the rows that are not excluded, hold current colors or were added on the Edit tab, and still have one, in row order, and Save Prominent Colors saves the bar's colors in the bar's order. The Recolor Artwork dialog lists the document's color groups on its right, or under the tabs in a window too narrow for both ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). @@ -5690,12 +5786,15 @@ error. ## Brush libraries -Brush libraries are read-only sets of brushes: thirteen generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive with Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow, Bristle +Brush libraries are read-only sets of brushes: fourteen generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive with Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow, Bristle Brushes with one bristle brush for each tip shape, Pattern Borders, Scatter Shapes, Stipple with Fine, Dense, Soft and Bold dot textures, Game Trails, Energy Beams, and Dry Media with the Chalk Grain, Graphite Pencil, Wax Crayon and -Charcoal Dust art brushes, id `dry-media`, Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`, and Arrows with Solid, Open, Double, Chevron and Dashed Arrow art brushes, id `arrows`), the `.vectorcraft` files in the user library folder of the desktop app (User +Charcoal Dust art brushes, id `dry-media`, Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`, Engraving with Fine Hatching, Dense Hatching, Tapered Hatching and Broken Hatching art brushes, id `engraving`, and Arrows with Solid, Open, Double, Chevron and Dashed Arrow art brushes, id `arrows`), the `.vectorcraft` files in the user library folder of the desktop app (User Defined) and the brushes of any document loaded with `brush.loadLibrary` (a document without brushes of its own has the default ones). `brush.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and -`brush.library {library}` returns one's brushes (`name`, `type`; `library` is an id or a name). +`brush.library {library}` returns one's brushes (`name`, `type`; `library` is an id or a name). A name +that a built-in library and a User Defined or loaded library share selects the built-in one; select the other by its +`user/…` or `loaded/…` id. The exact id `artistic` selects the built-in Artistic Brushes library, and `Artistic` +selects it too when no library is named `Artistic`. `brush.addFromLibrary {library, name? | names?}` copies brushes into the document's Brushes as one undo step (no names: the whole library), with the resources their art uses: patterns, symbols, swatches (`swatchConflict` as for `edit.paste`), graphic styles and images. Brushes the document already has (same name and definition) are reported @@ -5960,6 +6059,20 @@ details are VectorCraft's own rules; the help page says only that the option mov (). `pattern.list` reports it as `moveTileWithArt`. A `pattern.options` call that changes nothing records no undo step. +`object.pattern.replaceArt {name, ids?}` (Replace Pattern Art) makes copies of the selected art, or of `ids`, the tile +art of pattern `name`, as one undo step, and returns `{name}`. The pattern keeps its name, its swatch and the swatch's +place, its tile and its options; with `sizeTileToArt` on, the tile is sized to the new art plus `hSpacing` and +`vSpacing`. Fills and strokes name the pattern, so every object painted with it draws the new tile. The art stays on the +canvas, selected as it was. Art that matches the tile art already records no undo step. The command is off while a +pattern is edited ("finish editing the pattern first"), and returns an error, changing nothing, for a missing `name`, a +pattern that does not exist, no art, and art painted with the pattern itself, directly or through the symbols, other +patterns, graph designs and brushes it uses, or the series and label paints a graph stores. In the Swatches panel, art dragged off the canvas and released with Alt (Option on macOS) held over a +pattern swatch runs it with that swatch's pattern; the swatch is outlined while the art is held there. Released anywhere +else in the list, or without Alt, the art becomes a new pattern swatch as before. The help page describes replacing a +pattern by dragging its edited tile onto the old swatch with Alt or Option held, with the pattern updated in the file +(, +archived copy). Keeping the tile, the options and the source art are VectorCraft's own rules. + ```json {"name":"run_command","arguments":{"command":"pattern.options","params":{"showSwatchBounds":true}}} {"name":"run_command","arguments":{"command":"prefs.set","params":{"key":"patternTileEdgeColor","value":"#ff4f4f"}}} @@ -6341,7 +6454,9 @@ Arrowheads… is not confined. `stroke.set {endArrow: {"custom": name}}` puts a custom head on a stroke. The stroke keeps a copy of the head's art, so the document draws it, saves it and exports it to SVG and PDF the same way without the arrowheads file. -`document.inspect` reports such a head as `{"Custom": {name, path}}`, which `stroke.set` takes back unchanged. It +`document.inspect` reports such a head as `{"Custom": {name, path}}`, which `stroke.set` takes back unchanged. A head +read from an Illustrator file also carries `stop`, where the stroke ends under it in head units back from the tip +(0 to 64; without it, the stroke ends halfway along the head). It refuses a `path` that fills no area (non-zero rule; parts thinner than a millionth of a head unit count as none) or has more than 4,096 anchors, more than 4,096 subpaths or a point more than 64 head units from the tip. The help page [Apply stroke on an object](https://helpx.adobe.com/illustrator/using/stroke-object.html) describes defining custom @@ -6352,6 +6467,13 @@ arrowheads in a separate arrowheads file. {"name":"run_command","arguments":{"command":"stroke.set","params":{"ids":[9],"endArrow":{"custom":"Example Arrowhead"}}}} ``` +A dimension's options (`dimension.create`, `dimension.update` and the Dimension tool's `style`) take `arrowStyle` +(`filled`, `open`, `tick` or `none`: `Triangle`, `TriangleOpen`, `Slash` or no head) and `arrowHead`, `null` or one of +the built-in head names `stroke.set` takes, drawn at both ends in place of the arrow style's head. The Arrow Style menu +sets `arrowStyle` to `filled` when it sets `arrowHead`. A custom arrowhead and an unknown name are refused. Versions +that have the stroke arrowhead but do not read `arrowHead` keep the saved arrows until they draw the dimension again, +and then draw `arrowStyle`. Versions without the stroke arrowhead do not open the file. + ## Stroke bounds and clicks Visual bounds (Fit to Selected Art, Rasterize, exporting all art) and clicks on the canvas take @@ -6666,6 +6788,14 @@ is not a whole number of 0 or more, such as 1.5, -1 or "1" ("`subpath` must be a an `anchor` or `segment` in the same way. The document does not change and no undo step is recorded. `path.moveAnchor` to the point the anchor is at, and `path.setHandle` to the point the handle is at on an anchor that keeps its kind, leave the document as it is and record no undo step. +`path.setHandle` with `symmetric: true` also places the anchor's other handle opposite the moved one at the same +length, and the anchor keeps its kind. At an open end, where no segment leaves the anchor on the other side, +`symmetric` has no effect and the handle moves as it would without it. Both `symmetric` and `independent` default to false, and a call with both true is +refused with `` `independent` and `symmetric` cannot both be true ``; the document does not change and no undo step +is recorded. Direct Selection sends `symmetric` while Cmd/Ctrl is held during a handle drag, unless that Cmd/Ctrl +press lent Direct Selection for the gesture while another tool, such as the Pen, was chosen and has not been let go +since (#7842). A call that puts both handles where they already are records no undo step. `symmetric: true` with `link: true` is refused +("`link` and `symmetric` cannot both be true"), and so is `symmetric: true` with `link: true` in `object.blend.spine.moveAnchor`. `path.setHandle` with `link: true` (the Anchor Point tool's Alt-drag on a handle) places the handle and makes the anchor smooth: the other handle turns to lie in line on the far side of the anchor and keeps its length. A retracted other handle is pulled out to the placed handle's length when a segment leaves the anchor on its side, and stays @@ -6792,7 +6922,7 @@ Left out or null, `width` is 8 pt. The range is VectorCraft's own value. These commands refuse a string, a number or another value that is not true or false with `` `closed` must be true or false ``, naming the key; the document does not change and no undo step is recorded: -`independent` in `path.close` and `path.setHandle`; `link` in `path.setHandle`; `patterns` in `path.moveAnchors`; `closed`, `keepSelected` and +`independent` in `path.close` and `path.setHandle`; `symmetric` and `link` in `path.setHandle`; `patterns` in `path.moveAnchors`; `closed`, `keepSelected` and `fill` in `path.freehand` (and in `brush.freehand`); `closed` and the `corner` of a point in `path.curvature`; `corner` in `path.curvatureEdit`; `perpendicular` in `path.reshapeSegment`; and `keepSelected`, `mergeOnlySelection` and `merge` in `path.blob`. A null is read as a key left out. @@ -7365,6 +7495,25 @@ midpoint; any finite value is brought into 0 to 360). With both, the length appl and a line that would reach past the coordinate limit (±4,000,000 pt), are errors that change no line. Each call is one undo step. +A live rectangle's Rectangle Angle and a live ellipse's Ellipse Angle are `rectangleAngle` and `ellipseAngle` +(degrees counterclockwise, 0 for a shape drawn level; any number is read modulo 360). The help page +(https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) lists +both as the shape's rotation on the canvas from 0° to 360°. The rest are VectorCraft's own rules: each selected shape +of that kind turns about its own center, keeping its size, corners and pie (an ellipse's pie turns with it), and other +objects stay as they are. A pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move +its center or change its size. The Transform and Properties panels show the angle in each shape's Properties section, +blank when the selected shapes of that kind differ. It is the shape's own angle: after Reset Bounding Box +(`object.resetBoundingBox`) the Rotate field reads 0° while the shape angle keeps the turn. An angle that is not a +number is an error and changes nothing (`null` counts as an omitted key), a shape that the turn would take past the +coordinate limit (±4,000,000 pt) is an error that changes nothing, whether or not it is selected, and the angle the +shape already has records no undo step; the same holds for `polygonAngle`, and the Polygon Properties angle is blank, +too, when the selected polygons differ. + +```json +{"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"rectangleAngle":30}}} +{"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"ellipseAngle":45}}} +``` + `object.setLiveShape` returns a parameter error, and leaves the document and its undo history as they were, for a key it does not take, at the top level (`` unknown parameter `path` ``) or in one of `items` (`` unknown parameter `items[0].corner`; did you mean `items[0].corners`? ``), for a `sides` that is not a whole number @@ -8087,7 +8236,7 @@ snap the pointer as drawing tools do, so dragging a corner onto another object's Every point a drawing tool places snaps the same way, through one snapper (#506): the Pen's and Curvature tool's anchors, the shape tools' start and dragged corner or radius (`rectangle`, `roundedRectangle`, `ellipse`, `polygon`, `star`, `lineSegment`, `arc`, `spiral`, `rectangularGrid`, `polarGrid`), the -Type tool's click and frame, and a new artboard's corners. The Pencil ignores Smart Guides and Snap to Point and +Three-Point Arc tool's ends and third point, the Type tool's click and frame, and a new artboard's corners. The Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides: its strokes and straight lines follow the hand (Snap to Grid and Snap to Pixel still move their ends). The point lands on another object's anchor, centre or path ("anchor", "center", "path"), else lines up with the anchors, edges and centres of the art and the artboards (a @@ -8501,6 +8650,27 @@ is kept with the preferences and with the workspace; a workspace or preferences and a group id the bar does not have is dropped when they are read. Another `group`, or none, fails with "`group` must be one of …", and a `visible` that is not true or false fails with "`visible` must be true or false"; either leaves every group as it is. The groups and their contents are VectorCraft's own. +`window.taskBar.actions {action, visible?}` (desktop app) turns one of the Contextual Task Bar's actions or chips on +(`visible: true`), off (`false`) or toggles it (omitted or null), and returns `{action, visible}`. The actions are `imageTrace`, +`cropImage`, `removeBackground`, `removeAnchorPoints`, `join` (Connect and Join), `cutPath`, `convertToCorner`, +`convertToSmooth`, `group`, `makeClippingMask`, `unite`, `expand`, `editClippingPath`, `releaseClippingMask`, +`ungroup`, `isolate`, `editPath`, `releaseCompoundPath`, `createOutlines`, `convertToPointType`, `convertToAreaType`, +`typeOnPathOptions`, `centerOnTop`, `centerOnBottom`, `dynamicText`, `offsetPath`, `simplify`, `smooth`, `duplicate`, +`drawPencil`, `placeImage`, `fidelity` and `smoothToolOptions` (the Smooth tool's), and `resizeArtboard`, +`duplicateArtboards`, `rearrangeArtboards` and `exportArtboards` (the Artboard tool's); the chips are `fill`, `stroke`, +`recolor` (Recolor Artwork), `lock` and `shapeProperties` (a basic shape's Shape Properties, in Lock's place). The bar's +More Options menu has Bar Actions, which lists the actions and chips the bar offers for the current selection or tool, +each checked while it is on and named without a final colon or ellipsis, and runs the command for the one clicked. An +action or chip that is off stays out of the bar and out of More Options wherever the bar would offer it; turning one off +changes only the bar. With every action and chip it would offer off, the bar still shows its handle and More Options, +where Bar Actions turns them on again. Every action starts +on. The type font controls are not in Bar Actions and stay on the bar. Which actions are off is kept with the preferences +and with the workspace; a workspace or preferences saved without them show every action, and an id the bar does not have +is dropped when they are read. A `visible` of null toggles, as an omitted one does. Another `action`, or none, fails +with "`action` must be one of …", and a `visible` that is not true, false or null fails with "`visible` must be true +or false"; either leaves every action as it is. +`window.taskBar.resetActions {}` (More Options › Reset Bar Actions) turns every action and chip on again and returns +the ids it turned on. Choosing the bar's actions is VectorCraft's own. ```json {"name":"run_command","arguments":{"command":"file.new","params":{"preset":"A4","orientation":"landscape","artboards":4,"artboardLayout":{"columns":2},"bleed":9}}} @@ -9932,7 +10102,11 @@ images and point type in the font the file names. Type keeps the file's characte kerning off. On a single left to right line, an advance that tracking can't give (wider than its range, or a tab) starts a new point type object at the position the advance gives, and an underline or strikethrough is filled across the space between and on to the end of the last character's advance. Type on more than one line is placed a line at a time: each line is aligned by its own advances and -split as a single line is. An EMF that +split as a single line is. A character cell runs from the font's OS/2 +`usWinAscent` above the baseline to its `usWinDescent` below it: top and bottom aligned text has the top or the +bottom of its cells at the reference point. Text drawn in the opaque background mode, which a file is in until it +sets the mode to transparent, gets one filled rectangle of the background color behind the character cells of each +line, as far as its advances reach (NULs' included), placed before the type. An EMF that draws with EMF+ records is read from them. Hatched and pattern brushes fill with their average color. Records VectorCraft doesn't read are skipped with one warning. A file, or a metafile image inside it, cut short by one of the reader's limits adds one warning without a count. Each of these adds one warning, with a count: images and pattern brushes whose bitmap can't be read, which are left @@ -10444,8 +10618,8 @@ clipping mask into one layer and discards hidden layers that require merging; th imports one image, and Import Hidden Layers brings hidden layers in. `document.open` does the same, with `layers: false` for the single image and `hiddenLayers: true` for the hidden layers. The page also merges adjustment layers, layers with a knockout option, and layers that hold transparent pixels in some blend modes with -the layers below them. `document.open` applies neither adjustments nor knockouts, and it merges a layer by its blend -mode alone, as the rules below say. +the layers below them. `document.open` does not apply adjustments, applies only shallow knockouts inside groups, and +otherwise merges a layer by its blend mode alone, as the rules below say. The rest are VectorCraft's own rules: @@ -10465,6 +10639,12 @@ The rest are VectorCraft's own rules: mask. - A Dissolve layer's partly transparent pixels are merged as opaque or transparent, opaque at the share of its pixels their transparency gives, in a fixed pattern that differs from layer to layer. +- A layer or group inside a group with a Knockout value of 1 (shallow) is merged with the visible layers below it + in that group: where it has pixels, shaped by its layer mask, they are cleared to transparency, it is drawn there + at its fill opacity, and its opacity fades the result back toward them. In a Pass Through group this applies only + when it and the visible layers below it are in Normal mode. A knockout at 0 opacity, one that draws nothing, one + with nothing visible below it, and one at 0 fill that covers none of their painted pixels are not merged for the + knockout; one in a mode VectorCraft lacks is still merged by its mode. - A merged layer is named after the layers it holds, joined with ` + `. - A layer name the file stores only as a one-byte Pascal string, without its Unicode name, is read as Mac Roman. - A layer's opacity is multiplied by its fill opacity, in every blend mode. A layer that others are clipped to keeps @@ -10476,16 +10656,21 @@ The rest are VectorCraft's own rules: (RGB, CMYK, Grayscale, Lab or HSB) over the canvas. One whose shape is a vector mask isn't drawn, and the layers clipped to it are left out. - Adjustment layers, fill layers that store no pixels and whose fill isn't read, layer effects that are switched on, - knockouts and vector masks are not applied; the `warnings` count them. + the other knockouts (top-level layers, clipped layers, layers that others are clipped to, Pass Through groups with + layers in other modes, other Knockout values, and merges that need more memory than allowed) and vector masks are + not applied; the `warnings` count them. - Layer channels may be raw, PackBits or zipped (with or without prediction) at 8, 16 and 32 bits. - A file without layers opens as its merged image. A file whose layers can't be read opens as its merged image with a warning, and when the merged image can't be read either, the file is refused with an error. Each layer's pixels must fit the memory allowed for one image, and the pixels of all the layers and masks, with the canvases the merges make, must together fit eight times that; a file past either limit opens as its merged image, -with a warning. The canvases one step of a merge holds at once must also fit the memory allowed for one image; when -they don't, the layer that needed the merge comes in alone, with a warning: in the Normal mode, or as a layer of its -own instead of clipped. +with a warning. A merge being tried may use the whole of that limit beyond what was read before it. The pixels and +canvases of merges that aren't made, including knockouts that turn out to cut nothing, then count against a second +limit of the same size instead. The +canvases one step of a merge holds at once must also fit the memory allowed for one image; when they don't, the +layer that needed the merge comes in alone, with a warning: in the Normal mode, as a layer of its own instead of +clipped, or without its knockout. ```json {"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/poster.psd","hiddenLayers":true}}} @@ -10772,10 +10957,12 @@ undo step. Object › Transform › Scale, the Scale tool and the Transform pane `text.reshapePath {id, anchors: [[subpath, anchor]…], dx, dy}` does the same for the path of type on a path (Direct Selection dragging one of its anchors): the start and end brackets keep their fractions of the path and the text reflows along it. -`text.setPathHandle {id, subpath?, anchor, which: "in"|"out", x, y, independent?}` moves a direction handle of one -of its anchors, as `path.setHandle` moves a path's (Direct Selection dragging a handle of the path, #3565), in one -undo step. A call of `text.reshapeArea`, `text.reshapePath` or `text.setPathHandle` that changes nothing (`dx` and -`dy` both 0, or a handle moved to where it already is) adds no undo step and keeps redo. +`text.setPathHandle {id, subpath?, anchor, which: "in"|"out", x, y, independent?, symmetric?}` moves a direction handle +of one of its anchors, as `path.setHandle` moves a path's (Direct Selection dragging a handle of the path, #3565), in +one undo step. With `symmetric: true` the other handle goes opposite the moved one at the same length, measured on +the page, as in `path.setHandle`; `symmetric` and `independent` cannot both be true. A call of `text.reshapeArea`, +`text.reshapePath` or `text.setPathHandle` that changes nothing (`dx` and `dy` both 0, or handles left where they +already are) adds no undo step and keeps redo. ```json {"name":"run_command","arguments":{"command":"text.reshapeArea","params":{"id":42,"anchors":[[0,2]],"dx":40,"dy":60}}} @@ -12171,8 +12358,9 @@ path selected it is an error. Window › Retype shows the Retype panel. Find Matching Fonts runs `retype.find {}`, which shows the panel, ranks up to 96 fonts and lists the first ten. Find more font matches, at the end of the list when `more` is true, runs `retype.find {more: true}`, which adds the next five fonts that search found, whatever is selected now. Before any -search, `retype.find {more: true}` runs a first search. A search that fails is an error and leaves the list as it -was. Each row shows the font's family and style over a sample of the font. While live type is selected or edited, a +search, `retype.find {more: true}` runs a first search. With `more` false, omitted or null, `retype.find` runs a new +search; any other value than true, false or null is an error. A search that fails is an error and leaves the list as +it was. Each row shows the font's family and style over a sample of the font. While live type is selected or edited, a click on a row sets that font on it, as the font menus do; live type inside a selected group counts too. The list stays when the selection changes. @@ -13435,7 +13623,8 @@ the compound path selected), and the next click starts a new path. Choosing any A blend's spine is the straight lines between its key centres until it is edited. `object.blend.info` lists it (`spine.anchors`, `keyAnchors`: the point each key sits on). `object.blend.spine.addAnchor {x, y}` adds a point where the spine passes nearest, `object.blend.spine.moveAnchor {anchor, x, y}` moves a point (a key on it moves along; with -`handle: "in" | "out"` it places that handle), `object.blend.spine.convertAnchor {anchor, to: "smooth" | "corner", x?, y?}` converts a point's handles (a Smooth drag with `x, y` creates opposite handles; Corner retracts both), `object.blend.spine.reshapeSegment {segment, t, dx, dy, perpendicular?}` bends a segment +`handle: "in" | "out"` it places that handle, and with `symmetric: true` also the other handle opposite it at the +same length, as `path.setHandle` does; `symmetric` needs `handle` and cannot go with `independent`), `object.blend.spine.convertAnchor {anchor, to: "smooth" | "corner", x?, y?}` converts a point's handles (a Smooth drag with `x, y` creates opposite handles; Corner retracts both), `object.blend.spine.reshapeSegment {segment, t, dx, dy, perpendicular?}` bends a segment so its point at `t` moves by (dx, dy), turning a straight spine into a curve (`perpendicular` works as in `path.reshapeSegment`), and `object.blend.spine.removeAnchor {anchor}` deletes a point no key sits on; the first edit turns the spine into a path. Moving a key moves its end of the spine. Release (`object.blend.release`) leaves the spine of a blend that has one as a path that paints nothing (`spines` in the result): diff --git a/docs/roadmap.md b/docs/roadmap.md index 45df43932f..8deaccae25 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-18 · **Change:** minor (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-19 · **Change:** 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; 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). > @@ -179,16 +179,16 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | -| M5 | Performance | 🟡 background render + caches + MT done; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | +| M5 | Performance | 🟡 background render + caches + MT done; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; in the web build an edit while the view of a heavy document moves draws only the part it changed into the last frame (#8688); dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); 🟡 Retype phase 1: `type.retype` turns outlined text that exactly matches an available font back into point text (#4934); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | | 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 | 2–4 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | | 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, thirteen generated libraries including Tech Circuit, 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 | +| 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, fourteen generated libraries including Tech Circuit, 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 | -| 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, 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 | +| 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); 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 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | @@ -232,11 +232,13 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 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 | | 2026-11-18 | minor | M7/G4: Retype phase 1 (#4934): `type.retype` turns outlined text that exactly matches an available font back into point text. Scores and estimates unchanged | | 2026-11-18 | minor | 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). Scores and estimates unchanged. | | 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. | | 2026-11-17 | minor | Brush Options Key Color (#8284): restore canvas input for its existing eyedropper, then resume the retained draft and previous tool; OK/Cancel and Escape remain separate actions. Six full-app input regressions passed; scores and estimates unchanged. | +| 2026-11-17 | minor | Image Trace Ignore Color: sample original source pixels without changing the canvas View; outside and transparent misses keep the pick armed, while valid picks and cancellation retain the existing tool and Preview behavior (#8068). Scores, gaps and hours unchanged. | | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | | 2026-11-16 | minor | M4: `.ai` and EPS import (#8200): an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; details in [file-format-parity.md](file-format-parity.md). Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3d4e65dda0..4ff8a3aa5c 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-18 · **Change:** minor (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-19 · **Change:** minor (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). > @@ -73,6 +73,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…); right-clicking an unselected link row selects it first, and right-clicking within a multi-selection preserves it; headless tests in `crates/ui-egui/src/panels/tests_links.rs`; scores and estimates unchanged. | | 2026-11-19 | minor | PDF import (#8549 follow-up): type filled and stroked after a page of type filled only came in as a filled object and a stroked one: since #8549 lines filled only are kept for a stroke pass too, and the glyphs of the lines finished past the 64 kept were remembered until the next stroke, so `2 Tr (Title) Tj` after more than 64 lines of type filled only took its first stroke for the start of a stroke pass over them, always once more than 4,096 glyphs had been finished so. Those glyphs are now forgotten when anything else is drawn (a path, an image, a Type 3 glyph's art, a change of blend mode or soft mask: nothing is drawn between an operator's fill pass and its stroke pass), and past the first 4,096 glyphs none are remembered instead of every stroke matching. A `TJ` over more lines than are kept still comes in as a filled object and a stroked one for each part, also when it ends where it began, and when a glyph kept as an outline comes before that (the line it starts keeps the glyphs of the lines finished). Remaining: with nothing drawn between them, type filled and stroked at exactly the place, font, size and text of a glyph filled only on a line finished so still comes in as a filled object and a stroked one, as the device can't tell its stroke pass from the start of one over that glyph. Tests: `type_filled_and_stroked_after_a_dense_page_of_filled_type_is_filled_and_stroked`, `type_filled_and_stroked_over_a_finished_glyph_after_a_path_is_filled_and_stroked`, `an_outline_glyph_in_a_tj_over_more_lines_than_are_kept_leaves_fill_and_stroke_apart`; scores and estimates unchanged. | | 2026-11-18 | minor | Layers: a layer whose art was all added to the selection from its target circle shows as targeted, as an object does (#8646). Scores and estimates unchanged. | | 2026-11-18 | minor | G11: SVG export writes physical unit suffixes on the root for documents with physical units (mm, cm, in, pc), preventing drawings from scaling to 75% in external tools and preserving units across round-trips (#864; general unit preference on restart remains open under #864). Tests: export_physical_units_writes_unit_suffixes (crates/svg/tests/it/import_units.rs) and svg_round_trip_preserves_document_units (crates/engine/src/cmd/fileio/tests_svg.rs). G11 estimate 8–15 → 6–13 h. | @@ -278,7 +279,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005) | -| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (thirteen generated libraries including Tech Circuit, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | +| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fourteen generated libraries including Tech Circuit, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | @@ -289,7 +290,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (ruby, mojikumi), tab leaders, Touch Type, Retype | 20–28 | estimated; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | | Symbols, blends, envelopes, Repeat, perspective | 5 | 88% | remaining: dynamic symbols' `.ai` round trip, further built-in symbol libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons and Media Controls are done), envelope Anti-Alias/Preserve Shape, 9-slice guides outside the art; Symbol Options › Registration, Export Type (Graphic / Movie Clip) and 9-slice guides (drawn and draggable during symbol editing, #5280) and Symbol Type (dynamic on-canvas fill/stroke including gradient/pattern, opacity and blend, #4938) are done | 4–7 | estimated; Blend panel Type and Ramp control step easing with a separate color Shift (#2539); Blend Options retains spacing and orientation; polynomial curves are original approximations; interactive selected mirror axis implemented; bounding-box handles take priority over the axis line (focused regression and native checks passed; full CI blocked by an unrelated text test); #2544 spine Anchor Point conversion and picking regression-tested | -| Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); Create Object Mosaic's dialog with New Size, Constrain Ratio, Resize Using Percentages and Use Ratio is covered by `dialogs::object_mosaic::tests` (score, gaps and hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged | +| Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; simpler contour walk, identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments, so Paths is monotone on the code-drawn sweep) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them; Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views (scores/hours unchanged); Ignore Color canvas sampling reads the original pixels without changing View, keeps a missed pick armed, and retains the manual picker and Preview controls (#8068; scores, gaps and hours unchanged); Create Object Mosaic's dialog with New Size, Constrain Ratio, Resize Using Percentages and Use Ratio is covered by `dialogs::object_mosaic::tests` (score, gaps and hours unchanged); High Fidelity Photo traces in Full Tone with abutting shapes, summed mean pixel difference over 19 test images 80.5 to 65.6 levels ([quality notes](image-trace-quality.md#high-fidelity-photo-in-full-tone)), score, gaps and hours unchanged | | Live vector effects | 5 | 85% | Outline Object, SVG Filters | 4–8 | measured count 49/50 (Pathfinder 13/13 with Trap), depth estimated; Warp Options controls verified by focused checks and original-image review | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, original lighting presets, painter visibility), Revolve (Classic) with Angle, Cap, Offset and the Plastic, Diffuse, No Shading and Wireframe surfaces, the Quick Actions › Expand as Wireframes command (#6354), the Render Settings › Wireframe mode on Extrude & Bevel, Revolve, Inflate and Rotate; materials, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); Revolve (Classic) is covered by the `revolve::classic` tests and `dialogs::revolve::tests::classic_revolve_shows_its_options_and_applies_as_one_step`; Expand as Wireframes is covered by `crates/effects/src/solids/wireframe/tests.rs` and `crates/engine/src/cmd/wireframe/tests.rs`, and Render Settings › Wireframe by `crates/effects/src/solids/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` (score, gaps and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type advanced (CJK, spelling, Touch Type, Retype) | 4 | 50% | CJK vertical composition (mojikumi), variable font axes, tab leaders, Touch Type, Retype beyond exact matches of available fonts | 20–28 | estimated; Retype phase 1 (`type.retype`, exact glyph matches, #4934); No Break keeps marked characters on one line; upright fallback for fullwidth `!` / `?` regression-tested; score and hours unchanged | @@ -308,7 +309,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | anti-aliasing ghost borders (#983); TIFF choices and settings are implemented | 2–4 | estimated | | Print, colour management, separations, flattener | 3 | 80% | Production Preflight available; print preview fidelity remains | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | -| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides and Slices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; scores and estimates unchanged | +| UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 2 Preferences options stored but unused (#394, audited 2026-10-30: Scratch Disks, legacy vector clipboard), context menus in the panels that have none, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; the line under the Preferences fields describes each General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices setting on hover and keyboard focus (#8199, #8223, #8248, #8264, #8360, #8376, #8402, #8429, #8453, #8475, #8483, #8498), score and hours unchanged; numeric-field focus and normal text drags regression-tested (#1326); a focus click released more than 1 pt from its press keeps the caret and a tap within 1 pt selects all (#6659); artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged; icon-strip flyouts retain user sizes (#5713); floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), scores and hours unchanged ; interim macOS cursor delivery (#2292), headless coverage only; native validation pending, score and hours unchanged; Swatches item context menus have focused regressions and rendered-layout evidence below; scores and estimates unchanged | | Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated; #5804: private native-picked raster editor (scores unchanged) | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | @@ -550,7 +551,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Drawing tools | 7 | 86% | Eraser preserves fill when cutting fill-only open paths with fixed or varied tips or Alt-drag marquees; painted-stroke paths retain main behavior and clipping masks keep their remaining contours or empty geometry, with reproducible evaluated gradient placement preserved on ordinary paths, compounds, groups and layers (#6582); replacement-art effects, plug-ins/Rasterize, along/across strokes and placements that cannot be reproduced retain fitting; rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | -| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (thirteen generated in code including Tech Circuit, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | +| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (fourteen generated in code including Tech Circuit, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | @@ -602,7 +603,7 @@ since 2026-10-01. | **Interaction fidelity:** modifiers, cursors, small behaviours | ~30–40% | The dedicated pass hasn't started, and there has been no side-by-side session with Illustrator yet. A power user notices this first | | **Look & feel** | ~75–80% | Measured against Illustrator 2026 screenshots (2026-10-02); the panels added since haven't been re-measured | | **File interop** | ~85% | SVG/SVGZ, PDF and PDF-compatible `.ai` (and legacy version 7 `.ai` out, keeping layers, groups and type as text), EPS, DXF, EMF/WMF, raster formats, PSD export and PSD/PSB placement (merged image), Place and Links, Package, Print, clipboard flavours. Affinity documents (Affinity 1–3) open natively as editable art, checked against 51 pinned public files (33 current `.af`), with selected saved-thumbnail comparisons and every-board native/SVG/PDF/PSD checks for current files; Affinity export is missing and effects, adjustments and brushes don't import. Affinity isn't an Illustrator feature, so this doesn't raise the parity score. The editing copy inside an Illustrator EPS or `.ai` is read for its structure: layers, groups, names, hidden objects and type, colours, gradients, transparency, images and every artboard (see Out of scope for what it doesn't read yet); DWG has no open spec | -| **Bundled content:** brush, symbol, style and swatch libraries | ~46% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have six (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons), graphic style libraries eleven (including Game HUD, Status Effects and Neon & Glow) and brush libraries thirteen (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Arrows) beside User Defined and Other Library… | +| **Bundled content:** brush, symbol, style and swatch libraries | ~46% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have six (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons), graphic style libraries eleven (including Game HUD, Status Effects and Neon & Glow) and brush libraries fourteen (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Engraving, Arrows) beside User Defined and Other Library… | | **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine | | **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA | | **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows starts on Direct3D 12, falling back to OpenGL, and loads no Vulkan driver unless `WGPU_BACKEND` asks for it (#545: Vulkan flickered black on an Intel GPU, DX12 and OpenGL didn't; #806: a faulty Vulkan driver crashed the app before its window appeared; verified by unit tests and the reporter's runs with `WGPU_BACKEND`), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under native Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only), so Preferences › Performance › Linux Display Server › X11 (XWayland) opens the window through XWayland, where drops work (#1151; verified by unit tests and cross-compilation, not on a Wayland desktop); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending | @@ -679,6 +680,7 @@ since 2026-10-01. **Drawing tools, Dimension tool lines line up with dimensions already drawn (#8063, #5590):** By VectorCraft's own rule, with Smart Guides on, a linear dimension placed with its line within the Smart Guides snapping tolerance of the level of a parallel line of a visible, unlocked linear dimension already drawn has its line on that level, and with Alignment Guides on a guide runs along the level across both lines while it is placed. `a_dimension_line_placed_beside_another_lands_on_its_level`, `a_dimension_line_on_another_level_shows_one_guide_across_both`, `a_dimension_of_the_same_points_lines_up_and_the_line_follows_the_pointer`, `a_dimension_dragged_out_beside_another_lands_on_its_level` and `a_line_the_pointer_lies_across_wins_on_one_level` cover it. **Drawing tools, Dimension tool dimensions selected with their art keep their lines and label:** Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave a dimension selected with art it measures, directly or in selected groups without fills, strokes or effects of their own, as it is and change only the other art; when the new art no longer fits its link, the dimension stays where it was, no longer linked, and undo links it again. `expand_leaves_a_dimension_selected_with_its_art_as_it_is`, `expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is`, `outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is`, `a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing`, `a_group_effect_expanded_reaches_the_dimension_it_holds`, `expand_keeps_a_dimension_in_its_asset_and_its_variable_binding`, `a_dimension_keeps_no_link_to_the_art_expand_replaced`, `a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced`, `a_dimension_outlasts_the_stroke_expand_outlined` and `expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art` cover it. **Drawing tools, Dimension tool Arrow Style shows each arrowhead (#8049):** The Arrow Style dropdown in Dimension Tool Options and in the Properties panel's Dimension section draws each style's arrowhead at the end of a short line before its name, in the open list and in the closed field, using the Stroke panel's arrowhead previews. Filled, Open, Tick and None are the same four styles, saved as before. `arrow_style_shows_a_drawn_arrowhead` and `each_arrow_style_draws_its_stroke_arrowhead_at_both_ends` cover it. +**Drawing tools, Dimension tool Arrow Style offers every stroke arrowhead (#8049, #3222):** By VectorCraft's own rule, Arrow Style lists Filled, Open, Tick and None, then the other 38 built-in Stroke panel arrowheads, each with its drawn preview. The options save the head in `arrowHead` (`Barbed`) and keep `arrowStyle` at `filled`, so versions that have the stroke arrowhead but not `arrowHead` keep the saved arrows until they draw the dimension again and then draw Filled arrows (versions without the stroke arrowhead do not open the file); documents and tool settings saved before open unchanged. `every_stroke_arrowhead_draws_as_a_dimension_arrowhead`, `arrow_style_shows_a_stroke_arrowhead`, `arrow_style_list_names_each_style_once` and `built_in_arrowhead_names_are_in_complete_catalogs` cover it. **Drawing tools, Line Segment from one curve onto a common tangent of another:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a Line Segment drag pressed anywhere on a convex closed path with curves and dragged to within the snapping tolerance of another such path lands on a common tangent of the two ([tangent lines to circles](https://en.wikipedia.org/wiki/Tangent_lines_to_circles)): both ends move to where the line touches the paths, the start sliding along the first path, and each end shows the "tangent" label when Anchor/Path Labels is on, with the line drawn as a guide when Alignment Guides is on. The line is the tangent whose touch point on the second path is nearest the pointer, so moving the pointer around the second path switches between the outer tangent and the one crossing between the paths. The start stays where it was pressed when Shift, Alt or Space is held, when an anchor, center or crossing lies nearer the pointer than the second path does, when the press snapped to an anchor, center or crossing off the first path, when Snap to Tangent is off, when Snap to Grid or pixel snapping places drawn points, or when either path bends inward somewhere or has more than 512 segments. `a_line_from_one_circle_to_another_lands_on_their_common_tangent`, `a_line_from_a_turned_ellipse_lands_on_its_tangent_with_a_circle`, `a_line_near_the_second_path_takes_the_tangent_touching_it_nearest`, `a_line_keeps_its_start_without_a_tangent_snap`, `a_line_to_a_crescent_or_from_an_anchor_beside_the_curve_keeps_its_start` and `a_line_segment_drag_draws_the_common_tangent_as_one_undo_step` cover it. **Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views:** `live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle` checks every TraceView, geometric and visual bounds and rotated result bounds. `live_trace_selection_highlight_excludes_the_retained_source_rectangle` checks result highlights and the existing ordinary-group policy. Shared editing-child traversal also preserves Shaper handling. **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:** Shared existing preset definitions are reused; no external preset assets are added. Presets preserve each selected artboard's orientation, and orientation choices apply even when the active board already matches. Fit operations draft bounds until OK, affect only the active artboard and leave artwork in place. Regression coverage checks draft/Cancel, selected-set application, active-only fitting and Undo. @@ -737,12 +739,14 @@ since 2026-10-01. - **Constrain Angle (#394):** General › Constrain Angle turns the arrow keys' axes (guides stay on the page's), holds Shift drags of the Selection, Direct Selection, Free Transform, Slice Selection, Reshape and Measure tools and the Pen's handles to the turned axes, and new rectangles, rounded rectangles, ellipses, grids, point and area type, Shift-drawn polygons and stars and the shape size dialogs are drawn along it with their bounding box turned; 0° and whole turns are exactly as before, quarter turns exact (). Tests: `tests_constrain_tools`, `tests_constrain_new` (engine), `geom` `constrain_axes` / `rotate_deg`, the shape, grid and type tool tests. - **Arcs along General › Constrain Angle:** with a Constrain Angle other than 0° or a whole turn, an arc dragged out with the Arc tool and an arc placed from the Arc Segment Tool Options click dialog are drawn along the turned x and y axes, with their bounding box turned. The drag's box and Shift's equal lengths are measured along those axes, the reference point stays at the drag's corner or at the click, and F, C and ↑/↓ keep the turn. `shape.arc` takes an optional `rotation` (degrees clockwise, about `x1`, `y1` or about the reference point `x`, `y`); a `rotation` that is not a number is an error. At 0° and whole turns arcs are drawn as before, and quarter turns are exact. The help page () describes new objects being drawn along the turned axes; how the Arc tool's keys and reference point work with them is VectorCraft's own rule (tools `draw2::family::tests::arcs_follow_the_constrain_angle`; engine `constrain_angle_draws_a_dragged_arc_along_the_turned_axes`, `constrain_angle_turns_a_click_made_arc_about_its_reference_point`, `arc_rotation_turns_it_and_must_be_a_number`). Scores and hours unchanged. - **Spirals turn as they are dragged, and along General › Constrain Angle:** a spiral dragged out with the Spiral tool turns about its center so that its outer end is at the pointer, so dragging around the center turns it, while Alt, Ctrl/Cmd, ↑/↓, Space and Escape work as before. A spiral placed from the Spiral dialog starts along the x axis turned by a Constrain Angle other than 0° or a whole turn, with its bounding box turned. `shape.spiral` takes an optional `rotation` (degrees clockwise about `cx`, `cy`); a `rotation` that is not a number is an error, and without one spirals are drawn as before. The help page () says that moving the pointer around in a curve during the drag turns the new spiral, and the help page () describes new objects being drawn along the turned axes. Putting the outer end exactly at the pointer, keeping the last direction while the pointer is within 0.01 pt of the center, and leaving a dragged spiral's direction to the pointer with Shift or a Constrain Angle are VectorCraft's own rules (tools `draw2::family::tests::spiral_drag_turns_the_spiral_to_the_pointer`; engine `a_dragged_spiral_turns_its_outer_end_to_the_pointer`, `constrain_angle_turns_a_click_made_spiral`, `spiral_rotation_turns_it_and_must_be_a_number`; UI `spiral_click_dialog_starts_along_the_constrain_angle`). Scores and hours unchanged. +- **Three-Point Arc tool:** a new tool in the Line Segment tool's group, after the Arc tool, draws an open circular arc. A drag or two clicks place its ends (Shift keeps the second end at 45° steps), and a third click places a point the arc passes through. With Third Point Sets Direction on (the tool's Tool Options, or `]` while drawing), the third point gives the direction the arc leaves its first end in, or with Alt the direction at its second end. The tool previews the arc and its center, and with Measurement Labels on its radius, shows "Arc too large" where no arc fits, and draws the arc in one undo step with `shape.threePointArc {start, end, through | toward, at?}` (geom `shapes::tests::the_arc_through_a_point_passes_through_it`, `the_arc_leaving_along_a_direction_has_that_tangent`, `degenerate_points_give_no_arc`, `the_path_via_the_third_point_passes_through_it_exactly`; tools `three_point_arc::tests`; engine `tests::three_point_arc`; ui-egui `dialogs::three_point_arc_options::tests`). Scores and hours unchanged. - **Shape commands refuse invalid options:** `shape.arc` refuses a `reference` that is not a whole number from 0 to 8, a `baseAlong` other than `x` or `y` (either case), null included for both, and a `slope` outside −100…100, in both of its forms; before, such a value drew the arc with reference point 0 or 8, the X axis or the nearest slope. `shape.rectangularGrid` and `shape.polarGrid` refuse a divider count that is not a whole number of at least 0; before, such a count was 5. Each error names the key, and nothing is drawn. Left-out values keep their defaults. These ranges are VectorCraft's own command rules (engine `draw2::shape_arc_rejects_an_invalid_reference_base_along_or_slope`, `draw2::shape_arc_takes_every_reference_point_and_either_base_axis`, `draw2::grid_divider_counts_reject_fractions_and_negatives`). Scores and hours unchanged. - **Roughen at Size 0 keeps the outline:** with Size 0 (relative or absolute), Effect › Distort & Transform › Roughen… moves no point: each segment is split at the Detail spacing (fewer points past the anchor limit) into pieces of equal length on the segment itself, so the path keeps its outline, with Smooth or Corner points alike. A straight segment gets corner points without handles, and a curve gets smooth points whose handles follow it. Before, the points were joined by straight lines (Corner) or a smoothed curve through them (Smooth), which changed curved outlines. Existing documents with a Roughen of Size 0 on a curved path, or with Smooth points, draw differently. This is VectorCraft's own rule; what Roughen does is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `tests::roughen_at_size_0_keeps_the_outline_and_spaces_its_points_evenly`). Scores and hours unchanged. - **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged. - **Link cursor for loaded text:** with text loaded from a port, the Selection tool's pointer adds a link badge over a closed path, area type or type on a path that a click threads the text into, and keeps the loaded text elsewhere; a click on a frame already in a thread or a path inside a compound path makes a new frame instead of a `text.thread.add` error (`select::tests::loaded_text_shows_the_link_cursor_where_a_click_threads_it_into_the_object`, `cursors::tests::loaded_text_link_cursor_is_the_loaded_text_with_a_link_badge`); score unchanged. - **Copy and Cut of anchors picked with a lent Direct Selection (#6123):** with the Pen or the Curvature tool, Cmd/Ctrl held lends Direct Selection for the gesture; the anchors and segments it picks are what Edit › Copy and Cut take once the key is let go, as with Direct Selection chosen, while the last anchor the Pen leaves selected as it draws still makes Copy take the whole path (#2122). A Cmd gesture that leaves the selection as it was (a Shift marquee over nothing) picks nothing. Regression test: `tests::draw2::pen_cmd_selected_anchors_are_what_copy_and_cut_take`. +- **Mirrored handles in a Direct Selection drag (#7842):** Cmd/Ctrl added after a handle drag begins puts the anchor's other handle opposite the dragged one at the same length, on paths, type on a path and blend spines, and the anchor keeps its kind; Shift constrains the dragged handle first, and Alt keeps the handles independent. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without Cmd/Ctrl. When Cmd/Ctrl lends Direct Selection for the gesture while another tool, such as the Pen, is chosen, that press does not mirror; letting it go and pressing it again during the drag does. This is VectorCraft's own behavior. Regression tests: `crates/engine/tests/direct_handle_mirror.rs`. - **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. - **Large Shift-marquee selections and Select › Inverse:** `select.toggle` and `select.add` with many ids (a Shift-drag marquee sends them together) go through the selection once instead of once per id, and Select › Inverse looks each object up in a set of the selected ones. The resulting selection, its order and the reply are the same as before. With 50,000 objects the selection step of toggling every object off took 528 to 655 ms before and 2.5 to 4.6 ms after in 7 runs, wall clock on a machine that was running other builds (`cargo run --release -p vectorcraft-engine --example selection_bench`). Regression tests: `add_all_does_what_adding_each_does` and `toggle_all_does_what_toggling_each_does` in `crates/doc/src/selection/tests.rs`, and `toggle_and_add_handle_each_listed_id_in_order` in `crates/engine/tests/it/selection_commands.rs`. @@ -867,9 +871,19 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Preferences › General describes its settings:** the line under the Preferences fields shows a sentence for each of the 32 General settings, Enable Contextual Task Bar included, when the pointer is over the setting's row or its control has the keyboard focus, and a screen reader gets the same sentence. The sentences are VectorCraft's own and state what the app does with each setting. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Selection & Anchor Display describes its settings:** the line under the Preferences fields shows a sentence for each of the 14 Selection & Anchor Display settings, from Tolerance to the Curvature Tool rubber band, on hover and on keyboard focus, and a screen reader gets the same sentence. The Snap to Point sentence states that the Smart Guides Snapping Tolerance applies while Smart Guides is on. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Guides & Grid describes its settings:** the line under the Preferences fields shows a sentence for each of the 12 Guides & Grid settings, from Snap to Grid to Pattern Editing's Tile Edge Color, on hover and on keyboard focus, and a screen reader gets the same sentence. The Show Pixel Grid sentence states that the pixel grid shows from 600% zoom. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › Plug-ins & Scratch Disks describes its settings:** the line under the Preferences fields shows a sentence for Additional Plug-ins Folder, Primary and Secondary on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: on the desktop the folder's `.wasm` plug-ins load at startup and when OK sets a new folder, except in Safe Mode, and the web version does not load them; Primary and Secondary take Startup, None or a folder path and are stored, but no scratch disk is used yet (G12 stays open). Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › User Interface describes its settings:** the line under the Preferences fields shows a sentence for each of the 13 User Interface settings, from Brightness to Language, System Title Bar and VectorCraft Title Bar on Every Desktop included where the platform shows them, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Accent Color is dimmed while the color scheme has its own accent; Outline view shows the canvas white whatever Canvas Color says; with Auto-Collapse Iconic Panels on, a panel opened from its icon closes on Esc or a click outside it; Open Documents As Tabs applies to documents opened or created afterwards; both title bar settings apply from the next start; UI Scaling leaves the size of art at a given zoom alone; Scale Cursor Proportional to UI sizes only the pointers VectorCraft draws; the dialog shows a chosen language before OK. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › Performance describes its settings:** the line under the Preferences fields shows a sentence for each of the 8 Performance settings, from GPU Performance to Use Monitor Profile for Canvas, Linux Display Server included on Linux, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: GPU Performance only allows Animated Zoom; Animated Zoom makes wheel zooms glide and the Zoom tool zoom as it is dragged or held; Graphics Processor applies to the desktop version from the next start, and Automatic prefers the processor that drives the display; History States caps each document's undo steps, and the memory budget can drop older steps sooner; with Real-time Drawing and Editing off, outlines follow a drag and the art changes on release, while a ruler guide still moves; Render Threads sets the canvas rasterizer's workers, and the web version uses none; Linux Display Server's X11 choice always uses XWayland on a Wayland desktop and the others only with a pen attached; Use Monitor Profile for Canvas converts the canvas to the display's profile unless the system does so, and off draws it in sRGB. Units, General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance and Type have sentences, and the other categories leave the line empty. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Hyphenation describes its settings:** the line under the Preferences fields shows a sentence for Default Language and for Exceptions (comma separated) on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: new type takes the Default Language while Document Setup's language is English: USA and [Normal Character Style] sets no language, and type already in a document keeps its own; in paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere without one, in any case, except that Korean words take no hyphen and Indian-language words do not break inside a character cluster. Units, General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation and Type have sentences, and the other categories leave the line empty. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Smart Guides describes its settings:** the line under the Preferences fields shows a sentence for the Smart Guides box and for each of the 14 Smart Guides settings, from Color to Snap to Perpendicular, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Pixel Preview turns Smart Guides off and Snap to Grid snaps instead; with Alignment Guides off, art still lines up without the line; Object Highlighting outlines only an unselected object while a selection tool is not dragging; Snapping Tolerance is a distance on screen at every zoom; Snap to Last Location does not return a copy. Units, General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation and Type have sentences, and the other categories leave the line empty. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Slices describes its settings:** the line under the Preferences fields shows a sentence for Show Slice Numbers and for Line Color on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: each slice's number shows in a box at its top left on the canvas, the slice outlines still show with numbers off, and auto slices use a dimmer shade of the line color. Units, General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation and Type have sentences, and the other categories leave the line empty. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › Plug-ins & Scratch Disks describes its settings:** the line under the Preferences fields shows a sentence for Additional Plug-ins Folder, Primary and Secondary on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: on the desktop the folder's `.wasm` plug-ins load at startup and when OK sets a new folder, except in Safe Mode, and the web version does not load them; Primary and Secondary take Startup, None or a folder path and are stored, but no scratch disk is used yet (G12 stays open). Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › User Interface describes its settings:** the line under the Preferences fields shows a sentence for each of the 13 User Interface settings, from Brightness to Language, System Title Bar and VectorCraft Title Bar on Every Desktop included where the platform shows them, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Accent Color is dimmed while the color scheme has its own accent; Outline view shows the canvas white whatever Canvas Color says; with Auto-Collapse Iconic Panels on, a panel opened from its icon closes on Esc or a click outside it; Open Documents As Tabs applies to documents opened or created afterwards; both title bar settings apply from the next start; UI Scaling leaves the size of art at a given zoom alone; Scale Cursor Proportional to UI sizes only the pointers VectorCraft draws; the dialog shows a chosen language before OK. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › Performance describes its settings:** the line under the Preferences fields shows a sentence for each of the 8 Performance settings, from GPU Performance to Use Monitor Profile for Canvas, Linux Display Server included on Linux, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: GPU Performance only allows Animated Zoom; Animated Zoom makes wheel zooms glide and the Zoom tool zoom as it is dragged or held; Graphics Processor applies to the desktop version from the next start, and Automatic prefers the processor that drives the display; History States caps each document's undo steps, and the memory budget can drop older steps sooner; with Real-time Drawing and Editing off, outlines follow a drag and the art changes on release, while a ruler guide still moves; Render Threads sets the canvas rasterizer's workers, and the web version uses none; Linux Display Server's X11 choice always uses XWayland on a Wayland desktop and the others only with a pen attached; Use Monitor Profile for Canvas converts the canvas to the display's profile unless the system does so, and off draws it in sRGB. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › File Handling describes its settings:** the line under the Preferences fields shows a sentence for each of the 14 File Handling settings, from Enable Background Save to Use Compression, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: on the desktop, Background Save writes saves to a file on the worker, and Background Export does the same for exports to files and packages but not 3D exports; timed recovery copies are made at the Every (minutes) interval, only of documents changed since their last copy, and skip documents with more than 20,000 objects when Turn off Data Recovery for complex documents is on; a blank recovery Folder uses VectorCraft's own folder, and the web version keeps copies in the browser; Number of Recent Files to Display limits Open Recent Files and the Home screen while up to 30 files stay remembered; Use Low Resolution Proxy for Linked EPS keeps a linked EPS image's saved preview on open; anti-aliased bitmaps apply only in Pixel Preview; Update Links rereads, asks or notes a changed link; a blank Templates Folder uses VectorCraft Templates in the documents folder; Edit Original opens raster images in PhotoCraft when its system-defaults option is off; files from older versions open marked [Converted] and Save asks where to save them; Use Compression compresses native files and templates unless a save says otherwise. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › Clipboard Handling describes its settings:** the line under the Preferences fields shows a sentence for each of the 5 Clipboard Handling settings, from Include SVG Code to When pasting text, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Include SVG Code gives other apps SVG code of copied art, and on the desktop the code is not copied as text when the art embeds more than 1 MiB of images; the PDF checkbox puts a PDF on the system clipboard on Windows only; both legacy vector clipboard settings are stored but not used yet; When pasting text applies to text copied from VectorCraft type and pasted into type, where Keep Formatting keeps its styles and Keep Plain Text gives it the style where it lands. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › Appearance of Black describes its settings:** the line under the Preferences fields shows a sentence for On Screen and for Printing / Exporting on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Display All Blacks as Rich Black shows pure CMYK black (black ink alone at 100%) as RGB black on the canvas, and Display All Blacks Accurately converts it through the CMYK working space; Output All Blacks as Rich Black does the same in RGB and grayscale raster exports and Print as Bitmap, and does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › Devices describes its settings:** the line under the Preferences fields shows a sentence for Enable Touch Workspace and for Enable Touch Gestures on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: with Enable Touch Workspace on, a touch screen switches VectorCraft to the Touch workspace, and turning the setting off or losing the touch screen goes back to the workspace it switched from; with Enable Touch Gestures on, a two-finger tap on the canvas undoes, or in the Touch workspace switches between selection and drawing tools, and a three-finger tap redoes, except in Presentation Mode. Units, General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance, File Handling, Clipboard Handling, Appearance of Black and Devices have sentences, and Type leaves the line empty. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Type describes its settings:** the same line shows a sentence for each of the 23 Type settings, from Size/Leading to Measure Type by Glyph Bounds, when the pointer is over the setting's row or its control has the keyboard focus, and a screen reader gets the same sentence. Each sentence is VectorCraft's own and states what the app does with the setting: for example, which keys step by each increment, which panels show the East Asian and Indic options, and that the two pink highlights show only on screen. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Window › New Window (G7, #4116):** New Window (`window.newWindow`) opens another view of the current document ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes showing one document in several windows at once), with its own zoom, center, rotation, artboard and Outline or Preview, as a tab of its own; an edit in one view shows in every view. Tile, Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as they arrange a document, and Next and Previous Document step through the views. Closing a view leaves the document open; closing its last view closes the document, asking to save it first. The view's number after the name in its tab ("Name:2", while the document has more than one view) is VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. @@ -896,6 +910,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pattern names and swatch names:** `pattern.options` refuses a new name that another pattern, a swatch or a color group has. It takes a name that only the pattern's own swatches have. The reference page does not say what happens when the new name is taken; the refusal follows VectorCraft's rule that swatches and color groups share one namespace (`Document::swatch_name_taken`), which `swatch.new` and `swatch.edit` also follow. A rename gives the new name only to the pattern's swatches that had the old one; any other swatch with the old name keeps it, and art linked to that swatch stays linked. `object.pattern.make` and `object.pattern.saveCopy` number a color group's name as they number a swatch's. Tests in `tests/pattern.rs` cover each command. Public reference: [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copy). - **Cancel, Delete and rename leave no paint of a missing pattern:** the help page lists Save a Copy, Done and Cancel for leaving pattern editing (https://helpx.adobe.com/illustrator/using/create-edit-patterns.html). Canceling a pattern made for the edit removes it with every swatch of it, a color group's included. Canceling a new pattern, `pattern.delete` and a `pattern.options` rename reach every paint of the pattern: art outside the editing layer, opacity mask art, type runs, symbol definitions, graph designs, the series and label paints a graph keeps for its next redraw, other patterns' tiles (a copy Save a Copy made included), graphic and character styles, brush art, and the fill, stroke and appearance new art takes. Canceling a new pattern and Delete make those paints no paint, a VectorCraft rule; a rename renames them. Canceling the edit of an existing pattern puts its definition back as it was when editing started; after a rename in Pattern Options, it also gives the pattern its old name back with its swatches and paints, unless another pattern, swatch or color group has taken that name. Undo and Redo restore new art's paints with the document. Tests in `tests/pattern.rs` cover each command. - **Move Tile with Art:** Pattern Options has the Move Tile with Art checkbox under Size Tile to Art, and with it on, moving the tile art in pattern editing mode moves the tile with it (). VectorCraft's own rules for what the page leaves open: the tile moves only when a move takes all of the tile art, by the same offset; rotations, scales, copies and anchor moves leave it in place; the option is off for a new pattern. `pattern.options {moveTileWithArt}` sets it and `pattern.list` reports it. Tests in `tests/pattern.rs` and `panels::pattern_options::tests` cover it. +- **Art Alt-dragged onto a pattern swatch replaces its tile art:** the help page describes dragging the edited tile onto the old pattern swatch with Alt (Option on macOS) held to replace the pattern and update it in the file (, archived copy). In the Swatches panel, art released this way over a pattern swatch becomes that pattern's tile art in one undo step (`object.pattern.replaceArt`), and every object painted with the pattern draws the new tile. VectorCraft's own rules: the pattern keeps its name, swatch, tile and options (Size Tile to Art refits the tile), the dragged art stays on the canvas, art that matches the tile records nothing, art painted with the pattern itself is refused, and Alt over any other swatch still makes a new pattern. Tests in `tests/pattern.rs` and `panels::swatches::tests` cover it. - **A clip group in Properties:** with one clip group selected, the panel has Edit Clipping Path and Edit Contents at its top, under the Clip Group heading, which select the clipping path or the clipped art for the selection tools to transform alone, as Object › Clipping Mask does (: with a clip group selected, the tutorial uses Edit Clipping Path at the top of the Properties panel to select the mask for editing, and uses Edit Contents to select the masked art). Edit Contents shows only when the group clips something. Not checked against the reference app: whether Properties keeps the buttons while the clipping path or the contents is selected; the Control bar has no clip-group buttons here. Evidence: `panels::properties::tests::one_clip_group_has_edit_clipping_path_and_edit_contents_at_the_top`. - **Contextual controls in Properties:** the [Properties panel overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/properties-panel-overview.html) lists controls that appear for particular selections and tools; Properties has them, each running the existing command. Quick Actions has Blend Options for one selected blend, with the Blend tool or any other, as the [blending page](https://helpx.adobe.com/illustrator/using/blending-objects.html) describes (#4817) (the Blend Options dialog, OK one undo step) and Merge Live Paint when a Live Paint group is selected with more paths and nothing Live Paint refuses (`livePaint.merge`). Appearance has the stroke's Variable Width Profile list, the Control bar's, with the Width tool or when the stroke has a variable width (`stroke.set {profile}`), and beside fx the Delete icon: with one effect on the one selected object (its own or a fill's or stroke's) its name and an icon that removes it (`effect.remove`), with several an icon that opens the Appearance panel, as the overview describes. With Direct Selection and corners of one path selected, Corner and Corner Radius set the kind and radius of those corners (`object.setLiveShape`); a live rectangle's and polygon's own rows already do. Each edit is one undo step. The overview's Variable Font icon was already in Character. Not checked against the reference app: whether Merge needs two Live Paint groups (the overview speaks of several selected groups; `livePaint.merge` takes a group and paths), and where exactly each control sits in its section. Evidence: `panels::properties::tests::{blend_options_is_a_quick_action_for_one_blend_with_the_blend_tool, merge_live_paint_is_a_quick_action_for_a_live_paint_group_and_more, the_width_profile_shows_for_a_variable_width_or_the_width_tool, direct_selected_corners_show_their_kind_and_radius, one_effect_has_a_delete_icon_in_appearance}`. - **Edit Artboards in Properties:** a Transform section comes first (#5219): the reference point the Transform panel and Control bar share, the active artboard's X and Y (of that point) and W and H with the Constrain Width and Height Proportions link, its preset and orientation, and Move and Scale Artwork with Artboard. The Artboards section follows, with the name field, Artboard Options and Fill. The active artboard's name is a field. Typing a new name and pressing Enter or clicking elsewhere renames that artboard in one undo step, as the Artboards panel's rename does (`artboard.setProps {index, name}`); pressing Escape or leaving the field empty keeps the old name. A click on the Artboard Options icon beside the field opens Artboard Options for the active artboard, as double-clicking the Artboard tool's button does (`tool.options {tool: "artboard"}`). Pointer and key tests in `panels/properties.rs` cover both. Public references: [Resize artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/resize-artboards.html) and [Create and add new artboards](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/add-new-artboards.html). @@ -903,7 +918,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Resizing several artboards:** with several artboards selected with the Artboard tool, a new W or H in Properties, the Transform panel or the Control bar, a preset or an orientation in Properties or the Control bar, and a new Width or Height in Artboard Options resize every selected artboard in one undo step (`artboard.setProps {artboards}`), and a Fill chosen in Properties colors each of them (#5698); a Shift- or Ctrl/Cmd-click on an Artboards panel row with another tool in use switches to the Artboard tool and selects as it does; with Scale Artwork with Artboard on, Properties, the Transform panel and the Control bar scale each object once, with the artboard it was inside before the change. The Transform panel, the Control bar and Artboard Options resize each one about its own reference point, a preset sizes each one in its own orientation, and X and Y still move the active artboard alone. Pointer and key tests in `panels/properties.rs`, dialog tests in `dialogs/tests.rs` and an engine test in `tests/xform.rs` cover them. Public references: [Artboard Enhancements In Illustrator CC](https://blog.adobe.com/en/publish/2017/11/10/artboard-enhancements-in-illustrator-cc) (a height and a width entered once resize every selected artboard) and [Using multiple artboards](https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (2019). - **Artboard Escape routing:** Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture. Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. - **Escape in the distort tools:** Escape during a Puppet Warp pin drag or turn, a Perspective Grid tool handle or plane widget drag, a Perspective Selection move, resize or plane widget drag, or a Liquify stroke cancels it: the art goes back to how the press found it, no undo step is added, and the tool stays chosen. Puppet Warp also selects again the pins selected before the press, and Escape during a Liquify Alt-drag puts the brush size back. Regression tests: `escape_cancels_*` in `crates/tools/src/distort/puppet.rs`, `perspective.rs` and `liquify.rs`, and `escape_cancels_a_puppet_warp_perspective_or_liquify_drag` in `tests/distortkeys.rs`. -- **Shift with the Artboard tool:** a Shift-click adds an artboard to the selection or takes it out when the button comes up. A Shift-drag inside an artboard draws a new artboard there, and a Shift-drag on the pasteboard is a marquee that toggles the artboards it touches, as the [default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (a Shift-drag draws an artboard within an existing one) and [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy) describe. Shift no longer keeps an artboard move at 45° steps or a drawn artboard square. Escape during a marquee or while a new artboard is being drawn cancels it and keeps the Artboard tool. Pointer and key tests in `crates/tools/src/xform/artboard.rs` cover the four gestures and Escape. +- **Shift with the Artboard tool:** a Shift-click adds an artboard to the selection or takes it out when the button comes up. A Shift-drag inside an artboard draws a new artboard there, and a Shift-drag on the pasteboard is a marquee that toggles the artboards it touches, as the [default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) (a Shift-drag draws an artboard within an existing one) and [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy) describe. Shift held once a move or an Alt-drag copy is under way keeps it to the level, upright or 45° line from General › Constrain Angle, and snaps slide it along that line (#8580); a drawn artboard is still not kept square. Escape during a marquee or while a new artboard is being drawn cancels it and keeps the Artboard tool. Pointer and key tests in `crates/tools/src/xform/artboard.rs` cover the four gestures and Escape. - **Artboard edge buttons:** with the Artboard tool and one artboard selected, a button with a plus shows just outside the middle of each edge where an artboard of the same size fits on that side; clicking it adds an empty artboard of that size there (`artboard.new {beside, side}`), and Alt-clicking duplicates the artboard with its art there (`artboard.duplicate {index, side}`), each in one undo step, with the new artboard active. An Alt-click on a locked artboard's button does nothing, as the tool doesn't copy a locked artboard. The 20 pt gap and the room rule (within the canvas, overlapping no other artboard) are VectorCraft's own. Pointer tests in `crates/tools/src/xform/artboard/tests.rs` and an engine test in `tests/panelcmds.rs` cover it. Public references: [Add artboards instantly](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/add-new-artboards.html) and [Duplicate artboards instantly](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/duplicate-artboards.html). - **Artboard edge button tooltips:** resting the pointer on an edge button shows a tooltip, after the interface's usual tooltip delay, that says a click adds an artboard on that side and, on an unlocked artboard, that an Alt-click duplicates the artboard with its art. The tooltip covers the same disc a press takes. No tooltip shows during a drag or where a button is hidden for lack of room. The wording is VectorCraft's own. Tools can attach such hover text to any overlay region (`Overlay::HoverText`). Tests in `crates/tools/src/xform/artboard/tests.rs`, `crates/ui-egui/src/canvas/tests.rs` and `crates/ui-egui/src/i18n/tests.rs` cover it. - **Artboard deletion keys:** Delete/Backspace delete selected boards in one Undo step, retaining the original first board in the current order when all are selected, as in the public [Delete artboards guide](https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/add-edit-artboards/delete-artboards.html). The last board and active drags stay protected; neither key clears selected artwork. Headless shortcut regressions in `tests/distortkeys.rs` cover reordered boards, artwork, saved state and Undo/Redo. @@ -1064,7 +1079,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The contextual task bar offers more next steps by selection (): an open path Join and Edit Path (the Direct Selection tool), a closed path Edit Path, a compound path Edit Path and Release Compound Path, a clipping group Edit Clipping Path and Release Clipping Mask instead of Ungroup and Isolate, an image selected with vector art Make Clipping Mask instead of Unite, point or area type Convert To Area Type or Convert To Point Type beside Create Outlines, and type on a path, for which the overview names an item to add an effect and rearrange the text, Type on a Path Options (`type.pathOptions`; its options: ) beside Create Outlines. Evidence: `crates/ui-egui/src/tests/taskbar.rs`. - While a Type tool (Type, Area Type, Type on a Path and their vertical versions) adds or edits type, the contextual task bar shows the font family menu, the font style menu, the Font Size combo and the Fill chip (); the Touch Type tool shows no bar, as the same page describes. Type selected with a selection tool shows the same three font controls beside its Create Outlines, conversion and Type on a Path items (). The controls act as the Character panel's do: on the characters a Type tool selects, else on every selected type object, with the size left blank where the sizes differ. VectorCraft's own rules: a Type tool's bar leaves out the object actions, the Stroke chip, Recolor Artwork and Lock; a Type tool shows no bar before it adds type or with other art selected; type selected with other art shows no font controls; the font controls go on a second row when one row would be wider than the canvas, and narrow to fit a canvas narrower than they are; while a Type tool edits type, the Fill chip shows the edited characters' fill ("?" where it differs). Evidence: `the_type_tools_show_font_and_fill_controls`, `the_type_tools_show_no_bar_without_type`, `selected_type_shows_font_controls_beside_its_actions`, `the_task_bars_font_size_sets_what_the_character_panel_would`, `the_type_tools_fill_chip_activates_the_fill`, `the_type_tools_bar_is_named_and_stays_on_the_canvas`, `selected_types_font_controls_take_a_second_row_on_a_narrow_canvas` and `the_type_tools_fill_chip_shows_the_edited_characters_fill` in `crates/ui-egui/src/tests/taskbar.rs`. - The help page describes the contextual task bar as one horizontal row () and gives no rule for a canvas narrower than that row. VectorCraft's own rule: the bar stays whole on the canvas. When its actions don't fit in one row, they wrap, in order, onto rows under the row with the handle, the chips and More Options; an action wider than any row, or one that would need a row past the canvas's height, is listed in More Options instead; when the chips don't fit beside the handle and More Options, they take rows after the actions; with no row to spare for the font controls, the bar leaves them out; a canvas too small for the handle and More Options shows no bar. Evidence: `a_task_bars_actions_wrap_on_a_narrow_canvas` and `a_task_bar_action_wider_than_the_canvas_goes_in_more_options` in `crates/ui-egui/src/tests/taskbar.rs`. + - The contextual task bar's More Options menu has Bar Actions, which lists the actions and the Fill, Stroke, Recolor Artwork, Lock or Shape Properties chips the bar offers for the current selection or tool, each checked while it is on, and Reset Bar Actions, which turns every one on again (`window.taskBar.actions`, `window.taskBar.resetActions`). An action that is off stays out of the bar and out of More Options wherever the bar would offer it; turning one off changes only the bar. With all of them off, the bar still shows its handle and More Options. The type font controls are not in Bar Actions. Which actions are off is kept with the preferences and with the workspace. Choosing the bar's actions is VectorCraft's own. Evidence: `an_action_turned_off_leaves_the_bar_and_stays_in_its_menu`, `an_action_turned_off_is_not_listed_in_more_options`, `every_action_the_bar_offers_can_be_turned_off`, `a_chip_turned_off_leaves_the_bar`, `reset_bar_actions_shows_every_action_again`, `bar_actions_are_kept_with_the_preferences`, `bar_actions_list_names_without_a_colon_or_an_ellipsis` and `more_options_bar_actions_turns_an_action_off_and_on` in `crates/ui-egui/src/tests/taskbar.rs`, and `saved_workspaces_restore_the_task_bar_actions` in `crates/ui-egui/src/workspaces.rs`. - With a live rectangle, rounded rectangle, ellipse or polygon selected with the Selection tool, the contextual task bar shows a Shape Properties button in place of Lock. It opens a popup with the shape's rows from the Transform panel (corner radius, pie angles, or sides, angle, corner and radius), which edit it through `object.setLiveShape`. The overview describes this: when a shape drawn with a shape tool (Rectangle, Star) is selected, the bar offers to change its properties where Lock Object would be ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Object › Lock and ⌘2 still lock the shape. Not done: stars, which the app draws as plain paths. Evidence: `a_basic_shape_shows_its_properties_in_place_of_lock`, `the_shape_properties_popup_edits_the_shape` and `other_selections_keep_lock` in `crates/ui-egui/src/tests/taskbar.rs`. + - Rectangle Properties and Ellipse Properties in the Transform panel, the Properties panel and the task bar's Shape Properties popup have an Angle field, as Polygon Properties does: the help page lists Rectangle Angle and Ellipse Angle as the shape's rotation on the canvas from 0° to 360° (). A typed angle turns the shape through `object.setLiveShape {rectangleAngle, ellipseAngle}`. VectorCraft's own rules: degrees counterclockwise, 0 for a shape drawn level; each selected shape of that kind turns about its own center and keeps its size, corners and pie; the field is blank when the selected shapes of that kind differ, as the Polygon Properties angle now is too; the shape keeps its angle after Reset Bounding Box squares the Rotate field's box to the page; the angle a shape already has records no undo step. Evidence: `a_rectangle_and_an_ellipse_take_their_angle` in `crates/engine/src/tests/livecorners.rs` and `a_rectangle_and_an_ellipse_show_their_angle` in `crates/ui-egui/src/panels/transform/tests.rs`. - While the Rectangle, Rounded Rectangle, Ellipse, Polygon or Star tool is in use, the contextual task bar offers Edit Path (the Direct Selection tool), the Fill and Stroke chips, and Shape Properties for the shape it draws, as the help page lists for those five tools (). VectorCraft's own rules: the bar shows while one of those tools has one closed path selected whole, as right after it draws one, and not with nothing selected, several objects, a group, an open path, type or picked-out anchors; it shows nothing during the drag that draws the shape; it leaves out the selection tools' Duplicate, Offset Path, Simplify, Recolor Artwork and Lock; the Line Segment tool shows no bar. Not done: Shape Properties for a star, which the app draws as a plain path, and Gen Shape Fill and Generate Vectors, which the app doesn't have. Evidence: `shape_tools_show_edit_path_paint_and_properties_after_drawing`, `shape_tools_have_no_shape_bar_without_a_single_shape` and `shape_tool_bar_retargets_after_another_shape_and_undo` in `crates/ui-egui/src/tests/taskbar.rs`. - While the Smooth tool is in use with a path it can smooth selected (a path with three or more anchors, or two joined by a curve, on its own or inside a selected group), the contextual task bar shows the tool's Fidelity field and Tool Options…, which opens the Smooth tool's options. The overview says the Smooth tool's bar has its tool options (), and the tool's help page names Fidelity as its option (). A value typed or stepped in the field sets the tool's Fidelity through `tool.setOption`, with the same range, unit (screen pixels) and steps as the field in its options. VectorCraft's own rules: with nothing selected, or only straight lines or type selected, the tool shows no bar; the bar leaves out the selection tools' actions, the Fill and Stroke chips, Recolor Artwork and Lock; on a canvas too narrow for the field, More Options lists Fidelity, which opens the tool's options. Evidence: `the_smooth_tool_shows_fidelity_and_tool_options_for_a_path` and `the_smooth_tool_shows_no_bar_without_a_path_to_smooth` in `crates/ui-egui/src/tests/taskbar.rs`. - The contextual task bar has a Stroke chip beside the Fill chip, drawn with the paint the Stroke proxy shows (a "?" when the selected objects' strokes differ, as on the Fill chip); a click brings the Stroke proxy forward and shows the Swatches panel wherever it is docked, floating or closed, as a click on the Fill chip does for the Fill proxy. The reference app's bar has Fill and Stroke controls for changing an object's colors ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Evidence: `the_task_bar_shows_a_stroke_chip_beside_fill` and `the_task_bar_chips_follow_the_proxies_and_show_swatches_anywhere` in `crates/ui-egui/src/canvas/tests.rs`. @@ -1161,9 +1178,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`). - With Smart Guides › Transform Tools on, a Free Transform shear (Cmd/Ctrl on a side handle) shows its angle next to the pointer, as the Shear tool does, and a handle drag that turns from a scale into a shear and back shows only the current operation's value ([the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html)). The angle's sign and its one decimal place are VectorCraft's own rule, the same as the Shear tool's label (tools `xform::free::tests::shear_drag_shows_its_angle_with_transform_tools_guides`, `a_handle_drag_that_changes_operation_relabels_it`). - Native macOS menu bar, vector tool cursors, a command palette (Help › Search Commands…), middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8). - - A Recent Commands button beside the Help › Search Commands field lists the last eight commands, tools, panels and effects picked from the palette, most recent first, with a command picked again moved to the top. A pick is recorded when it runs or opens a dialog, even if the dialog is then canceled; a pick that is refused because its menu item is dimmed, its tool can't be chosen or its panel can't be shown is not recorded, unless it opened a dialog. Choosing a row closes the palette and runs it as a pick of the same result does; with no picks yet the list shows a dimmed No recent commands row, and a command that is not available now, such as a filter of a plug-in that is not loaded, is left out until it comes back. The ids are saved with the UI state. While the list is open, Up and Down move through its rows, wrapping at the ends, and Escape closes the list before the palette. This is VectorCraft's own addition and does not raise a score (#6376; `palette` tests `recent_commands_*`, `a_recent_command_runs_what_its_pick_runs`, `the_keys_wrap_within_recent_commands`, `escape_closes_recent_commands_before_the_palette`). - - With an empty search, or one of spaces only, the Help › Search Commands field lists the picks of the Recent Commands list (at most eight, leaving out a filter of a plug-in that is not loaded) under a Recent heading, most recent first, with the first highlighted and no result count, so opening the palette and pressing Enter picks the last pick again; a pick that is dimmed now shows why in the status line, as from a search, and keeps its place in the list. With no picks yet it lists no results and shows a dimmed Type to search commands, tools, panels and effects line. A pick of Search Commands… itself is not recorded. The palette opens with its first result highlighted and its list scrolled to the top. This is VectorCraft's own behavior (`palette` tests `an_empty_search_lists_the_recent_picks_most_recent_first`, `an_empty_search_without_picks_says_what_to_type`, `enter_on_an_empty_search_runs_the_last_pick_again`, `the_palette_opens_again_with_its_first_row_highlighted`, `the_palette_toggle_is_not_a_recent_pick`, `a_click_on_a_recent_pick_runs_it_and_moves_it_first`, `a_pick_says_whether_it_ran_opened_a_dialog_or_was_refused`, `a_refused_pick_is_not_recorded`, `a_pick_that_opens_a_dialog_is_recorded_even_when_canceled`). - Help › Search Commands… is the first item of the Help menu in the window, with its shortcut and a separator after it; in the native macOS menu bar it is the first item below the system's search field. This is VectorCraft's own order and does not raise a score (`menus::tests::help_starts_with_search_commands`, `tests::nativemenu::the_mac_help_menu_starts_with_search_commands`). + - A Recent Commands button beside the Help › Search Commands field lists the last eight commands, tools, panels and effects picked from the palette, most recent first, with a command picked again moved to the top. A pick is recorded when it runs or opens a dialog, even if the dialog is then canceled; a pick that is refused because its menu item is dimmed, its tool can't be chosen or its panel can't be shown is not recorded, unless it opened a dialog. Choosing a row closes the palette and runs it as a pick of the same result does; with no picks yet the list shows a dimmed No recent commands row, and a command that is not available now, such as a filter of a plug-in that is not loaded, is left out until it comes back. The ids are saved with the UI state. While the list is open, Up and Down move through its rows, wrapping at the ends, and Escape closes the list before the palette. This is VectorCraft's own addition and does not raise a score (#6376; `palette` tests `recent_commands_*`, `a_recent_command_runs_what_its_pick_runs`, `the_keys_wrap_within_recent_commands`, `escape_closes_recent_commands_before_the_palette`). + - With an empty search, or one of spaces only, the Help › Search Commands field lists the picks of the Recent Commands list (at most eight, leaving out a filter of a plug-in that is not loaded) under a Recent heading, most recent first, with the first highlighted and no result count, so opening the palette and pressing Enter picks the last pick again; when no callout can point at the highlighted pick's home, the line under the list still says where it is. A pick that is dimmed now shows why in the status line, as from a search, and keeps its place in the list. With no picks yet it lists no results and shows a dimmed Type to search commands, tools, panels and effects line. A pick of Search Commands… itself is not recorded. The palette opens with its first result highlighted and its list scrolled to the top. This is VectorCraft's own behavior (`palette` tests `an_empty_search_lists_the_recent_picks_most_recent_first`, `an_empty_search_without_picks_says_what_to_type`, `enter_on_an_empty_search_runs_the_last_pick_again`, `the_palette_opens_again_with_its_first_row_highlighted`, `the_palette_toggle_is_not_a_recent_pick`, `a_click_on_a_recent_pick_runs_it_and_moves_it_first`, `a_pick_says_whether_it_ran_opened_a_dialog_or_was_refused`, `a_refused_pick_is_not_recorded`, `a_pick_that_opens_a_dialog_is_recorded_even_when_canceled`, `under_the_recent_picks_the_footer_names_a_home_out_of_view`). - The app bar's search control is a field showing a magnifier, "Search commands" and the Help › Search Commands… shortcut. The field shows no shortcut when the shortcut is cleared or too long to fit beside the text; the tooltip and the screen-reader name still give it. A click on the field, or Enter or Space while it has the keyboard focus, toggles the command palette as the shortcut does, and the palette's popup holds the text field. While the field has the focus, the app's existing rule for a focused control keeps the app's own keys off, so Enter does not open Move and Tab moves the focus on. While a dialog is open the field and the icon are drawn disabled and do nothing, as the shortcut does. Screen readers name the field and the icon Search commands, with the shortcut. As the bar narrows, the community button goes first, then Explore tutorials, then the field becomes the magnifier icon, then the workspace switcher narrows to 64 points, then the icon goes; Safe Mode's label keeps its room first. The field is wider than the icon, so the community button and Explore tutorials go at wider bars than they did beside the icon. This is VectorCraft's own addition and does not raise a score (`chrome::tests`: `the_app_bar_gives_up_its_right_hand_controls_in_order`, `a_wide_app_bar_shows_a_search_field_with_the_palette_shortcut`, `the_search_field_follows_the_palettes_shortcut`, `a_long_shortcut_leaves_the_search_hint_readable`, `a_click_on_the_search_field_opens_the_palette`, `the_search_icon_has_the_fields_name_and_both_are_disabled_under_a_dialog`, `the_keyboard_opens_the_palette_from_the_search_field`, `a_narrowing_app_bar_turns_the_search_field_into_the_icon`). - The Learn panel (Window › Learn, or Explore tutorials beside the search field on the app bar) has a For you tab with a Get started section and a Quick skill guide card, and a Skills tab that lists VectorCraft's own skills with their progress rings and counts of tutorials finished; a skill lists its tutorials, a tutorial shows its numbered steps, and Back goes up a level; `learn.list`, `learn.tab {tab}`, `learn.skill {skill}`, `learn.show {tutorial}` and `learn.back` script it, and the tab buttons, the rows and Back run them ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `panels::learn::tests`). - **Windows/Linux menu access keys (#6596):** Alt+letter opens any of the nine in-window menu roots, with access letters underlined in the current language; letters and arrow keys reach visible nested and dynamic menus. Alt+O, P, Right, O opens Offset Path; in English, Alt+S, S opens Save Selection and Alt+S, E opens Edit Selection. Disabled items stay unavailable, colliding letters cycle choices for Enter, and changed menus discard stale choices. Escape and focus loss dismiss menu access while text editing, IME/AltGr input, custom shortcuts and active tool/pointer gestures keep their normal ownership. Keyboard focus reveals rows in long menus and wheel scrolling returns control to the pointer (`crates/ui-egui/tests/menu_access_keys.rs`). @@ -1217,16 +1234,19 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **The Symbols panel reads its current symbol from the document:** the Symbols panel and its panel menu read the current symbol on each frame without running `symbol.list`, which counts every symbol's instances by walking the whole document. The current symbol they show and act on is the one `symbol.list` reports, and an idle frame of the panel or its menu runs no command, so on macOS the native menu is not brought up to date on every frame while the panel is open. In a document with 200 symbols and 50,000 objects, the read takes 0.035 µs instead of 48.5 ms in a release build (thread CPU time on Linux, median of 7 runs); in a small document the difference is too small to notice. Tests: `tests::brushsym::current_symbol_is_the_current_symbol_list_answers`, `panels::symbols::tests::current_is_the_current_symbol_list_answers`, `panels::symbols::tests::idle_frames_of_the_panel_and_its_menu_run_no_command`; the timing probe is `panels::symbols::tests::current_symbol_read_timing`. - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. - - **Symbolism Tools Options** ([Symbolism tool options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbolism-tool-options.html), [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): the dialog a double-click on a symbolism tool opens has, besides Diameter, Intensity and Symbol Set Density, Use Pressure Pen (a pen's pressure is the intensity), Method (User Defined, Average or Random) for the Scruncher, Sizer, Spinner, Stainer, Screener and Styler, Show Brush Size and Intensity, the Symbol Sprayer's Scrunch, Size, Spin, Screen, Stain and Style (each Average or User Defined), and the Symbol Sizer's Proportional Resizing and Resizing Affects Density; a new Symbol Set Density spaces the instances of the selected symbol sets (`symbol.setDensity`). VectorCraft's own rules: a Tool row lists the eight tools by name and shows the chosen one's options; Random gives each instance its own share of the change for the whole stroke; Average moves each value toward the mean of the instances under the brush; the starting values are Method User Defined, the Sprayer's six options Average, Proportional Resizing on and Resizing Affects Density off, so only a Sprayer stroke over instances of the selected set changes from before (its new instances take their mean values); the brush shows the intensity as a dashed ring. The Symbol Sprayer does not use Intensity or pen pressure. Tests: `crates/engine/src/tests/symbolism_options.rs`, `symbolism::tests` in `crates/tools`, `dialogs::symbolism_options::tests`. + - **Symbolism Tools Options** ([Symbolism tool options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbolism-tool-options.html), [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): the dialog a double-click on a symbolism tool opens has, besides Diameter, Intensity and Symbol Set Density, Use Pressure Pen (a pen's pressure is the intensity), Method (User Defined, Average or Random) for the Scruncher, Sizer, Spinner, Stainer, Screener and Styler, Show Brush Size and Intensity, the Symbol Sprayer's Scrunch, Size, Spin, Screen, Stain and Style (each Average or User Defined), and the Symbol Sizer's Proportional Resizing and Resizing Affects Density; a new Symbol Set Density spaces the instances of the selected symbol sets (`symbol.setDensity`). VectorCraft's own rules: a Tool row lists the eight tools by name and shows the chosen one's options; Random gives each instance its own share of the change for the whole stroke; Average moves each value toward the mean of the instances under the brush; the starting values are Method User Defined, the Sprayer's six options Average, Proportional Resizing on and Resizing Affects Density off; with them, two strokes change from before: a Sprayer stroke over instances of the selected set gives its new instances their mean values, and the Symbol Styler applies the style by the brush's strength, so a click at the brush's center at the default intensity 5 applies it at half opacity instead of in full, and a stroke's samples add up; the brush shows the intensity as a dashed ring. The Symbol Sprayer does not use Intensity or pen pressure. Tests: `crates/engine/src/tests/symbolism_options.rs`, `symbolism::tests` in `crates/tools`, `dialogs::symbolism_options::tests`. + - **Symbolism tools with Shift** ([the manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=199), [the CS6 reference](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=136)): a Shift-click with the Symbol Shifter brings the instances under the brush forward in the stacking order and Alt+Shift-click sends them backward; the Symbol Sizer with Shift keeps the set's density while it resizes; the Symbol Stainer and the Symbol Styler with Shift keep the amount of stain or style and move the color or style toward the current fill or the selected style (`symbol.adjust {shift}`). VectorCraft's own rules: the Shifter moves each instance one place among its siblings, once per stroke, without moving it on the canvas; the Sizer keeps each instance's center, even with Resizing Affects Density; a stain or style with no form between it and the new paint (a solid color and a pattern) takes the new paint at once; an instance without a stain or style is left as it is, and Alt has no effect on the Stainer or the Styler with Shift. The selected style is the one last clicked into the Graphic Styles panel's selection. Tests: `crates/engine/src/tests/symbolism_shift.rs`, `symbolism::tests::shift_reaches_the_tools_that_have_a_shift_form`, `panels::graphic_styles::tests::shift_click_selects_a_range_and_cmd_click_adds_or_removes_one_style`. - **The Symbols and Properties panels find selected symbol instances once per revision:** whether the selection or its groups hold a symbol instance (Break Link to Symbol), one with appearance changes of its own (Reset Symbol Instance and the Properties panel's Reset), or one Reset Transformation would change is worked out in one walk of the selected objects for each document revision, and later frames reuse it. The buttons and menu items are enabled as before. With one selected group of 300,000 paths, the two panels' reads took a median 5.1 to 5.7 ms of thread CPU time per frame; the first read after a change now takes about 3 ms and later frames about 5 ns (Linux, opt-level 3, median of 7 runs). In a small document the difference is too small to notice. Tests: `panels::symbols::tests::instance_flags_are_found_once_per_revision_and_match_a_walk_of_the_selection`, `properties_and_symbols_panels_walk_the_selection_once_per_revision`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). - - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Arrows) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. + - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Engraving, Arrows) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust); Engraving adds fine-line hatching art brushes (Fine Hatching, Dense Hatching, Tapered Hatching, Broken Hatching). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). - **Stipple library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Stipple holds Fine Stipple, Dense Stipple, Soft Stipple and Bold Stipple. These original scatter brushes place filled vector dots or small dot clusters along a path, with varied size, spacing and spread; Soft Stipple uses translucent dots. Their art and settings are VectorCraft's own. Evidence: `stipple_library_draws_dot_textures_and_survives_save` in `crates/engine/src/tests/brushlib.rs` covers listing, finite drawn geometry, dots that take the stroke color with only Soft Stipple's translucent, add and apply, and saved-library reopening. - **Bristle strokes follow recorded pen input** ([brush documentation](https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=201)): a Bristle brush in VectorCraft widens its strand spread and thickness with pressure along the stroke; pen tilt changes the spread, and bearing and barrel rotation turn it in the path's local frame. Missing pen channels use neutral values, and mouse strokes keep their existing appearance. This is VectorCraft's own rendering model; hardware-specific output has not been verified. `bristle_pen_pressure_changes_its_footprint`, `bristle_pen_pressure_is_sampled_along_the_stroke`, `trimmed_bristle_strands_read_pressure_where_they_begin` and `bristle_pen_orientation_changes_its_footprint` cover the geometry in `crates/brush/src/tests.rs`; `bristle_path_keeps_and_draws_its_pen_pose` covers saving and export in `crates/engine/src/tests/brushsym.rs`; area scores unchanged. - **Tech Circuit library:** Circuit Trace is a chamfered art brush with 45-degree elbows and terminal pads; Bus Lines repeats three parallel conductor lanes; Terminal Nodes repeats solder pads, circular test points and connecting leads. Original vector geometry generated in code, with Tints colorization and continuous pattern tile edges. Evidence: `the_tech_circuit_library_constructs_adds_and_applies_each_brush` in `crates/engine/src/tests/brushlib.rs` covers listing, finite geometry on straight, curved, short and closed paths, add/apply, undo/redo, deduplication and saved-library round trips. G5 remaining estimate 3–13 h (estimated); area scores unchanged. + - **Engraving library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Fine Hatching, Dense Hatching, Tapered Hatching and Broken Hatching make fine parallel-line textures along paths. These four 100 pt art brushes are original VectorCraft geometry, with Tints colorization; they can be added, applied and saved through the existing library controls. - **Image Brush library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Image Brush offers Soft Bloom, Halftone Field, Solar Grain and Color Flecks as original image stamp designs. Each preset places copies of its embedded, transparent PNG along a path as a scatter brush; adding a brush carries its image resource into the document, and saving a library keeps the pixels. The public page names the category but not these presets. Evidence: `image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved` in `crates/engine/src/tests/brushlib.rs` covers stamps, add/apply and reopening; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers the UI. - **Pressure Sensitive library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Pressure Sensitive offers Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow. The first two are art brushes whose width follows recorded pen pressure; the other two are calligraphic nibs whose size follows it. They use the engine's existing pressure input where the device and platform deliver it, and a neutral width for a mouse path. These presets and names are VectorCraft's own. Evidence: `pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` checks light and heavy pressure, short and curved paths, add/apply and saved-library reopening; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers opening and clicking from the UI. + - **Paint library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Paint offers Flat Sweep, Dry Drag, Loaded Stroke and Fan Sweep. These original art brushes stretch broad, broken, loaded and fanned vector marks along a path and take the stroke color as tints. The public source describes the Paint category's varied thickness, textured edges and natural effects; the preset designs and names are VectorCraft's own. Evidence: `paint_brushes_draw_distinct_marks_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers finite output on short, long and curved paths, add/apply and saved-library reopening; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers opening and clicking from the UI. - **Dry Media library** ([help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Dry Media holds four art brushes with textured strokes like dry drawing materials, each 100 pt long: Chalk Grain (about 8 pt high), Graphite Pencil (about 2.3 pt), Wax Crayon (about 5.5 pt) and Charcoal Dust (about 7 pt). The brushes, their names, sizes and art are VectorCraft's own: each is filled vector paths from a fixed seed, at most 80 paths and 500 anchors, stretched along the path with Tints colorization, and the chalk and crayon art has even-odd gaps where the paper shows (`brush.libraries`, `brush.addFromLibrary`; `the_dry_media_library_holds_grainy_art_brushes_with_bounded_art`). - **Arrows library:** Window › Brush Libraries › Arrows holds five art brushes, each 100 pt long: Solid Arrow, Open Arrow (an outlined head), Double Arrow (a head at each end), Chevron Arrow (a second chevron on the shaft) and Dashed Arrow (five separate dashes and a head). Each brush stretches only the part between its guides, so the shaft follows the path's length and the heads keep their proportions, with Tints colorization. The brushes, their names and their art are VectorCraft's own, generated in code (`brush.libraries`, `brush.addFromLibrary`; `arrows_library_lists_renders_and_applies_original_brushes`, `dashed_arrow_keeps_separate_dashes_and_survives_library_save`). - **Brush names in library panels**: a built-in brush library's panel shows its brushes' names in the UI language, in its list rows and tooltips, and its Find field matches the name shown or the English name. This is VectorCraft's own rule. A User Defined or Other Library… library's brushes, and the document's Brushes panel, show names as they are stored. A click, a drag, Add to Brushes and `brush.addFromLibrary` still use the English name, so the brush comes into the document under that name (`built_in_library_brushes_are_listed_in_the_ui_language`, `built_in_library_brush_names_are_in_complete_catalogs`). @@ -1342,6 +1362,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Polygonal Lasso selects anchor points (and gradient mesh points) inside a straight-edged loop, with the Lasso's rule for which points are inside, and is listed under Object › Plug-ins and under its own heading in All Tools. It has no default shortcut or Basic toolbar slot. Each click sets a vertex. A double-click, Enter or a click on the first vertex closes the loop, Backspace or Delete removes the last vertex, Escape drops the loop, and Shift keeps the next segment to 45° steps. Shift or Alt held at the first click adds to or subtracts from the selection. This is a VectorCraft addition; scores and estimates are unchanged. Select by Artboards (Object › Plug-ins › Selection Tools, a VectorCraft addition: #5525, #5548, #5549) selects the objects overlapping, fully inside or fully outside one or more chosen artboards (`addon.select.byArtboards {artboards, relation}`). Overlapping is All on Active Artboard's test, shared as `select::on_artboard`; Fully inside means within one artboard, edges included; Fully outside means on none. It looks at what Select All takes, so hidden, locked and locked-artboard art stays out. Its dialog lists each artboard's number, name and size in the document's units, filters by name, chooses rows with click, Shift-click and Cmd/Ctrl-click, and fits a row's artboard in the window on double-click (`view.goToArtboard`). Tests: `crates/engine/src/cmd/addons/select/tests.rs`, `crates/ui-egui/src/addons/select/tests.rs`, `crates/engine/tests/command_sweep.rs`. Select by Link Status (Object › Plug-ins › Selection Tools and the Links panel menu, a VectorCraft addition: #5526) selects the image objects and placed documents whose link is linked (its file found unchanged), embedded, missing or modified, as `links.list` reports it (`addon.select.byLinkStatus {status, ids?, add?, zoom?}`); Select Linked, Embedded, Missing and Modified are off when no image has that status and add to the selection with Shift. Objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard, or outside the isolated group are left out (the `select::is_selectable` test) and returned with the reason, and the status bar says how many, in plural forms of every catalog. Select by Link Status… lists each image and placed document with its name, status and format, searches by name, filters by status, picks rows with checkboxes and All / None, and zooms to the selection with the existing Zoom to Selection (`addon.arrange.zoomSelection`). Missing-link markers on the canvas are #5547. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`by_link_status`), `crates/ui-egui/src/addons/select/link_status/tests.rs`, `crates/engine/tests/command_sweep.rs`. + The Links panel provides an item right-click context menu on link rows offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Separator, and Embed Image / Unembed…. Right-clicking an unselected row selects that row first; right-clicking a row that is already part of a multi-selection preserves the multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`. A marquee selects a clip group, or an object on a layer with a clipping mask, only when it reaches the area inside the clipping path, and it measures the art only within that path's bounds. Within the bounds of a mask that is not a rectangle, it can still select art that the mask hides. Direct Selection's marquee still selects the hidden anchor points inside it (#2345). When a clip group, a layer with a clipping mask or a single object in one is isolated, the Selection, Direct Selection and Group Selection tools also select the art that the mask hides, by a click or a marquee, and a drag from that art moves it (#3748). In isolation mode the canvas Unlock submenu also lists that art when it is locked. Outside isolation mode a click selects clipped art only inside the mask. A marquee selects a Shaper Group only when it reaches the art the group shows, not the original shapes kept under it, and Direct Selection's clicks and marquee do not select those shapes' anchor points. In Construction mode a marquee selects the original shapes, and Direct Selection selects their anchor points. @@ -1540,7 +1561,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A modal window that opens without a press in the window (a dialog opened from the macOS menu bar or by an automation command, the About window, a file dialog, the update prompt, or the progress window of a plug-in, trace or open run) closes the Command Palette, a tool group's flyout, the All Tools drawer and any open menu or popup in the pass it opens. While such a window is open, the palette stays closed, so opening it from the macOS menu bar or by an automation command does not take the keyboard from the window; it opens again once the window closes (`palette` tests `a_dialog_opened_from_the_system_menu_closes_the_palette`, `the_about_window_closes_the_palette`, `a_progress_window_closes_the_palette`, `the_palette_opened_over_a_dialog_closes`, `a_click_on_the_menu_bar_closes_the_palette_before_a_dialog_opens`, `a_dialog_opened_without_a_press_closes_a_flyout`, `a_dialog_opened_without_a_press_closes_the_tools_drawer`, `a_dialog_opened_without_a_press_closes_a_menu`, `the_palette_opened_as_a_dialog_closes_stays_open_until_the_next_dialog`). The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name without its menu path starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word, so a query that is a menu's title ("object") lists results named with that word above the items of that menu. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…, and of two results of the same kind the shorter name comes first. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs); with the native macOS menu bar, the items that bar moves into its application menu are found under it (Preferences… under Settings). Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `a_menu_title_does_not_lift_its_items`, `common_queries_list_the_command_near_the_top`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`, `native_homes_follow_the_native_application_menu`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`). A Command Palette query word in an English plural or verb form finds a result whose English name or menu path holds the base word: "rounded corners" lists Effect › Stylize › Round Corners… first, and "scaling" finds Object › Transform › Scale…. The search drops `'s`; `es` after `s`, `x`, `z`, `ch` or `sh` (also trying the word with only its `s` dropped, so "rasterizes" finds Rasterize…); a final `s` in words of more than 3 letters, except after `ss`, `us` or `is`; `ing` in words of more than 5 letters and `ed` in words of more than 4. After `ing` or `ed`, a doubled `b`, `d`, `g`, `m`, `n`, `p`, `r` or `t` is tried both single and doubled, the single letter only when at least 3 letters are left ("cutting" meets Cut, "added" meets Add); otherwise the word is also tried with an `e` ("scaling" meets Scale…). It turns `ies` into `y` or `ie` in words of more than 5 letters and `sses` into `ss`, and leaves `series` and `species` as they are. Among results that the whole query matches the same way (as an id, as a label, at the start of a label, as initials, or none of these), a result whose name holds the base word of a query word ranks below one that holds the query word whole and above one where the query word only starts a word of the name, so "scale zz" lists a name with "Zz Scaling" above one with "Zz Scalers". "scale" alone still lists "Scalers" above "Scaling", because "Scalers" starts with the query. A partly typed word that is not itself a word of any result ("scal") does not meet a base word. Names shown in other languages and ids are not changed this way, and every result found before is still found (`palette::search` tests `plurals_and_verb_forms_meet_their_base_word`, `a_plural_or_verb_form_finds_the_result`, `a_better_word_grade_ranks_first`, `a_partly_typed_word_does_not_lift_a_verb_form`, `a_whole_query_tier_comes_before_a_stem_form`, `results_matched_without_a_stem_keep_their_order`). - A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it (also when another result matches it through a word with the same meaning, so "spin" finds Span as well as Rotate) with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches in its name, menu path or id without one, and before every result the query matches only through its description; among them the query is read with the misspelled word replaced by the word it meets, so they come in the order the word spelled right gives; then a result whose label holds the word comes before one whose menu path holds it. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and results without typos keep their order (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `a_word_with_the_same_meaning_elsewhere_still_finds_a_typo`, `a_description_match_ranks_below_a_typo`, `misspelled_words_find_the_command`). + A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it (also when another result matches it through a word with the same meaning, so "spin" finds Span as well as Rotate) with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches in its name, menu path or id without one, and before every result the query matches only through its description; among them the query is read with the misspelled word replaced by the word it meets, so they come in the order the word spelled right gives; then a result whose label holds the word comes before one whose menu path holds it. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and matching through a typo does not change the order of the results matched without one (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `a_word_with_the_same_meaning_elsewhere_still_finds_a_typo`, `a_description_match_ranks_below_a_typo`, `misspelled_words_find_the_command`). A Command Palette query word also finds a result whose name or menu path holds a word with the same meaning: "remove bg" lists Remove Background… first, "outline text" lists Type › Create Outlines first, and "flip", "combine", "vectorize" and "colour" list Reflect…, Unite, an Image Trace command and the Color panel among the first 3 results. The words come from VectorCraft's own table of 21 groups of English words (`palette/words.rs`, at most 60 groups of at most 6 words); a word that is the whole label of another command, such as Merge or Mirror, is in no group, and neither is Insert. A word or its English base word that is in a group meets the other words of its group in labels and menu paths, and their base words, but not ids or word starts. A result whose label holds the word itself ranks above one whose label holds a word with the same meaning, which ranks above one whose menu path holds the word, so "type" now lists Scale Text Attributes above Type › Orientation › Vertical. A catalog may add a group's words in its language with a row in the `search` context (the group's English words joined by ", ", then that language's words), used while that language is the UI language; no catalog has to have these rows (`palette::search` tests `a_word_with_the_same_meaning_finds_the_result`, `a_catalog_row_adds_words_to_a_group`, `words_with_the_same_meaning_find_the_command`; `palette::words` tests; `i18n` test `search_rows_name_a_group_and_add_single_words`). 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`). @@ -1805,6 +1826,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Pattern editing mode and opacity mask editing exclude each other, by a rule of VectorCraft itself: in pattern editing mode a click or Alt-click on the mask thumbnail does not edit the mask, and Make Mask is off for one object; while a mask is edited, Object › Pattern › Make and Edit Pattern are off. Disable, Enable, Unlink and Link Opacity Mask and Opacity Mask Options (`transparency.setOpacityMask`) record no undo step when every mask they act on already has the flags they set. - **Linked opacity masks follow geometry effects, the Free Transform distort and envelopes:** when masked art moves, a linked opacity mask moves with it and an unlinked one stays in place ([Transparency and blending modes](https://helpx.adobe.com/illustrator/using/transparency-blending-modes-alt.html)). Applying that rule when art is reshaped, as below, is VectorCraft's own rule. When a group's or layer's geometry effects (Transform, Free Distort, the Warp effects and the others) reshape its members, the linked masks of the paths, compound paths and groups inside it take the same effects, nested and inverted masks included, with the type and live objects in a mask's art outlined first. Each Transform copy of a masked path carries its own mask. An image or symbol instance that a group's Transform effect moves carries its linked mask too, and with Scale Strokes & Effects on, the mask's strokes scale as a path's mask's do. With Transform Objects off, a member's mask takes the effect's stroke and pattern changes as the member does. The linked masks in the art of a symbol instance in perspective are projected with that art. A Free Transform tool distort drag (`object.distort`) warps a linked mask with its object, in a group too, in the same undo step. An envelope bends only a linked mask. When a mask can't take an effect as the art it masks does (a path in either would pass the geometry budget, the mask would get fewer Transform copies, the mask's art holds an image or symbol instance and the effect is not Transform, a Warp effect would bend an image that has a linked mask, or the effect is a live-effect plug-in that paints its pieces), the art and its masks keep their shape under that effect. The copies of a masked path count the art of its mask against the budget. Existing documents draw differently in four cases: a geometry effect on a group whose members have linked masks moves those masks; an envelope no longer bends an unlinked mask; art with linked masks keeps its shape under an effect that its masks can't take; and a Transform effect can make fewer copies of a masked path near the budget (effects `group::tests::a_groups_geometry_effects_reshape_a_members_linked_mask_with_it`, `group::tests::a_groups_geometry_effects_reshape_nested_and_inverted_masks`, `group::tests::a_compound_paths_and_a_layers_members_masks_take_the_effects`, `group::tests::a_groups_effects_reshape_a_live_object_in_a_members_mask`, `group::tests::each_transform_copy_of_a_masked_member_carries_its_mask`, `group::tests::a_groups_transform_moves_an_image_members_linked_mask`, `group::tests::a_groups_transform_moves_a_symbol_instance_members_linked_mask`, `group::tests::a_groups_transform_moves_a_linked_mask_whose_art_is_an_image`, `group::tests::art_whose_mask_holds_an_image_keeps_its_shape_under_a_warp`, `group::tests::art_with_a_masked_image_keeps_its_shape_under_a_warp`, `group::tests::a_transform_with_scale_strokes_scales_the_masks_of_images_and_paths_alike`, `group::tests::a_transform_of_strokes_only_scales_a_members_mask_strokes`, `group::tests::perspective_projects_the_masks_in_a_symbols_art`, `group::tests::a_mask_whose_art_passes_the_budget_stays_whole`, `group::tests::art_whose_mask_would_take_fewer_copies_keeps_its_shape`, `group::tests::transform_copies_count_the_art_of_their_masks`, `group::tests::the_mask_of_a_masks_art_copied_whole_counts_against_the_budget`; engine `xform::distort_command_warps_a_linked_opacity_mask_with_its_object`, `xform::distort_command_warps_the_linked_mask_of_a_path_in_a_group`, `envelope_distort::an_envelope_bends_a_linked_opacity_mask_and_leaves_an_unlinked_one`, `plugins::a_painted_group_effect_leaves_art_with_a_linked_mask_as_it_is`). Scores and hours unchanged. +- **Image Trace, Ignore Color canvas sampling (#8068):** the panel eyedropper reads the selected placed image or the retained original image of a live trace without changing the canvas View. Outside and transparent pixels leave it armed; a valid pixel restores the previous tool. The manual picker, Preview-off drafts and Preview-on single-step retrace remain available. `tests/image_trace_ignore_sampler.rs` covers original-pixel sampling, the unchanged CPU canvas, missed-pick continuation, Preview/Undo, Escape, explicit tool choices, stale document/target/revision presses and cancellation while Selection borrows the Eyedropper; the restored lender is no longer armed. This is UI interaction evidence, not algorithm parity; scores, gaps and hours unchanged. - **Image Trace, thin closed outlines:** generated `fit::snap_area_tests` verify nonzero interiors after straightening, opposite closed-boundary winding and Noise controls; see [quality notes](image-trace-quality.md#thin-closed-outlines-with-snap-curves-to-lines). Scores and hours unchanged; open-piece fitting is unchanged. - **Image Trace, curve fitting tolerance:** the outline fitter keeps cutting a run while a point stays farther than the tolerance from its curve, so a run of fewer than six points or one cut 14 times no longer keeps a piece over the tolerance. Pieces already within the tolerance do not change, and noisy art can get more anchors. Tests: `logo::bezier::tests`, `logo::outline::tests`. Scores and hours unchanged. - **Image Trace, gray photos:** Color and Grayscale smooth a gray photo within its tones before choosing its colors, as they do a color photo. A picture with at least 95% of its opaque pixels within 8 levels across their channels counts as continuous tone when 8 colors leave an error of more than 6 levels and more than 0.065 of the error of one color, instead of 0.1, unless 16 colors leave at most a tenth of the error of 8 (VectorCraft's own values). That exception keeps gray flat art of up to 16 clean levels on its old route; anti-aliased or noisy gray flat art can now count as continuous tone too. Most gray photos the change reaches, and very noisy gray scans of flat art, trace with fewer specks and fewer staircase edges. Some 16 Colors and High Fidelity Photo palettes of gray photos grow toward the requested count, with more anchors and regions. Some gray illustrations and sketches get more anchors and staircase edges at 16 Colors and High Fidelity Photo, and some 6 Colors traces get more staircase edges. Tests: `tests::a_gray_photo_is_continuous_tone_as_its_color_original_is`, `tests::a_gray_photo_is_smoothed_before_it_is_traced`. Scores and hours unchanged. @@ -1918,6 +1940,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries, seven gradient libraries (among them Organic Fades, soft perceptually mixed multi-stop fades that thin out to transparent, and Holographic, seven opaque linear foils of narrow pastel and pearl bands and seven radial glows that fade out to a clear edge) and three pattern libraries (Geometric Patterns; Grit Textures with eight seamless grain, speckle, stipple, scratch and fleck tiles; and Optical Effects with eight of VectorCraft's own seamless wave, ring, warped-check, stripe, chevron and lens tiles; their swatches bring their patterns) in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate. Right-clicking a swatch in either list or thumbnail view selects it without applying paint and offers Swatch Options…, Duplicate Swatch and Delete Swatch for that item. None, [Registration] and missing swatches disable these actions. Existing active-item multiselection is retained; actions still target only the clicked item. Evidence: `panels::swatches::tests::context_menu` harness tests cover all five views, selection, dialog dispatch, duplicate/delete and Undo. All 39 Swatches tests pass; the regression fails with the menu hooks removed. Rendered headless list and thumbnail menus were inspected, and a fresh local deep CodeRabbit review reported zero findings. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. Validation on 2026-11-15: native Windows formatting, workspace Clippy and all 39 focused Swatches tests passed. Windows full CI stopped at unchanged engine tests `tests::package::a_confined_package_names_files_outside_the_read_root_by_name` (slash-sensitive report assertion) and `tests::plugins::plugin_storage_behind_a_link_is_left_alone` (storage-link setup returned AlreadyExists). Both cases pass in the Linux/WSL full CI run, which passed all 13 gates. No engine or CI workflow changes are included. + The Swatches panel menu has Add Selected Colors, on while art is selected: it adds a swatch for each color of the selected art that the panel does not hold yet, as global swatches the art's matching paints link to, in one undo step ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/use-swatches/add-colors-to-swatches.html) describes the panel menu command that adds the selected artwork's colors). The swatch names and the colors it reads (fills, strokes, text, gradient stops, mesh points) are VectorCraft's own, as for Add Used Colors. Add Used Colors and Add Selected Colors record no undo step when there is no new color, and still end typing in progress as its own step. With Global Edit on, the members the command does not read keep their colors. Evidence: `add_selected_colors_adds_the_selection_colors_as_global_swatches` in `crates/ui-egui/src/panels/swatches/tests.rs`; `add_used_colors_with_no_new_color_records_no_undo_step`, `add_used_colors_with_no_new_color_ends_the_typing` and `add_selected_colors_in_global_edit_keeps_the_other_members_colors` in `crates/engine/src/tests/swatchcmds.rs`. The panel's Delete Swatch and Swatch Options (footer buttons and panel menu), New Color Group and Save Swatch Library treat only None and [Registration] as reserved, so a user swatch or color group whose name starts with `[` can be deleted, edited, grouped and saved; selected names the document no longer holds are left out (`panels::swatches::tests::bracketed_user_swatches_and_groups_can_be_deleted_and_edited`). Dragging swatches onto Delete Swatch deletes them ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=136), Replace, merge, or delete swatches section, lists this drag as one of the ways to delete the selected swatches): a swatch or color group dragged from the Swatches panel, in any view, and released on the Delete Swatch button is deleted through `swatch.delete`, even while nothing was selected and the button is disabled for clicks. A swatch that is part of the selection carries the other selected swatches of its kind with it. VectorCraft's own rules: the drop asks first as a plain click does, and Alt does not skip the question; Cancel keeps everything, and OK deletes them in one undo step; None and [Registration] are never taken; the button is enabled while swatches are selected or while a swatch or group of the active document is being dragged, and it is outlined only while such a swatch or group is held over it, so a paint from another panel, art and a swatch dragged from another document delete nothing. Tests: `panels::swatches::tests::swatches_dropped_on_delete_swatch_are_deleted_after_asking`, `delete_swatch_ignores_other_drags`. Dragging swatches onto New Swatch duplicates them ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/use-swatches/duplicate-swatches.html) gives this drag as another way to duplicate the selected swatches): a swatch dragged from the Swatches panel, in any view, and released on the New Swatch button is copied through `swatch.duplicate` without opening the New Swatch dialog. A swatch that is part of the selection carries the other selected swatches with it. VectorCraft's own rules: each copy goes just after its swatch and in its color group, named ` copy` and then ` copy 2`; the copies of one drop are one undo step and are selected; modifiers held on release do not change the drop; color groups, None and [Registration] are not duplicated; the button is outlined only while such a swatch of the active document is held over it, so a paint from another panel, art, a swatch dragged from another document and a swatch deleted during the drag duplicate nothing. Tests: `panels::swatches::tests::swatches_dropped_on_new_swatch_are_duplicated`, `new_swatch_ignores_other_drags`. @@ -1931,6 +1954,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. EPS and SVG write the image's own pixels. - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. - **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given. + - **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 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. 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}`). @@ -1947,6 +1972,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A double-click right of an RGB field switches the Color panel's R, G and B between percent and 0 to 255 ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), Color panel). In VectorCraft the color does not change, Web Safe RGB and the hex field stay in 0 to 255, and the panel keeps the choice between sessions (`ui.colorPanel {rgbPercent}`); the color mixer of the Fill and Stroke chips and the gradient stop dialog follow the same setting. Toggle RGB Percent (`ui.colorRgbPercent`) in the command palette and Keyboard Shortcuts switches the units from the keyboard. Tests: `rgb_percent_switches_the_rgb_fields_between_percent_and_0_to_255`, `rgb_percent_does_not_switch_while_the_rows_are_disabled`, `rgb_percent_comes_back_after_a_restart` and `toggle_rgb_percent_switches_the_units_from_the_keyboard` in `crates/ui-egui/src/panels/color/tests.rs`. View › Proof Setup › Color blindness – Tritanopia-type turns Proof Colors on and proofs the canvas with the tritanopia simulation of Brettel, Viénot and Mollon (1997). The Separations Preview panel's Proof Setup list offers the same target (`view.proofSetup {target: "tritanopia"}`). Grays keep their value. In VectorCraft the Color Wheel panel menu's Show Color Vision Preview (`ui.colorWheel {vision: true}`) adds a row of four chips under the wheel or the box: the current color through the protanopia, deuteranopia and tritanopia simulations that View › Proof Setup uses, and an achromatopsia chip, which is VectorCraft's own gray with the color's CIE L*. Each chip takes the keyboard focus and gives its name and hex value in its tooltip and to screen readers, and a click on one does not apply it. The setting is kept with the preferences. Tests: `crates/ui-egui/src/panels/tests_color_wheel_vision.rs`. + View › Proof Setup › Customize… opens a Proof Setup dialog with Device to Simulate (the working CMYK space or any CMYK or RGB profile), Preserve CMYK Numbers or Preserve RGB Numbers, Rendering Intent (used while the numbers are not preserved), Simulate Paper Color and Simulate Black Ink, and Preview; OK sets the proof and turns Proof Colors on ([Soft-proof colors](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=146), "Custom soft-proof options"). In VectorCraft, Simulate Paper Color also shows the black ink, the two simulations act on CMYK devices only, and Cancel puts the earlier proof back (`ui.proofSetupDialog`, `view.proofSetup {preserveNumbers, simulateBlack}`). Tests: `simulate_black_ink_shows_the_press_black_as_gray`, `preserve_cmyk_numbers_sends_the_numbers_unchanged` and `rgb_device_proofs_show_the_device_numbers` in `crates/color/src/cms/tests.rs`, `proof_setup_takes_the_custom_proof_settings` in `crates/engine/src/tests/colormgmt.rs`, `customize_sets_the_proof_setup_and_turns_proof_colors_on` and `preview_shows_the_settings_and_cancel_puts_the_view_back` in `crates/ui-egui/src/dialogs/proof_setup.rs`. + The Proof Setup dialog's Save… and Load… buttons save the custom proof setup to a file and read one back, and View › Proof Setup lists the setups saved in the Proof Setups folder next to the preferences; choosing one applies it with Proof Colors on ([Save or load a custom proof setup](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=148)). The buttons and the saved setups are desktop only; the web build has neither. The file format (`.vcproof`, JSON, at most 64 KiB), the folder and the error for a device profile that is not loaded are VectorCraft's own (`view.proofSetup.save`, `view.proofSetup.load`, `view.proofSetup.read`, `view.proofSetup.list`). Tests: `a_saved_proof_setup_loads_back`, `proof_setup_files_refuse_what_they_cannot_use`, `proof_setups_saved_by_name_are_listed`, `proof_setups_are_listed_among_many_other_files`, `proof_setups_are_listed_by_names_that_load_them` and `proof_setup_names_that_are_not_unicode_are_left_out` in `crates/engine/src/tests/colormgmt.rs`, `save_and_load_keep_a_custom_proof_setup`, `a_canceled_save_leaves_no_folder`, `the_listing_after_a_save_asks_for_a_frame`, `load_starts_in_the_folder_once_it_exists`, `a_saved_setup_named_with_an_ellipsis_loads` and `load_of_an_unusable_file_keeps_the_dialog` in `crates/ui-egui/src/dialogs/proof_setup.rs`. The Separations Preview panel's Gamut Check button reports one color outside the CMYK gamut in the singular and more in the plural, in English and in each language's plural forms (`gamut_check_status_takes_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). The "?" on the Fill and Stroke proxies finds a few selected objects along their cached places in the document instead of walking every object; a large selection takes one walk, as before. The proxies show the same paints and question marks as before, also for an id that a damaged file repeats. On a document of 50,000 rectangles in 500 groups on 5 layers with one object selected, the check takes under 5 µs of CPU time instead of a median of 995 µs in a release build on Linux, so the gain shows on large documents (seven alternating runs, `cargo test --release -p vectorcraft-engine --lib proxy_mixed_timing -- --ignored --nocapture`). - **Document Color Mode outside the layers:** File › Document Color Mode (in one undo step) and `document.open {colorMode}` also convert the colors of graph designs, graphic styles, opacity-mask art, the tile that pattern editing's Cancel puts back and the art of brushes (with a Hue Shift brush's key color); a tint of a global swatch there becomes the converted swatch's color at its tint, as in the art. @@ -1956,6 +1983,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Document Color Mode for effects and graphs:** File › Document Color Mode and `document.open {colorMode}` convert the colors of effects (Drop Shadow, Inner Glow, Outer Glow and the other effects with a color, on objects, their fills and strokes and in graphic styles) and the series paints and label styles that a graph keeps, so a graph drawn again from new data keeps the converted colors; File › Document Color Mode also converts the fill and stroke that new art takes. Undo restores the original new-art fill and stroke and Redo applies the conversion again. - **Recolor Artwork layout (#3416):** the Edit chip list uses the modal scroll helper and its actual remaining height; the tab's minimum-height space scrolls with the chips. `tests_recolor` covers 5/20/200/400 colors, window resizing, 100/125/150/200% UI scaling, scrolling to and editing the final chip, Preview, Cancel, Confirm and Undo, alongside the existing #1733 drag regressions. Scores and estimates unchanged. - **Recolor Artwork Edit displays:** buttons beside the Edit tab's wheel show the colors on a smooth color wheel, a segmented color wheel or as color bars ([Edit colors using Recolor Artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-colors-using-edit-colors-dialog.html)). The segmented wheel draws 24 hues by 5 saturations as solid patches, and its markers move freely as on the smooth wheel. The bars show one solid bar per recolored color in row order: a click selects a bar for the color sliders, and a drag moves its row without changing a color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The dialog opens on the smooth wheel; `display` (`smooth`, `segmented`, `bars`) is the dialog field. `tests_recolor` covers switching, the dialog height, segmented dragging and Brightness, and bar selection, editing, reordering, scrolling, Preview, Cancel and OK. Scores and estimates unchanged. + - **Recolor Artwork base color and right-click menus:** a right-click on an Edit tab wheel marker or a color bar offers Set As Base Color, Select Shade, Color Picker and Remove Color, and a right-click elsewhere on the wheel offers Add New Color; a color added on a marker's line moves with that marker; Set Current Color As Base Color makes the selected color the base, and the harmony rules build from the base color whichever color is selected ([Edit swatch groups using the color wheel](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-color-groups-using-the-color-wheel.html), [Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [archived user guide, pages 137 to 140](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf)). The base color is the row with `base: true`, or the first color shown; a color added on a marker's line follows the marker's `tie` with `follows`. VectorCraft's own rules: an added color takes the selected color's brightness, or its saturation on the brightness wheel (the base color's when none is selected), Select Shade's grid is 7 saturations by 7 brightnesses of the color's hue and moves the color as a drag of its marker would, and a tied color follows its marker only while the colors are unlinked (linked, every color moves). Tests: `a_markers_menu_sets_the_base_color_that_the_rules_build_from`, `select_shade_gives_a_marker_the_shade_clicked`, `a_markers_menu_opens_the_color_picker`, `add_new_color_on_a_markers_line_moves_with_that_marker` and `set_current_color_as_base_color_marks_the_selected_color` in `crates/ui-egui/src/tests/recolor.rs`, and `set_base_moves_the_base_mark`, `the_base_mark_follows_merge_separate_and_randomize`, `a_color_added_on_a_markers_line_moves_with_it` and `the_shade_grid_spans_saturation_and_brightness` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. - **Recolor Artwork Add Color and Remove Color tools:** under the display buttons beside the Edit tab's wheel, the Add Color tool adds the color clicked on either wheel to the color group, and the Remove Color tool removes the color whose marker is clicked; a color bar's right-click menu has Remove Color, and the base color can't be removed ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Edit swatch groups using the color wheel](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-color-groups-using-the-color-wheel.html)). An added color is a new row with no current colors and `added: true`; unlike a row made with New Row, it adds its new color to a rewritten color group, after the group's other colors. VectorCraft's own rules: an added color takes the base color's brightness, and with art or a group a removed color's row stays with its current colors and no new color, so that art keeps its colors and the group's swatch at that place is removed. `wheelTool` (`add`, `remove`) is the dialog field. Tests: `the_add_color_tool_adds_a_row_with_no_current_colors`, `an_added_color_joins_the_color_group`, `the_remove_color_tool_removes_a_marker_but_not_the_base_colors` and `a_color_bars_menu_removes_its_color` in `crates/ui-egui/src/tests/recolor.rs`, `apply_params_give_the_group_added_colors_and_keep_its_other_colors` in `crates/ui-egui/src/dialogs/recolor.rs`, and `an_added_empty_row_gives_the_group_its_color_after_the_others` in `crates/engine/src/tests/recolor.rs`. Scores and estimates unchanged. - **Recolor Artwork brightness and hue wheel:** a button under the Edit tab's wheel tools switches the wheel between hue with saturation and hue with brightness; a marker's angle sets its hue, and its distance from the center sets the component the wheel shows ([Recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/recolor-options-overview.html), [archived help, Edit colors](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=144)). VectorCraft's own rules: brightness runs from black at the center to full at the edge, the segmented wheel's five rings become brightness steps, the slider under the wheel edits the component the wheel leaves out (Saturation on the brightness wheel), Add Color takes the hue and brightness clicked at the base color's saturation, the choice holds for both wheels while the dialog is open and the button is off for the color bars, and each opening shows hue and saturation. `wheelAxes` (`hueSaturation`, `hueBrightness`) is the dialog field. Tests: `the_brightness_and_hue_wheel_swaps_the_wheel_axis_and_the_slider`, `a_marker_on_the_brightness_wheel_sets_hue_and_brightness`, `the_add_color_tool_on_the_brightness_wheel_adds_the_brightness_clicked` and `the_segmented_brightness_wheel_has_24_hues_by_5_brightnesses` in `crates/ui-egui/src/tests/recolor.rs`, and `an_added_color_on_the_brightness_wheel_takes_the_base_colors_saturation` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. - **Recolor Artwork Find:** the Assign tab's Find button finds the colors of the selected rows in the art ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)): while it is on, their art shows as the preview shows it and the rest of the selected art shows dimmed, until a second click ([archived help, Recolor Artwork](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=149)). VectorCraft's own rules: a dimmed color is a 25% tint of its current color (or the nearest lighter tint when that one is a color a selected row lists), a color a selected row also lists is not dimmed, and Find records no undo step. `findColors` is the dialog field. Tests: `find_dims_the_colors_of_the_rows_not_selected` and `find_shows_the_selected_rows_art_and_dims_the_rest` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged. @@ -2260,7 +2288,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur EPS export and EPS Save make each file's PNG thumbnail from its TIFF preview, averaging the preview's pixels down to the thumbnail's size on white, instead of drawing the document a second time; a file without a preview still draws its thumbnail (`crates/engine/src/cmd/fileio/tests_eps.rs`). - Targa files (`.tga`, `.vda`, `.icb`, `.vst`) open, place linked or embedded, relink and update at their pixel size: color-mapped, true-color and black-and-white, raw or run-length encoded, in any of the four row orders. The image descriptor's attribute bits and the extension area's Attributes Type decide the transparency: a file with no attribute bits, or with attribute data the Attributes Type calls undefined, opens opaque; with one bit, a 16-bit true-color pixel takes that bit as its alpha, and a color-mapped pixel takes the bit of the 16-bit color map entry it indexes; premultiplied colors are divided by their alpha. Open and Place recognize a Targa file by its extension, and `clipboard.importImage` and Glass's Load Texture… by its header; a Targa file copied in a file manager pastes as a bitmap (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/tests/links.rs`). - BMP files named `.dib` or `.rle` (run-length encoded bitmaps included), Photoshop files named `.pdd` and PNG files named `.pns` open and place, linked or embedded, as BMP, PSD and PNG files, in any letter case: the Open and Place dialogs list them with their format, the Links panel names their format, and Edit Original opens them. Exports write only `.bmp`, `.psd` and `.png` (`crates/engine/src/cmd/fileio/tests_tiffbmp.rs`, `crates/engine/src/cmd/fileio/tests_psdread.rs`, `crates/engine/src/tests/links.rs`). - - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), and adjustment layers, layer effects, knockouts and vector masks aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). + - File › Open converts a PSD or PSB file's layers to objects, keeping the layer structure, merging clipped layers into one layer, merging a layer that uses a Knockout option with the layers below it, and leaving out hidden layers that would need a merge, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for the option that converts layers to objects; hidden layers come in with `hiddenLayers`, as Import Hidden Layers brings them in, and `layers: false` opens the merged image. VectorCraft's own rules: each layer becomes a layer holding its pixels with its name, visibility, opacity and blend mode, groups become layers of sublayers, layers in Dissolve, Linear Burn, Linear Dodge, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color and Lighter Color are merged with the layers below, layer masks become opacity masks, fill opacity multiplies the opacity (in a layer that others are clipped to, it fades only that layer's own pixels), a Knockout value of 1 is read as a shallow knockout and applied to a layer or group inside a group, which is merged with the visible layers below it in that group (its pixels clear them to transparency, it is drawn there at its fill opacity, and its opacity fades the result; in a pass-through group only when it and the visible layers below it are in the Normal mode; a knockout at 0 opacity, or at 0 fill where it covers none of their painted pixels, isn't merged for the knockout), and adjustment layers, layer effects, vector masks and the other knockouts (top-level layers, clipped layers, layers that others are clipped to, pass-through groups with layers in other modes, other Knockout values, and merges that need more memory than allowed) aren't applied and are counted in the warnings. 8-, 16- and 32-bit files, PSB, raw, PackBits and zipped channels (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`). - File › Open of a PSD or PSB file with two or more layers, and File › Place of one without Link, show PSD Import Options: Convert Layers to Objects with Import Hidden Layers, or Flatten Layers to a Single Image, the options [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded. A file placed with Link shows its flat image and isn't asked about. `file.place` takes `layers` and `hiddenLayers`, and `document.psdInfo` counts a file's layers without opening it. VectorCraft's own rules: placed layers come in as one group named after the file, a layer as an image and a layer group as a group, at the place the merged image would take and clipped to the canvas when layers reach past it; the dialog asks from two layers up and starts from the choices made last. Layer comps aren't read (`crates/engine/src/cmd/fileio/tests_psdlayers.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). - A PSD or PSB file's clipping path, the saved path that image resource 2999 names in the [PSD file format specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), clips its merged image on File › Place and on File › Open of the merged image, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file imported as one flattened image. The image comes in a clip group whose clipping path has no paint and uses the even-odd rule, and the path can be edited or released. `links.update` and `links.relink` give the clip group the clipping path the new file names, or leave a plain group when it names none, and files that name no clipping path come in as before. `links.unembed` keeps the clip group, and the PNG or TIFF it writes is read with the path on File › Open, File › Place, `links.relink` and `links.update` (`crates/engine/src/cmd/fileio/tests_psdread.rs`). - Import Slices: File › Open of a PSD or PSB file with slices, and File › Place of one without Link, bring its slices in as user slices, as [PSD import options](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/photoshop-import-options.html) describes for a file that is opened or embedded; PSD Import Options offers Import Slices for such a file. `document.open` and `file.place` take `importSlices`, and `document.psdInfo` counts the slices. The slices are read from image resource 1050 in version 6 and in the descriptor of versions 7 and 8, as the [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/) describes it. VectorCraft's own rules: Import Slices applies to Convert Layers to Objects and to Flatten Layers to a Single Image alike, and makes the dialog ask for a file with fewer than two layers; placed slices move and scale with the art in the same undo step; each slice keeps its name, type, link, target, message, alternative text, cell text and background color; slices the file generated automatically, and slices wholly outside the canvas, are left out; slices that can't be read are left out with a warning while the art comes in; with Show Import Options off, a PSD file is placed with the PSD Import Options chosen last, and on, each PSD file of the place cursor asks for them (`crates/engine/src/cmd/fileio/tests_psdslices.rs`, `crates/ui-egui/src/dialogs/psd_import.rs`). @@ -2276,6 +2304,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - EMF and WMF type takes its size from the font's height, where a negative height is the em and a positive height is the character cell, and a font's average character width becomes Horizontal Scale against the face's own average width (OS/2 `xAvgCharWidth`) when the face gives one, as [LOGFONT](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-logfontw) and [MS-EMF 2.2.13](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-emf/1cd7cb7a-1a7c-48d2-b4a4-c218f9d12100) describe the two fields. VectorCraft's own rules are that the cell is the face's `usWinAscent` plus `usWinDescent` at a variable font's instance (its ascent plus descent without an OS/2 table), that a negative width is read as its absolute value, and that the width is ignored when the height is 0 (`a_font_width_becomes_horizontal_scale`, `a_positive_font_height_is_the_character_cell`, `a_font_the_system_lacks_is_measured_in_the_face_that_draws_it`, `wmf_font_width_becomes_horizontal_scale`). - EMF and WMF files are read by the shared `craft-metafile` reader and open, place and paste as editable paths, clipping groups, images and point type: an EMF drawn with EMF+ records (on their own, or beside plain records) is read from them instead of opening empty, and hatched and pattern brushes fill with their average color (`crates/metafile/src/tests/import.rs`). - EMF, WMF and EMF+ text keeps the character advances the file gives (ExtTextOut's `lpDx`, DrawDriverString positions) as tracking, with pair kerning off; on a single left to right line, an advance that tracking can't give (wider than its range, or a tab) starts a new point type object where the advance puts it, with an underline or strikethrough filled across the space between and on to the end of the last character's advance; type on more than one line is placed a line at a time, each line aligned by its own advances and split as a single line is (`text_is_spaced_by_its_advances`, `multiline_text_with_advances_aligns_each_line`, `wmf_text_is_spaced_by_its_advances`, `emf_plus_driver_strings_keep_their_positions`, `split_type_keeps_its_underline_and_right_to_left_order`). + - EMF and WMF text drawn in the opaque background mode, which a playback starts in ([MS-EMF 2.1.4 BackgroundMode](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-emf/2f57054c-2b69-4303-a6f8-5aacd401f759), [SetBkMode](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/nf-wingdi-setbkmode)), gets one rectangle of the background color behind each line's character cells, placed before the type; transparent text gets none. A character cell runs from the font's OS/2 `usWinAscent` above the baseline to its `usWinDescent` below it, and top or bottom aligned text puts the top or the bottom of the cell at the reference point (`opaque_backgrounds_fill_behind_the_character_cells`, `opaque_backgrounds_reach_as_far_as_the_advances`, `wmf_text_fills_its_cells_in_the_opaque_background_mode`). - EMF and WMF import warns about what the reader leaves out or does not play as the file asks: a file, or a metafile image inside it, cut short by one of the reader's limits (items, bytes kept, saved states, clip paths), with one warning without a count, and, with counts, images and pattern brushes that are not read, clips that are not applied, and raster operations other than a plain copy (`a_file_cut_short_by_another_limit_says_so`, `images_the_reader_does_not_read_are_counted`, `clips_that_are_not_applied_are_counted`, `raster_operations_that_are_not_played_are_counted`, `a_wmf_reports_unread_pattern_brushes_and_raster_operations`). - Export As › HP-GL (`document.export {format: "hpgl"}`) writes a `.plt` plot of an artboard, each artboard or the art for pen plotters and cutters: each visible path once along its line in plotter units from the artboard's bottom-left corner or center, a pen per color or a pen table, curves flattened to a tolerance, type as outlines, clipping masks and the artboard's edges applied, and HP-GL or HP-GL/2 (pen colors and encoded polylines); plots read back by the HP-GL reader give the same lines (`crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). - HP-GL export's `insideFirst` cuts each pen's paths inside before outside: a path is drawn only after the pen's paths that lie inside it (a letter's counter, a part's holes, rings within rings), touching outlines counted as inside and crossing ones not, in paint order or nearest first with `sortPaths`, within the plot's work budget; these order rules are VectorCraft's own (`crates/cad/src/hpgl/write/nest.rs`, `crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`). @@ -2364,6 +2393,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Missing linked files can be looked for in a folder and its subfolders: Find in Folder… in the Linked File Not Found dialog and in the Links panel menu lists the files with each one's name, those with the size and contents saved with the link first, and relinks the files chosen, copying an image's file into the document's folder when asked, without replacing a file there (`links.findFiles`, `links.relink {copy}`). In the Links panel it looks for the selected linked files when any are selected. - The Links panel's Relink… opens a Relink dialog whose Replace menu picks which links take the new file: Selected Instances (the selected images, as before), All Instances (every image linked to the same file), Missing Links from This Folder (then every other missing link whose file name is in the new file's folder) and Each Link Separately (a file for each selected link in turn). Each relinks as one undo step (`links.relink {scope}`, `ui.relinkDialog`). Relink to Folder… stays as it is. - The Links panel menu's Copy Info ([Links panel](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-from-other-apps/links-panel-in-illustrator.html)) copies the selected link's file name to the clipboard (`links.copyInfo`). VectorCraft's own rules: with several rows selected it copies one name per line in the order the panel shows them, an embedded image gives the name its row shows, and the item is off with no row selected. + - With one image selected, the Control bar's object label, Linked File or Embedded, is an underlined link, and a click on it opens the Links panel wherever it is docked, scrolls the list to the image's row, which shows selected, and shows the image's details in Link Info. The help page () describes clicking this label for a selected linked object as a way to open the Links panel. VectorCraft's own rules: the Embedded label opens the panel too, the click opens Link Info when it was closed and scrolls the list to the row, and a Show filter that leaves out the image's row goes back to Show All; the panel's sort, thumbnail size and other options stay as they were (`the_linked_file_and_embedded_labels_open_the_links_panel`, `opening_the_panel_on_the_selected_image_shows_its_row_and_link_info`, `opening_the_panel_on_the_selected_image_scrolls_to_its_row`). - The Links panel menu's Unembed… works on several selected embedded images at once and writes them all to one chosen folder ([Embed and unembed images and files](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/manage-linked-and-embedded-files/embed-images-and-files.html)): it asks for a folder once, writes a file for each image there and links each image to its file in one undo step (`links.unembed {ids, folder}`). VectorCraft's own rules: each file keeps the format its image is stored in (or PNG when that format is not one of VectorCraft's raster file formats) and is named after the image, a taken name gets a number (`Name 2`) and a file already in the folder is never replaced, linked rows in the selection are left as they are, and when one image can't be written the files already written are removed and nothing is unembedded. On the web each image is downloaded instead. Evidence: `unembed_to_a_folder_writes_each_image_and_links_it_in_one_undo_step`, `unembed_to_a_folder_that_fails_leaves_no_file_and_no_change`, `unembed_writes_several_images_to_one_picked_folder`. - Linked files inside symbols, graph designs, patterns and opacity masks are saved with their paths relative to the document, as linked files in the layers are, so they are found after the document and its files move to another folder together; on open each of those links takes the path where its file was found. Update Links, and opening with Update Links: Automatically, read a modified file again for that art too, and saving a document refreshes its placed copies inside symbols and patterns of the other open documents. Evidence: `links_outside_the_layers_find_their_files_after_the_folder_moves`, `update_links_reads_files_again_inside_symbols_patterns_and_masks`, `saving_a_document_refreshes_its_placed_copies_inside_symbols_and_patterns`. - A linked file that is missing when a moved document is saved keeps the folder its relative path names, instead of a relative path worked out from the out-of-date absolute path, also for a `.ai` file another app wrote (such as `src/`), so the file is found once it is back in that folder. Evidence: `a_missing_link_keeps_its_relative_path_when_the_moved_document_is_saved`, `links_of_an_imported_file_are_found_by_their_relative_folder`, `a_missing_link_of_a_moved_document_keeps_its_relative_place`. @@ -2457,6 +2487,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When the Layers or Links panel shows another document's rows, the thumbnail thread drops the row thumbnails it has not started for the documents not shown, and it drops all of them when the Layers or Links panel is open after the last document closes. Those rows ask for their thumbnails again when their document shows again, and the thumbnails already made are kept. With 150 rows of 20,000-anchor paths waiting for another document, the 8 rows of such paths of the document shown get their thumbnails in 153 ms instead of 3,265 ms (debug test build, median of three runs). The Links panel keeps its `links.list` rows and Link Info in one shared cache, and a frame that fetches nothing new reads that cache without copying the rows. The cache is replaced when the document or its revision changes, the Show, Sort or Show DCS Transparency Interactions option changes, or the files are looked at again every 2 seconds, and, while an image is selected, when Link Info opens or closes or the first selected image changes. With 2,001 images a frame's cache step takes 0.2 µs instead of 1.79 ms, and with 10,001 images 0.2 µs instead of 12.2 ms (test build, median of 7 wall-clock runs of 1,000 frames, measured while other builds were running). In the web build, while a pan, zoom or rotation changes the view of a document whose last canvas render took more than 8 ms, the canvas draws the last frame moved with the view, and it renders the art again once the view has been still for 0.2 s. + In the web build, an edit while that view moves (a tool drag held near an edge of the canvas, which scrolls the view, or a wheel scroll during a drag) draws only the part of the last frame that the edit changed, at the view that frame was rendered for, and the frame stays drawn moved with the view until the view has been still for 0.2 s (#8688). The part of the canvas a pan uncovers shows the pasteboard and the artboards' paper until then, as for a pan without an edit. Edits that go on after the view stops don't start that 0.2 s again: the whole canvas renders 0.2 s after the view stopped. An edit that changes more than half of the frame, or one while more than the view and the document change, renders the whole canvas at once as before. Tests: `canvas::tests::without_a_worker_a_heavy_canvas_is_reprojected_until_the_view_is_still`, `canvas::tests::without_a_worker_edits_while_the_view_is_still_do_not_hold_off_the_render`. An Alt-drag with the Selection, Direct Selection, Group Selection, Rotate, Scale, Reflect or Shear tool copies the selection on its first move, and the moves after it transform those copies; the previews of the Move, Rotate, Scale, Reflect and Shear dialogs with Copy and Preview on copy the selection once in the same way (#1429). An Alt-drag of objects in perspective with the Perspective Selection tool, and an Alt-drag of a plane widget with that tool or the Perspective Grid tool, copy the objects on the first move, and the moves after it move those copies (#1429). With the Perspective Selection tool, Ctrl+Alt-drag (Command+Option-drag on macOS) also copies objects on their perspective plane; Alt/Option-drag continues to do so. @@ -3084,10 +3115,13 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 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. | | 2026-11-18 | minor | Layers panel: context menu on guide rows (Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show) with one-step undo; regression tests in `crates/ui-egui/src/panels/layers/tests.rs`; scores and estimates unchanged. | | 2026-11-18 | minor | Type advanced: Retype phase 1 (`type.retype`, #4934), exact matches of available fonts become point text again; evidence added; near matches, the ranked font list and images remain; score and hours unchanged | | 2026-11-18 | 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. | | 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. | +| 2026-11-17 | minor | Image Trace Ignore Color: sample original source pixels without changing the canvas View; outside and transparent misses keep the pick armed, while valid picks and cancellation retain the existing tool and Preview behavior (#8068). Scores, gaps and hours unchanged. | | 2026-11-16 | minor | Layers panel: an Alt-drag copies a row above or below its own place (`layer.move` with `copy` and that row as the target), so the top layer dragged up, the bottom layer dragged down and a document's only layer are copied (#8237). Scores and estimates unchanged. | | 2026-11-17 | minor | Brush Options Key Color (#8284): restore canvas input for its existing eyedropper, then resume the retained draft and previous tool; OK/Cancel and Escape remain separate actions. Six full-app input regressions passed; scores and estimates unchanged. | | 2026-11-16 | minor | Layers panel: rows or the selected-art square dragged over the list show the copy cursor while Alt is held, as the drop then copies, and the grabbing hand otherwise (#8217). Scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 6fb7985935..3822702956 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 (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-19 · **Change:** minor (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). > @@ -253,7 +253,7 @@ tools, never checked side by side) isn't captured row by row. | Drag a curved segment to bend it, a straight one to move its anchors | done | | | Drag by an anchor of a path selected whole moves the whole path; Alt-drag by an anchor or a segment copies it, Alt toggles the copy during the drag, and the copy snaps by the anchor pressed, onto the original too | done | #1104 | | Handles shown are the handles that drag; tolerance from Selection & Anchor Display | done | #494 | -| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), Space (ordinary paths: move its anchor and both handles) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); Space pressed during an ordinary path's handle drag moves its owning anchor and both handles; releasing Space while keeping the mouse down resumes handle adjustment. This also applies while Cmd/Ctrl lends Direct Selection to the Pen, which then continues the same path (#7237, request 3 only) | +| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), Control/Command added mid-drag (mirror the opposite handle), Space (ordinary paths: move its anchor and both handles) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); #7842: temporary mirroring covers paths, transformed type on a path and blend spines, preserves the anchor mode and the pre-press selection-tool loan, and keeps Alt independent priority; the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again; `crates/engine/tests/direct_handle_mirror.rs`; Space pressed during an ordinary path's handle drag moves its owning anchor and both handles; releasing Space while keeping the mouse down resumes handle adjustment. This also applies while Cmd/Ctrl lends Direct Selection to the Pen, which then continues the same path (#7237, request 3 only) | | Show handles when multiple anchors are selected; Highlight anchors on mouse over; anchor and handle size | done | Preferences › Selection & Anchor Display | | Convert selected anchors to corner/smooth from the Control bar and Properties | done | | | Cut path at selected anchors, Remove Anchor Points, Delete removes segments | done | Open-path anchor Delete removes adjoining segments without bridging the gap; #3380 (deletion only): disconnected survivors of an ordinary contour become independent selected sibling objects, while multi-subpath paths and compound members stay intact; targeted core and full-frame Delete/Backspace regressions pass for survivor selection and Undo/Redo. Explicit Remove Anchor Points keeps its reconnect/refit behavior; #1278: segment Delete preserves neighboring edges and endpoint anchors; a second Delete removes all selected surviving objects; explicit anchor Delete retains its behavior; #1674: Delete removes every selected anchor of a closed path and objects selected whole along with them, and keeps the surviving objects selected; #2241: Remove Anchor Points then selects the next anchor along the path (the one before at an open end), so it can be run again without picking each anchor | @@ -349,6 +349,7 @@ tools, never checked side by side) isn't captured row by row. | Sliders in dialogs and popups (Save for Web, raster export options, Preferences, the opacity popup) show their rail, filled up to the handle | done | #1483 | | Rectangular Grid and Polar Grid click dialogs: size, divider counts with a skew slider each, Use Outside Rectangle As Frame / Create Compound Path From Ellipses, Fill Grid; kept as the tool's options, used by drags too | done | #1377. The options are the documented ones; how far a skew percentage moves the dividers and which way the radial skew turns are our own choice (the public documentation gives neither). The reference point locator is in the dialog, and a double-click on the tool opens it as the tool's Tool Options (next row) | | Double-click the Line Segment, Arc, Rectangular Grid or Polar Grid tool: its Tool Options ([Rectangular Grid tool](https://helpx.adobe.com/illustrator/using/tool-techniques/rectangular-grid-tool.html) and [Arc tool](https://helpx.adobe.com/illustrator/using/tool-techniques/arc-tool.html) step 3, [Tools](https://helpx.adobe.com/illustrator/using/tools.html)) | done | #2691. The tool's click dialog without a place to draw: Line Segment's Length, Angle and Fill Line; Arc's lengths, Reference Point, Type, Base Along, Slope and Fill Arc; the grids' Reference Point, Default Size, dividers, skews and switches. OK draws nothing and sets what the next drag draws with (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and what a click's dialog opens at (with the Length, Angle and Default Size); Cancel changes nothing (`double_clicking_the_line_arc_and_grid_tools_opens_their_tool_options`) | +| Three-Point Arc tool (VectorCraft addition), after the Arc tool: two ends, then a third point the open arc passes through or, with Third Point Sets Direction (its Tool Options, or `]` while drawing), the direction it leaves an end in; a preview with the center and, with Measurement Labels on, the radius; one undo step | done | `shape.threePointArc` (`crates/engine/src/cmd/create.rs`), the tool in `crates/tools/src/three_point_arc.rs`, the geometry in `crates/geom/src/shapes.rs` (`CircularArc`), and their tests; a VectorCraft addition, so it is not scored | ## Modifier keys and temporary tools @@ -366,6 +367,7 @@ tools, never checked side by side) isn't captured row by row. | Double-click a stroked segment to create a width point in Width Point Edit | done | Finite-arithmetic follow-up: engine regressions and full CI passed; [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area). Command and pointer regressions cover opening, sampled widths, adjoining adjustment on/off through checkbox/OK, compound paths, Cancel/Delete and Undo/Redo; dialog layout reviewed. [Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area) | | Shift-double-click a width point enables adjoining adjustment in Width Point Edit | done | Tool dispatch, plain double-click control, neighboring widths, Undo/Redo and Cancel in `dialogs/width_point.rs` | | Alt-drag duplicates (objects, artboards with their art) | done | | +| Artboard tool: Shift held once a move or an Alt-drag copy is under way keeps it to the level, upright or 45° line from General › Constrain Angle, as a Selection tool move does; a Shift-press still draws an artboard inside another or marquee-selects (#2497) | done | #8580; no public page describes Shift held during an artboard move, so it follows the request in #8580. Smart Guides, the grid and whole pixels slide the move along its line; the cursor stays the move cursor. `xform/artboard/tests.rs` `shift_held_during_a_move_keeps_it_to_its_line`, `shift_keeps_an_alt_drag_copy_to_its_line_from_the_constrain_angle`, `snaps_keep_a_shift_move_on_its_line`, `shift_during_a_move_keeps_the_move_cursor` | | Artboard tool: the canvas right-click menu has Lock Artboards (Lock Selected, Lock All Except Selected, Lock All) and Unlock Artboards (Unlock Selected, Unlock All) | done | #2531; `artboard.setProps` with `locked` for each artboard named; the lock itself is #2592 | | Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool | done | Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. | | Escape leaves Artboard editing for Selection; during a drag it first cancels the gesture | done | Headless egui key events cover idle Escape, active-drag cancellation and a subsequent Escape in `tests/distortkeys.rs`. | @@ -462,6 +464,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Window › Toolbars › Manage Toolbars… (also in the All Tools drawer's menu): the dialog lists the toolbars made with New Toolbar; a new name typed for the selected one renames it, + copies it (none selected: a blank toolbar) and the trash can deletes it; the changes stay in the workspace | done | #1759 in part; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete` | | Quick Image Trace presets trace at once and leave the panel as it was; the Image Trace button (Control bar, Properties) opens the editable controls | done | Per the public documentation, choosing a preset traces the image with it straight away, and the panel is opened with the Image Trace button in the Control panel or in Properties' Image Trace section (). The controls show Threshold, Paths, Corners and Noise with Advanced open; `panels/image_trace.rs` headless tests (`a_quick_trace_leaves_the_panel_as_it_was`, `sketch_quick_trace_reveals_all_adjustments_and_keeps_the_source` for the button's route). No algorithm parity claim. | | Image Trace panel: holding the eye button next to View down shows the selected Image Trace objects' source image on the canvas | done | Per the public documentation, the control next to View is pressed and held to compare the trace result with the source image (). On release the objects show their View again; the document, its View and the undo history are unchanged. `RenderOptions::trace_source`; `panels/image_trace.rs` headless test `holding_the_eye_button_shows_the_source_image_until_released`, render test `trace_source_draws_the_source_image_of_the_listed_objects`. The Control bar and Properties have no such button | +| Image Trace panel: Ignore Color has a canvas eyedropper beside its color picker | done | #8068. Samples original pixels of the selected placed image or the retained source of a live trace without changing the displayed canvas View. The existing color picker remains available. Preview off keeps a draft; Preview on retraces a live trace as one undo step. An outside or transparent miss leaves the pick armed; a valid sample or Escape restores the previous tool, and changing the target or explicitly choosing a tool cancels. Paint defaults and selection are retained. `tests/image_trace_ignore_sampler.rs`; no algorithm parity claim. | | Live trace result bounds and selection highlights exclude the retained bitmap; source-image views retain it | done | All TraceView modes and rotated result bounds regression-covered; ordinary hidden group behavior retained | | Image Trace panel: the Preview checkbox before Trace chooses whether a setting change traces the selected Image Trace object again at once | done | Per the public documentation, Preview shows the result of the current settings and Trace traces with them (). Preview is on by default and kept with the UI preferences; Reset to Default leaves it. Off, changes wait in the panel until Trace applies them as one undo step, or until Preview is turned on again. Changes stay with the object they were made for while another object is selected, and come back when it is selected again. `imageTrace.preview {on?}`, `ui.set {imageTracePreview}`; `panels/image_trace.rs` headless tests (`with_preview_off_a_slider_change_waits_for_trace`, `turning_preview_on_traces_the_changes_that_waited`, `preview_turned_on_with_nothing_selected_traces_when_the_object_is_selected_again`, `settings_that_wait_stay_with_their_object`, `settings_that_wait_come_back_when_their_object_is_selected_again`, `settings_that_wait_are_dropped_when_their_object_changed_since`, `preview_is_kept_with_the_preferences_and_reset_to_default_leaves_it`) | | Toolbar without group labels by default, one or two columns; All Tools drawer by flyout group with shortcuts, its menu (Reset, Basic, Advanced) and Show section | done | #1751; a preference brings the labels back; `toolbar.show` sets the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls; Window > Toolbars > Compact Tools adds optional denser spacing for the main Tools panel while retaining the existing default (#7234) | @@ -490,7 +493,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Info panel follows the tool in use: W and H show the change in x and y, with the distance and the angle, while the selection moves, the Gradient tool draws a vector or a Pen drag pulls out an anchor's handle; the Scale tool's percentages; the center and angles of a Rotate, Reflect or Shear tool drag; the Zoom tool's magnification; the Paintbrush's brush. W and H follow Use Preview Bounds, several selected objects show only the paint and type they share, and Show Options names a tint or a gradient swatch | done | `info.readout`; `Tool::readout`; behavior from the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76); number formats, the rows shown between drags and the Direct Selection and Group Selection readouts are VectorCraft's own | | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | -| Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Arrows, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; thirteen built-in libraries (original, generated in code) | +| Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Engraving, Arrows, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; fourteen built-in libraries (original, generated in code) | | Brushes panel menu › Options of Selected Object…: changes the selected brushed paths' brush settings on those paths only, leaving the brush and its other strokes as they are; the brush type's options dialog opens without the Name row (and without an art brush's scale and direction options or a pattern brush's tiles), and OK sends only the values changed in it | done | [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `brush.objectOptions`, `ui.brushObjectOptions`; which fields a path can set is VectorCraft's own choice (calligraphic, scatter, art and pattern brushes; not bristle); `options_of_selected_object_*` tests in `crates/engine/src/tests/brushsym.rs` and `crates/ui-egui/src/dialogs/brush_options/tests.rs`, brush tests in `crates/brush/src/tests.rs` | | Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938); Align to Pixel Grid (`alignToPixelGrid` on `symbol.new` / `symbol.options`: the art snaps at the symbol's natural size and instances at that size stay on whole points; [Aligning symbols to pixel grid](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28)) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its solid fill or stroke, is on canvas; on-canvas editing beyond a solid fill and stroke, and `.ai` read and write, remain | @@ -503,6 +506,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Canvas context menu | done | Right-clicking type opens the canvas menu, with Bullets and Numbering and Spelling. Right-clicking a path offers Object › Path › Simplify… and Smooth…, each opening what its menu item opens (#8344). Artboard rows, library groups and items, the rulers and floating toolbar grips have menus too. Gaps: other panels have none | | Layers panel row context menu | done | Right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export; right-clicking a ruler guide row shows Hide/Show, Lock/Unlock, Release Guides, Delete and Locate Object; right-clicking a blend spine row shows Select, Blend Options…, Reverse Spine, Reverse Front to Back, Expand, Release and Locate Object (#8592). | | Swatches item context menu (G12) | done | List and thumbnail items offer Swatch Options…, Duplicate Swatch and Delete Swatch for the clicked item. Right-click selects without applying paint; reserved/missing items disable actions. All 39 Swatches tests pass, including all five views and Undo; the regression fails with the menu hooks removed. Rendered headless menus inspected. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. | +| Links panel row context menu (G12) | done | Right-clicking a link row presents an item context menu offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, and Embed Image / Unembed…; right-clicking an unselected row selects it first, preserving selection if already part of a multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`. | | SVG Interactivity panel: JavaScript for each object's events and the document's linked JavaScript files, written to SVG and read back as text | done | `svgInteractivity.*`, `ui.javascriptFilesDialog` | | Retype panel | partial | Window › Retype lists the fonts whose glyphs exactly match at least one selected outlined shape, ranked by how many shapes each matches, ten and then five more, with samples in three sizes and the user's own text; a click sets the font on selected live type (`retype.find`, `type.retypeFonts`). Opening it from the Type menu, the context menu and the Properties panel, filtering by font source and favorites, near matches, installed fonts not yet loaded and text in images are missing (#4934) | | Comments, Version History panels | missing | cloud features (out of scope) | @@ -617,11 +621,14 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 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. | | 2026-11-19 | minor | G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s (part of #5930, `file.cancelPlace`); indeterminate moving bar, Cancel (Esc) leaves the document unmodified without undo steps; scores and estimates unchanged. | | 2026-11-18 | 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. | | 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. | | 2026-11-17 | minor | Brush Options Key Color (#8284): restore canvas input for its existing eyedropper, then resume the retained draft and previous tool; OK/Cancel and Escape remain separate actions. Six full-app input regressions passed; scores and estimates unchanged. | +| 2026-11-17 | minor | Image Trace Ignore Color: sample original source pixels without changing the canvas View; outside and transparent misses keep the pick armed, while valid picks and cancellation retain the existing tool and Preview behavior (#8068). Scores, gaps and hours unchanged. | +| 2026-11-16 | minor | Image Trace: Ignore Color samples original image pixels with a canvas eyedropper, retaining the manual picker, Preview drafts, source View and Undo behavior (#8068). Scores and estimates unchanged. | | 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | | 2026-11-16 | minor | Recolor Artwork › Assign: native Lab entry in the Color Picker, swatch libraries access in the picker, and row context menu options (Pick from Swatches, Limit to Library) (#4028). Scores and estimates unchanged. | | 2026-11-16 | minor | Eraser review (#6582): hidden Rasterize rows and hidden strokes with gradients along or across their paths do not block preserving visible fitted gradients. Visible unsupported paint branches retain existing fitting. Scores and estimates unchanged. | diff --git a/xtask/src/pdf_deps.rs b/xtask/src/pdf_deps.rs index e0877302a9..0b9653830a 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 = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b"; +const REV: &str = "50b0ee7bf811e363b5f238382b5c77318cf33e46"; const PACKAGES: &[(&str, &str, &str)] = &[ ("craft-pdf", "0.1.0", REV), ("krilla", "0.8.2", REV),