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/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/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/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/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs
index bfaece3d77..2f169dc3b1 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;
@@ -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")]
@@ -1392,6 +1430,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 +1441,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 +1449,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/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/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/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/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..1e9ef6d699 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`]).
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..c93239442d 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,
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 815a33eeae..0b785456a2 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -208,6 +208,7 @@ 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..424e5678bb 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]
diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs
index 660b24d6f6..de28e1d01e 100644
--- a/crates/engine/src/tests/colormgmt.rs
+++ b/crates/engine/src/tests/colormgmt.rs
@@ -682,6 +682,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/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/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/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/tooling.rs b/crates/engine/src/tooling.rs
index 5f36c5a98e..7d86dcc67f 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))
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/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/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/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..01da0fa29f 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…",
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..4f4ac487e2 100644
--- a/crates/tools/src/settings.rs
+++ b/crates/tools/src/settings.rs
@@ -48,6 +48,7 @@ const ROWS: &[Row] = &[
(&["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/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/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/canvas.rs b/crates/ui-egui/src/canvas.rs
index e4d21df36f..128134425e 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};
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/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