diff --git a/ASSETS.md b/ASSETS.md
index 0e4e4aa4fe..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 |
@@ -221,6 +222,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-polygon.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-pucker.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-puppet.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
+| `assets/icons/dc-quick-pen.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a line and a half circle with a dot at each point) | MIT OR Apache-2.0 | |
| `assets/icons/dc-rearrange.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-rect-cut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-rect-grid.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
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 4d8f84de90..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.
@@ -145,6 +146,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
+- 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged.
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
@@ -161,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/assets/icons/dc-quick-pen.svg b/assets/icons/dc-quick-pen.svg
new file mode 100644
index 0000000000..e87a486046
--- /dev/null
+++ b/assets/icons/dc-quick-pen.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/appearance/layers.rs b/crates/doc/src/appearance/layers.rs
index 1728b7e323..11d2b0664d 100644
--- a/crates/doc/src/appearance/layers.rs
+++ b/crates/doc/src/appearance/layers.rs
@@ -195,12 +195,14 @@ impl StrokeLayer {
wheel: None,
}
}
+ /// The least weight an arrowhead is drawn at, in points ([`Self::arrow_weight`]).
+ pub const LEAST_ARROW_WEIGHT: f64 = 0.25;
/// Weight of the start (`end == false`) or end arrowhead: stroke weight × its scale, at least
- /// a quarter point. A head of weight `hw` fits a box about `4·hw` long and wide (see
+ /// [`Self::LEAST_ARROW_WEIGHT`]. A head of weight `hw` fits a box about `4·hw` long and wide (see
/// [`Arrowhead::reach`] and [`Arrowhead::half_width`]).
pub fn arrow_weight(&self, end: bool) -> f64 {
let pct = if end { self.arrow_scale.1 } else { self.arrow_scale.0 };
- (self.width * pct / 100.0).max(0.25)
+ (self.width * pct / 100.0).max(Self::LEAST_ARROW_WEIGHT)
}
/// How far the start (`end == false`) or end arrowhead can reach from its end point (0
/// without one): the head's diagonal, or with [`ArrowAlign::Extend`] its length, plus the cap.
diff --git a/crates/doc/src/appearance/stroke_style.rs b/crates/doc/src/appearance/stroke_style.rs
index 18b226c676..7a39d6cbb2 100644
--- a/crates/doc/src/appearance/stroke_style.rs
+++ b/crates/doc/src/appearance/stroke_style.rs
@@ -68,6 +68,10 @@ pub struct CustomArrowhead {
/// across it, positive to the right of the direction the head points. A head is 4 units wide,
/// as the built-in heads are, and a unit is the head's weight.
pub path: PathData,
+ /// Where the stroke ends under the head, in head units back from the tip, when the head says
+ /// so ([`Self::with_stop`]); `None`: halfway along its length ([`Self::stop`]).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub stop: Option,
}
#[derive(Deserialize)]
@@ -75,11 +79,17 @@ struct CustomArrowheadData {
name: String,
#[serde(default)]
path: PathData,
+ #[serde(default)]
+ stop: Option,
}
impl From for CustomArrowhead {
fn from(d: CustomArrowheadData) -> Self {
- CustomArrowhead::new(d.name, d.path)
+ let head = CustomArrowhead::new(d.name, d.path);
+ match d.stop {
+ Some(stop) => head.with_stop(stop),
+ None => head,
+ }
}
}
@@ -94,7 +104,17 @@ impl CustomArrowhead {
/// than [`Self::MAX_UNITS`] from the tip is dropped: the head then draws nothing.
pub fn new(name: String, path: PathData) -> Self {
let path = if Self::fits(&path) { path } else { PathData::default() };
- CustomArrowhead { name, path }
+ CustomArrowhead { name, path, stop: None }
+ }
+ /// The head with the stroke ending `stop` head units back from its tip (an arrowhead an
+ /// Illustrator file defines draws its line to a point of its own). A stop that is not finite,
+ /// is negative or is farther than [`Self::MAX_UNITS`] is left out: the stroke then ends
+ /// halfway along the head.
+ /// A head whose outline was dropped ([`Self::new`]) draws nothing and keeps no stop.
+ pub fn with_stop(mut self, stop: f64) -> Self {
+ let fits = !self.path.subpaths.is_empty() && stop.is_finite() && (0.0..=Self::MAX_UNITS).contains(&stop);
+ self.stop = fits.then_some(stop);
+ self
}
/// Whether outline `path` has at most [`Self::MAX_ANCHORS`] anchors and as many subpaths, with
/// finite points within [`Self::MAX_UNITS`] only.
@@ -116,10 +136,10 @@ impl CustomArrowhead {
pub fn half_width(&self) -> f64 {
self.bounds().map_or(0.0, |b| b.y0.abs().max(b.y1.abs()))
}
- /// Where the stroke ends under the head, in head units back from the tip: halfway along the
- /// head's length.
+ /// Where the stroke ends under the head, in head units back from the tip: its own stop
+ /// ([`Self::with_stop`]), else halfway along the head's length.
pub fn stop(&self) -> f64 {
- self.bounds().map_or(0.0, |b| b.x1.max(0.0) / 2.0)
+ self.stop.unwrap_or_else(|| self.bounds().map_or(0.0, |b| b.x1.max(0.0) / 2.0))
}
}
diff --git a/crates/doc/src/appearance/tests.rs b/crates/doc/src/appearance/tests.rs
index caad4f6edc..ab0ba559f0 100644
--- a/crates/doc/src/appearance/tests.rs
+++ b/crates/doc/src/appearance/tests.rs
@@ -383,6 +383,15 @@ fn custom_arrowheads_carry_their_art_and_measure_it() {
assert_eq!(head.half_width(), 2.0);
let Arrowhead::Custom(c) = &head else { panic!("custom") };
assert_eq!(c.stop(), 1.5, "the line stops halfway along the head");
+ // A head with a stop of its own (an Illustrator file's arrowhead) keeps it, saved and read back.
+ let stopped = (**c).clone().with_stop(0.5);
+ assert_eq!(stopped.stop(), 0.5);
+ let back: CustomArrowhead = serde_json::from_value(serde_json::to_value(&stopped).unwrap()).unwrap();
+ assert_eq!(back, stopped);
+ assert!(!serde_json::to_string(&**c).unwrap().contains("stop"), "a head without one writes none");
+ for odd in [f64::NAN, -0.5, CustomArrowhead::MAX_UNITS + 1.0] {
+ assert_eq!((**c).clone().with_stop(odd).stop(), 1.5, "{odd} is left out");
+ }
// Saved with the stroke, art and all, beside the built-in heads' names.
let mut st = StrokeLayer::new(Paint::solid(Color::BLACK), 2.0);
(st.start_arrow, st.end_arrow) = (Some(Arrowhead::Triangle), Some(head.clone()));
@@ -404,7 +413,7 @@ fn custom_arrowheads_out_of_bounds_draw_nothing() {
let mut path = c.path.clone();
path.subpaths[0].anchors[1] = vectorcraft_geom::Anchor::corner(vectorcraft_geom::Point::new(1e9, 0.0));
// A file can hold what `new` drops: reading it drops it too.
- let json = serde_json::to_value(CustomArrowhead { name: "Wedge".into(), path }).unwrap();
+ let json = serde_json::to_value(CustomArrowhead { name: "Wedge".into(), path, stop: None }).unwrap();
let far: CustomArrowhead = serde_json::from_value(json).unwrap();
assert_eq!((far.name.as_str(), far.path.subpaths.len()), ("Wedge", 0));
assert_eq!((far.reach(), far.half_width(), far.stop()), (0.0, 0.0, 0.0));
@@ -415,7 +424,7 @@ fn custom_arrowheads_out_of_bounds_draw_nothing() {
let mut hollow = c.path.clone();
hollow.subpaths.extend(std::iter::repeat_n(vectorcraft_geom::SubPath::new(vec![], false), CustomArrowhead::MAX_ANCHORS));
assert!(!CustomArrowhead::fits(&hollow), "too many subpaths");
- let json = serde_json::to_value(CustomArrowhead { name: "Hollow".into(), path: hollow }).unwrap();
+ let json = serde_json::to_value(CustomArrowhead { name: "Hollow".into(), path: hollow, stop: None }).unwrap();
let hollow: CustomArrowhead = serde_json::from_value(json).unwrap();
assert!(hollow.path.subpaths.is_empty(), "too many subpaths, read back");
}
diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs
index 9e78d17d4d..4d66f5d74c 100644
--- a/crates/doc/src/dimension.rs
+++ b/crates/doc/src/dimension.rs
@@ -124,6 +124,54 @@ impl ArrowStyle {
}
}
+/// `arrowHead`: null, or a built-in stroke arrowhead by its name (`Barbed`, as `stroke.set` takes
+/// it). A custom arrowhead and an unknown name are refused.
+mod arrow_head {
+ use crate::Arrowhead;
+ use serde::de::{Error, IntoDeserializer, Visitor};
+ use serde::{Deserialize, Deserializer};
+
+ pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result, D::Error> {
+ deserializer.deserialize_option(Name)
+ }
+
+ /// Reads the name where it is, without a copy of its own.
+ struct Name;
+
+ impl<'de> Visitor<'de> for Name {
+ type Value = Option;
+
+ fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+ f.write_str("a built-in stroke arrowhead name or null")
+ }
+
+ fn visit_none(self) -> Result {
+ Ok(None)
+ }
+
+ fn visit_unit(self) -> Result {
+ Ok(None)
+ }
+
+ fn visit_some>(self, deserializer: D) -> Result {
+ deserializer.deserialize_str(self)
+ }
+
+ fn visit_str(self, name: &str) -> Result {
+ // No built-in name is this long, so a longer one is refused without parsing it.
+ let parsed: Result =
+ if name.len() > 64 { Err(serde::de::value::Error::custom("too long")) } else { Arrowhead::deserialize(name.into_deserializer()) };
+ match parsed {
+ Ok(head) if !matches!(head, Arrowhead::Custom(_)) => Ok(Some(head)),
+ _ => {
+ let shown: String = name.chars().take(64).collect();
+ Err(E::custom(format!("Unknown arrowhead {shown}: a built-in stroke arrowhead name or null")))
+ }
+ }
+ }
+ }
+}
+
/// Where the label sits across the dimension line.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
@@ -157,6 +205,12 @@ pub struct DimensionOptions {
pub line_type: LineType,
pub line_color: [u8; 3],
pub arrow_style: ArrowStyle,
+ /// A built-in stroke arrowhead drawn at both ends in place of `arrow_style`'s head. Versions
+ /// that have the stroke arrowhead but do not read this keep the saved arrows until they draw
+ /// the dimension again, and then draw `arrow_style`. Versions without the stroke arrowhead do
+ /// not open the file.
+ #[serde(deserialize_with = "arrow_head::deserialize", skip_serializing_if = "Option::is_none")]
+ pub arrow_head: Option,
pub arrow_scale: f64,
pub extension_weight: f64,
pub extension_type: LineType,
@@ -186,6 +240,7 @@ impl Default for DimensionOptions {
line_type: LineType::Solid,
line_color: [0, 0, 0],
arrow_style: ArrowStyle::Filled,
+ arrow_head: None,
arrow_scale: 100.0,
extension_weight: 0.5,
extension_type: LineType::Solid,
@@ -209,7 +264,8 @@ impl DimensionOptions {
/// tolerantly so a newer version's options don't stop a document opening.
pub fn from_params(v: serde_json::Value) -> Result {
if let (Some(given), Ok(serde_json::Value::Object(known))) = (v.as_object(), serde_json::to_value(Self::default()))
- && let Some(k) = given.keys().find(|k| !known.contains_key(*k))
+ // `arrowHead` is left out of the saved options when it is null.
+ && let Some(k) = given.keys().find(|k| !known.contains_key(*k) && k.as_str() != "arrowHead")
{
return Err(format!("Unknown dimension option {k}"));
}
@@ -228,8 +284,16 @@ impl DimensionOptions {
}
Ok(f)
}
+ /// The stroke arrowhead drawn at each end of the dimension line: `arrow_head`, or else the
+ /// arrow style's head.
+ pub fn arrowhead(&self) -> Option {
+ self.arrow_head.clone().or_else(|| self.arrow_style.arrowhead())
+ }
pub fn validate(&self) -> Result<(), String> {
self.factor()?;
+ if matches!(self.arrow_head, Some(crate::Arrowhead::Custom(_))) {
+ return Err("A dimension's arrowhead is a built-in stroke arrowhead".into());
+ }
if self.precision > 6 {
return Err("Choose a precision from 0 to 6".into());
}
diff --git a/crates/doc/src/node/live_shape.rs b/crates/doc/src/node/live_shape.rs
index a384836442..0a17301331 100644
--- a/crates/doc/src/node/live_shape.rs
+++ b/crates/doc/src/node/live_shape.rs
@@ -144,10 +144,36 @@ impl LiveShape {
/// from straight up (the Rotate field's sense). None for other shapes.
pub fn polygon_angle(&self) -> Option {
let LiveShape::Polygon { .. } = self else { return None };
- // No −0° or 360° from rounding: a polygon drawn upright reads 0°.
+ self.shape_angle()
+ }
+ /// A rectangle's, ellipse's or polygon's angle (Rectangle, Ellipse and Polygon Angle): the
+ /// counterclockwise degrees in [0, 360) it is turned by (the Rotate field's sense). A rectangle or
+ /// ellipse drawn level reads 0°, as does a polygon drawn with its first vertex straight up. None for
+ /// other shapes.
+ pub fn shape_angle(&self) -> Option {
+ let (LiveShape::Rectangle { .. } | LiveShape::Ellipse { .. } | LiveShape::Polygon { .. }) = self else { return None };
+ // No −0° or 360° from rounding: a shape drawn level reads 0°.
let a = (-self.angle_deg()).rem_euclid(360.0);
Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 })
}
+ /// Turn a rectangle, ellipse or polygon about its center to `angle` (degrees, as
+ /// [`LiveShape::shape_angle`]), keeping its size, corners and pie. Nothing changes for other
+ /// shapes or an angle that isn't finite.
+ pub fn set_shape_angle(&mut self, angle: f64) {
+ let Some(now) = self.shape_angle() else { return };
+ if !angle.is_finite() {
+ return;
+ }
+ // Brought into [0, 360) first: `now - angle` loses `now` for a very large angle.
+ let angle = angle.rem_euclid(360.0);
+ let (xf, local) = match self {
+ LiveShape::Rectangle { w, h, xf, .. } | LiveShape::Ellipse { w, h, xf, .. } => (xf, Point::new(*w / 2.0, *h / 2.0)),
+ LiveShape::Polygon { xf, .. } => (xf, Point::ZERO),
+ LiveShape::Line { .. } | LiveShape::Path { .. } => return,
+ };
+ let center = *xf * local;
+ *xf = Affine::rotate_about((now - angle).to_radians(), center) * *xf;
+ }
/// Whether a polygon's sides are all as long: `xf` scales it evenly and doesn't shear it. True
/// for other shapes.
pub fn polygon_sides_equal(&self) -> bool {
@@ -171,12 +197,8 @@ impl LiveShape {
}
/// Turn a polygon about its centre to `angle` (degrees, as [`LiveShape::polygon_angle`]).
pub fn set_polygon_angle(&mut self, angle: f64) {
- let Some(now) = self.polygon_angle() else { return };
- if let LiveShape::Polygon { xf, .. } = self
- && angle.is_finite()
- {
- let centre = *xf * Point::ZERO;
- *xf = Affine::rotate_about((now - angle).to_radians(), centre) * *xf;
+ if let LiveShape::Polygon { .. } = self {
+ self.set_shape_angle(angle);
}
}
/// A line's length in the document, from its first end to its second. None for other shapes.
diff --git a/crates/doc/src/node/tests.rs b/crates/doc/src/node/tests.rs
index 789e0f66b2..cdcbf2cf85 100644
--- a/crates/doc/src/node/tests.rs
+++ b/crates/doc/src/node/tests.rs
@@ -184,6 +184,20 @@ fn a_polygon_reports_and_takes_its_radius_angle_and_equal_sides() {
assert_eq!((e.polygon_radius(), e.polygon_angle()), (None, None));
}
+/// A very large angle turns a rectangle to that angle modulo 360, whatever angle it had before.
+#[test]
+fn a_shape_takes_a_very_large_angle() {
+ let close = |a: f64, b: f64| (a - b).abs() < 1e-6;
+ let want = 1e20f64.rem_euclid(360.0);
+ for turned in [0.0, 90.0] {
+ let xf = Affine::translate((50.0, 50.0)) * Affine::rotate(-f64::to_radians(turned));
+ let mut r = LiveShape::Rectangle { w: 100.0, h: 50.0, radii: [0.0; 4], kinds: Default::default(), radii_relative: false, xf };
+ assert!(close(r.shape_angle().unwrap(), turned), "{:?}", r.shape_angle());
+ r.set_shape_angle(1e20);
+ assert!(close(r.shape_angle().unwrap(), want), "from {turned}°: {:?}, not {want}", r.shape_angle());
+ }
+}
+
/// A node holding a live rectangle (`w` × `h`, all radii `r`, placed by `xf`) and its path.
fn live_rect(w: f64, h: f64, r: f64, xf: Affine) -> Node {
let live = LiveShape::Rectangle { w, h, radii: [r; 4], kinds: Default::default(), radii_relative: false, xf };
diff --git a/crates/effects/src/stroke/arrow.rs b/crates/effects/src/stroke/arrow.rs
index d188bcafd6..1047e4d0dd 100644
--- a/crates/effects/src/stroke/arrow.rs
+++ b/crates/effects/src/stroke/arrow.rs
@@ -5,7 +5,8 @@
//! corner. With [`ArrowAlign::Tip`] the tip sits on the end point and the stroke is shortened by
//! the inset; with [`ArrowAlign::Extend`] the path keeps its length and the tip sits the inset
//! past the end point. Heads added after the first ten are drawn in local units ([`local`]), as are
-//! custom heads, whose stroke ends halfway along their length.
+//! custom heads, whose stroke ends at their own stop or else halfway along their length
+//! ([`vectorcraft_doc::CustomArrowhead::stop`]).
use std::borrow::Cow;
diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs
index e2f6b7624f..9a1531ede9 100644
--- a/crates/engine/src/cmd.rs
+++ b/crates/engine/src/cmd.rs
@@ -907,7 +907,7 @@ pub use gradpresets::{GradientPreset, GradientPresetEntry};
pub use buildcmds::{TracePreset, TracePresetChange};
/// An Image Trace made off the UI thread, and what it traced (#3098).
-pub use buildcmds::{TraceRun, Traced};
+pub use buildcmds::{TraceRun, Traced, image_trace_target};
/// The saved Image Trace presets' revision and latest changes ([`crate::Session`] keeps them).
pub(crate) use buildcmds::TracePresetChanges;
diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs
index 1b14e25391..6d2c7fd18f 100644
--- a/crates/engine/src/cmd/appearance.rs
+++ b/crates/engine/src/cmd/appearance.rs
@@ -278,6 +278,28 @@ impl ItemTarget {
}
}
+ /// [`ItemTarget::targets`] of a fill (`fill`) or a stroke edit: on the topmost fill or stroke, a
+ /// Live Paint group stands for its faces in a fill edit and for its edges in a stroke edit
+ /// ([`super::paint::live_paint_parts_skipped`]).
+ pub(crate) fn targets_for(self, s: &Session, p: &Value, fill: bool) -> Result> {
+ Ok(self.targets_and_skipped(s, p, fill)?.0)
+ }
+
+ /// [`ItemTarget::targets_for`], and whether it left out any object inside a Live Paint group: a
+ /// group with no part of the edited kind was still given or selected, so the edit does not go
+ /// to new art.
+ pub(crate) fn targets_and_skipped(self, s: &Session, p: &Value, fill: bool) -> Result<(Vec, bool)> {
+ let mut ids = self.targets(s, p)?;
+ let mut skipped_any = false;
+ if self == ItemTarget::Top {
+ let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill);
+ let before = ids.len();
+ ids.retain(|id| !skipped.contains(id));
+ skipped_any = ids.len() != before;
+ }
+ Ok((ids, skipped_any))
+ }
+
/// The target of a fill (`fill`) or stroke edit: the panel's active item stands only for edits
/// of its own kind, so a fill row leaves stroke edits on the topmost stroke of the painted
/// leaves (as without an active item) and vice versa. Explicit items are kept (and checked).
diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs
index 2d31c5af6e..9866d7d9af 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,6 +183,7 @@ 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 },
];
@@ -237,6 +239,49 @@ fn art(name: &str, art: Node, colorization: Colorization) -> Brush {
Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) }
}
+/// 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 +595,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)]));
diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs
index 904e80df61..1e6739b6c7 100644
--- a/crates/engine/src/cmd/buildcmds.rs
+++ b/crates/engine/src/cmd/buildcmds.rs
@@ -42,7 +42,7 @@ pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, iso
use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge};
use shape_builder::{sb_merge, sb_regions};
pub(crate) use trace::TracePresetChanges;
-pub use trace::{TracePreset, TracePresetChange, TraceRun, Traced};
+pub use trace::{TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target};
use trace::{trace_expand, trace_make, trace_presets_delete, trace_presets_save, trace_release, trace_set_view};
/// Name of an Image Trace group.
diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs
index 90c505cfb6..f0f2557ded 100644
--- a/crates/engine/src/cmd/buildcmds/trace.rs
+++ b/crates/engine/src/cmd/buildcmds/trace.rs
@@ -606,6 +606,30 @@ struct Prepared {
library: Vec<([u8; 3], Paint)>,
}
+/// The object `imageTrace.make` would trace, without preparing settings or reading image bytes.
+pub fn image_trace_target(s: &Session, p: &Value) -> Result {
+ target_image(s, "imageTrace.make", p).map(|(target, _)| target)
+}
+
+fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box)> {
+ let roots = root_ids(s, p)?;
+ let d = &s.doc()?.doc;
+ roots
+ .iter()
+ .find_map(|r| {
+ let n = d.node(*r)?;
+ match &n.kind {
+ NodeKind::Image(i) => Some((*r, i.clone())),
+ _ if is_trace_group(n) => match &n.children()?.first()?.kind {
+ NodeKind::Image(i) => Some((*r, i.clone())),
+ _ => None,
+ },
+ _ => None,
+ }
+ })
+ .ok_or_else(|| bad(c, "select an image (or an Image Trace group)"))
+}
+
/// What command `c` with params `p` traces, and how, from the session: everything but the trace.
fn prepare(s: &Session, c: &str, p: &Value) -> Result {
let mut params = trace_params(s, c, p)?;
@@ -625,25 +649,7 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result {
None if is(tr::preset(named)) || is(tr::enhanced_preset(named)) => named.to_string(),
None => "Custom".to_string(),
};
- let roots = root_ids(s, p)?;
- // The image (inside a trace group, or selected directly).
- let (target, image) = {
- let d = &s.doc()?.doc;
- roots
- .iter()
- .find_map(|r| {
- let n = d.node(*r)?;
- match &n.kind {
- NodeKind::Image(i) => Some((*r, i.clone())),
- _ if is_trace_group(n) => match &n.children()?.first()?.kind {
- NodeKind::Image(i) => Some((*r, i.clone())),
- _ => None,
- },
- _ => None,
- }
- })
- .ok_or_else(|| bad(c, "select an image (or an Image Trace group)"))?
- };
+ let (target, image) = target_image(s, c, p)?;
if by_color && s.doc()?.doc.node(target).is_some_and(vectorcraft_render::effects::has_pathfinder) {
return Err(bad(c, LIVE_PATHFINDER_BY_COLOR));
}
diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs
index 0ac4f8c3b0..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")]
@@ -1003,7 +1041,7 @@ impl PasteProfile {
if o.keys().any(|k| k != "rgb" && k != "cmyk") {
return Err(refuse());
}
- let model = |m: &str| o.get(m).map(&one).transpose();
+ let model = |m: &str| o.get(m).map(one).transpose();
Ok(Some(PasteChoice { rgb: model("rgb")?, cmyk: model("cmyk")? }))
}
Some(v) => {
@@ -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/draw2.rs b/crates/engine/src/cmd/draw2.rs
index 63ae0a3e4c..885fd35988 100644
--- a/crates/engine/src/cmd/draw2.rs
+++ b/crates/engine/src/cmd/draw2.rs
@@ -28,6 +28,7 @@ mod commands;
mod common;
mod cut;
mod freehand;
+mod quickpen;
mod smooth;
pub use commands::specs;
diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs
index 45171f62a1..e4846367b5 100644
--- a/crates/engine/src/cmd/draw2/commands.rs
+++ b/crates/engine/src/cmd/draw2/commands.rs
@@ -1,6 +1,7 @@
use super::anchors::{convert_anchor, curvature, curvature_edit, remove_anchor, remove_anchors, reshape_segment};
use super::cut::{erase_region, erase_segments, knife, split};
use super::freehand::{blob, freehand};
+use super::quickpen::quick_pen;
use super::smooth::{join_scrub, smooth_region};
use super::{CommandSpec, cmd, has_anchors, has_doc, has_selection};
@@ -33,6 +34,15 @@ pub fn specs() -> Vec {
has_doc,
curvature_edit
),
+ cmd!(
+ "path.quickPen",
+ "Quick Pen",
+ [],
+ None,
+ "{start?: [x, y] (a new path starts there), id? (or: draw on this path), subpath?: index (0), keep?: count (default: all its points; the points after the first `keep` are replaced), pieces?: [{x, y, action?: \"line\" (default)|\"continuousArc\"|\"sharpArc\", turn?: 1..359 degrees (180), flip?: bool}] (at most 10000), closed?: bool} draw a path of straight lines and circular arcs as the Quick Pen tool does, each piece from the path's last point to x, y: a line; a continuous arc, which leaves its start in the direction the path arrives in (with no direction, the first piece of a path, it is drawn as a sharp-corner arc; with its end straight ahead or straight behind, as a line); a sharp-corner arc, which turns through `turn` degrees and bulges to the left of the direction drawn (with flip, to the right). A piece that ends where the path does adds nothing. closed: a last piece that ends on the first point joins it, otherwise a straight segment closes the path. A new path takes the current paint (a black stroke when it has neither fill nor stroke); the path is selected, as one undo step → {id}. Without id, `start` must be given; with id, the subpath must be open and `start` is refused",
+ has_doc,
+ quick_pen
+ ),
cmd!(
"path.removeAnchor",
"Delete Anchor Point",
diff --git a/crates/engine/src/cmd/draw2/quickpen.rs b/crates/engine/src/cmd/draw2/quickpen.rs
new file mode 100644
index 0000000000..84640bc876
--- /dev/null
+++ b/crates/engine/src/cmd/draw2/quickpen.rs
@@ -0,0 +1,96 @@
+//! The Quick Pen tool's command (`path.quickPen`): a path of straight lines and circular arcs.
+
+use vectorcraft_tools::quickpen::{self as qp, Piece, Stroke};
+
+use super::common::{path_kind, path_mut, point_entry, usize_opt, within_input_bound};
+use super::{Color, Paint, PathData, Result, Session, SubPath, Value, add_look, bad, json, number_or, object_param, switch_or};
+
+const C: &str = "path.quickPen";
+/// The most pieces one request takes.
+const MAX_PIECES: usize = 10_000;
+
+/// The `pieces` param.
+fn pieces(p: &Value) -> Result> {
+ let list = match p.get("pieces") {
+ None | Some(Value::Null) => return Ok(vec![]),
+ Some(Value::Array(list)) if list.len() <= MAX_PIECES => list,
+ Some(_) => return Err(bad(C, "`pieces` must be a list of at most 10000 pieces")),
+ };
+ list.iter()
+ .map(|v| {
+ let to = point_entry(v, C)?;
+ if !within_input_bound(to) {
+ return Err(bad(C, "x and y must be finite"));
+ }
+ let stroke = match v.get("action") {
+ None | Some(Value::Null) => Stroke::Line,
+ Some(a) => a.as_str().and_then(Stroke::parse).ok_or_else(|| {
+ let key = "action";
+ bad(C, format!("`{key}` must be one of {}", Stroke::ALL.map(Stroke::name).join(", ")))
+ })?,
+ };
+ let turn = number_or(v, "turn", qp::DEFAULT_TURN, C)?;
+ if !(qp::MIN_TURN..=qp::MAX_TURN).contains(&turn) {
+ let (key, min, max) = ("turn", qp::MIN_TURN, qp::MAX_TURN);
+ return Err(bad(C, format!("{key} must be a number from {min} to {max}")));
+ }
+ let flip = switch_or(v, "flip", false, C)?;
+ Ok(Piece { to, stroke, turn, flip })
+ })
+ .collect()
+}
+
+pub(super) fn quick_pen(s: &mut Session, p: &Value) -> Result {
+ let pieces = pieces(p)?;
+ let closed = switch_or(p, "closed", false, C)?;
+ let start_given = p.get("start").is_some_and(|v| !v.is_null());
+ let either = "give either `start` for a new path or `id`, not both";
+ let Some(id) = object_param(p, "id", C)? else {
+ let start = match p.get("start") {
+ Some(v) if start_given => point_entry(v, C)?,
+ _ => return Err(bad(C, either)),
+ };
+ if !within_input_bound(start) {
+ return Err(bad(C, "x and y must be finite"));
+ }
+ if ["subpath", "keep"].iter().any(|key| p.get(key).is_some_and(|v| !v.is_null())) {
+ return Err(bad(C, "`subpath` and `keep` need `id`"));
+ }
+ let sp = qp::build(&SubPath::new(vec![vectorcraft_geom::Anchor::corner(start)], false), &pieces, closed);
+ let mut look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
+ let ap = &mut look.appearance;
+ if ap.stroke_paint().is_none() && ap.fill_paint().is_none() {
+ ap.set_stroke(Paint::solid(Color::BLACK));
+ }
+ return add_look(s, "Quick Pen", path_kind(PathData::single(sp)), look, None);
+ };
+ if start_given {
+ return Err(bad(C, either));
+ }
+ let si = usize_opt(p, "subpath", C)?.unwrap_or(0);
+ let d = &s.doc()?.doc;
+ if !d.is_editable(id) {
+ return Err(bad(C, "the path is locked or hidden"));
+ }
+ let path = d.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(C, "`id` is not a path"))?;
+ let sp = path.subpaths.get(si).ok_or_else(|| bad(C, "no such subpath"))?;
+ if sp.closed {
+ return Err(bad(C, "the subpath is closed"));
+ }
+ let n = sp.anchors.len();
+ let keep = usize_opt(p, "keep", C)?.unwrap_or(n);
+ if keep == 0 || keep > n {
+ let (key, min, max) = ("keep", 1, n);
+ return Err(bad(C, format!("{key} must be a number from {min} to {max}")));
+ }
+ let base = SubPath::new(sp.anchors.get_range(..keep).unwrap_or_default(), false);
+ let out = qp::build(&base, &pieces, closed);
+ let top = super::super::path::compound_or_self(d, id);
+ s.edit("Quick Pen", |d, sel| {
+ let slot = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| crate::EngineError::Other("no such subpath".into()))?;
+ *slot = out;
+ sel.set([top]);
+ Ok(())
+ })?;
+ Ok(json!({ "id": id.0 }))
+}
diff --git a/crates/engine/src/cmd/fileio/psdlayers.rs b/crates/engine/src/cmd/fileio/psdlayers.rs
index cbfaa434d5..17e6c3f814 100644
--- a/crates/engine/src/cmd/fileio/psdlayers.rs
+++ b/crates/engine/src/cmd/fileio/psdlayers.rs
@@ -24,20 +24,28 @@
//! Light, Pin Light, Hard Mix, Subtract, Divide, Darker Color, Lighter Color) is merged with the
//! layers below it in its group. A Dissolve layer's partly transparent pixels are merged as opaque
//! or transparent, opaque at the share of its pixels their transparency gives, in a fixed pattern
-//! that differs from layer to layer. When a merge's canvases would need more memory than allowed,
-//! the layer comes in alone: in the Normal mode, or unclipped.
-//! Hidden layers are left out unless `hidden` asks for them. A hidden layer that would need a merge
-//! (one in a mode VectorCraft lacks, one that layers are clipped to, one clipped to another, or
-//! one below a merged layer) is always left out, with the layers clipped to it. Adjustment layers,
-//! fill layers that store no pixels and whose fill isn't read or whose shape is a vector mask,
-//! layer effects that are switched on, knockouts and vector masks aren't applied; the warnings
-//! count them and the hidden layers left out.
+//! that differs from layer to layer. A layer or group in a group whose Knockout setting is 1 (read
+//! as a shallow knockout) is merged with the layers below it in its group too, as the import option
+//! describes: where it has pixels, they are cleared to transparency and it is drawn there at its fill
+//! opacity, and its opacity fades that back toward them. In a pass-through group this is done only
+//! when it and the visible layers below it are in the Normal mode. When a merge's canvases would need more
+//! memory than allowed, the layer comes in alone: in the Normal mode, unclipped, or without its
+//! knockout. Hidden layers are left out unless `hidden` asks for them. A hidden layer that would need
+//! a merge (one in a mode VectorCraft lacks, one with a knockout in a group that changes the layers
+//! below it, one that layers are clipped to, one clipped to another, or one below a merged layer) is
+//! always left out, with the layers clipped to it. Adjustment layers, fill layers that store no
+//! pixels and whose fill isn't read or whose shape is a vector mask, layer effects that are switched
+//! on, vector masks, and the knockouts of top-level layers, of clipped layers, of layers that others
+//! are clipped to and of layers in a pass-through group with a layer in another mode, and other
+//! Knockout values, aren't applied; the warnings count them and the hidden layers left out.
//!
//! The file is untrusted: every count, length and size is checked before anything is allocated,
//! groups nest at most [`MAX_DEPTH`] deep (layers deeper than a document may nest merge into the
//! group around them, with a warning), each layer's pixels, like the canvases one step of a
//! merge holds together, must fit the memory allowed, and all the pixels decoded and the canvases
-//! the merges make must fit [`TOTAL_DECODED`] times that.
+//! the merges make must fit [`TOTAL_DECODED`] times that. A merge being tried may take that much
+//! past what was read before it. What the merges that aren't made, or that a hidden layer would
+//! need, decoded and made is counted apart, against the same limit.
use std::cell::Cell;
use std::sync::Arc;
@@ -66,6 +74,13 @@ const MAX_CHANNELS: usize = 56;
const MIN_RECORD: usize = 34;
const DAMAGED: &str = "the PSD file's layer records are damaged";
+#[cfg(test)]
+thread_local! {
+ /// The layer lists imports on this thread have walked, and the most a test lets them walk
+ /// before the import stops with an error.
+ pub(super) static WALKS: Cell<(usize, usize)> = const { Cell::new((0, usize::MAX)) };
+}
+
/// The keys of the tagged blocks that make a layer an adjustment layer.
const ADJUSTMENTS: [&[u8; 4]; 18] = [
b"levl", b"curv", b"brit", b"blnc", b"hue ", b"hue2", b"selc", b"mixr", b"grdm", b"phfl", b"expA", b"vibA", b"thrs", b"nvrt", b"post", b"clrL",
@@ -227,7 +242,9 @@ struct Record<'a> {
content: Content,
effects: bool,
vector_mask: bool,
- knockout: bool,
+ /// The Knockout setting's byte (`knko`): 0 none, 1 a shallow knockout. Any other value isn't
+ /// applied.
+ knockout: u8,
}
/// The layer records of `info` (the layer count, the records, then their channels' data).
@@ -285,7 +302,7 @@ fn record<'a>(r: &mut Reader<'a>, psb: bool) -> Result<(Record<'a>, Vec<(i16, us
content: Content::Pixels,
effects: false,
vector_mask: false,
- knockout: false,
+ knockout: 0,
};
rec.read_extra(extra, psb)?;
Ok((rec, lengths))
@@ -345,8 +362,7 @@ impl Record<'_> {
b"lfx2" | b"lmfx" => effects = Some(effects == Some(true) || effects_on(data)),
b"lrFX" => old_effects = true,
b"vmsk" | b"vsms" => self.vector_mask = true,
- // Shallow or deep knockout.
- b"knko" => self.knockout = data.first().is_some_and(|&k| k != 0),
+ b"knko" => self.knockout = data.first().copied().unwrap_or(0),
k if ADJUSTMENTS.contains(&k) => self.content = Content::Adjustment,
_ => {}
}
@@ -612,6 +628,8 @@ struct Unit<'i> {
body: Body<'i>,
/// While layers are clipped to it: how its merged canvas is shaped.
clip: Option,
+ /// Layers are clipped to it, merged into it or not.
+ base: bool,
}
impl Unit<'_> {
@@ -640,13 +658,36 @@ enum Clip {
enum Body<'i> {
/// A layer record's pixels.
Layer(usize),
- /// A group's layers.
- Group(&'i [Item]),
+ /// A group's record and its layers.
+ Group(usize, &'i [Item]),
/// Layers merged into one image.
Merged(Canvas),
}
+/// Where a layer list is.
+#[derive(Clone, Copy, PartialEq)]
+enum Level {
+ /// The file's top level.
+ Top,
+ /// An isolated group, or a group drawn on its own.
+ Group,
+ /// A pass-through group whose layers blend with what is below it.
+ Pass,
+}
+
+/// What a knockout's merge with the layers below it gives.
+enum Knocked {
+ /// The merged canvas.
+ Merged(Canvas),
+ /// Nothing below it draws, it draws nothing, it is at 0 fill and cuts no painted pixel below
+ /// it, or what is below it and the merge are both transparent: it comes in as a layer of its own.
+ Nothing,
+ /// The canvases would need more memory than allowed.
+ TooLarge,
+}
+
/// A unit's body drawn alone.
+#[derive(Clone)]
enum Drawn {
/// It draws nothing.
Nothing,
@@ -663,6 +704,7 @@ struct Notes {
fills: usize,
effects: usize,
vector_masks: usize,
+ /// Layers whose knockout wasn't applied.
knockouts: usize,
/// Hidden layers left out, and layers clipped to them.
hidden: usize,
@@ -677,11 +719,17 @@ struct Notes {
/// The counts a merge that can't be made gives back.
#[derive(Clone, Copy)]
struct Counts {
+ /// The bytes spent so far (see [`Builder::spent`]).
+ spent: u64,
skipped: usize,
+ /// The knockouts counted as not applied.
+ unknocked: usize,
merged: usize,
unmerged: usize,
unclipped: usize,
clipped_out: usize,
+ /// The groups found to read no pixels.
+ blank: usize,
}
/// Adds the warning for `n` things to `out`: `one` when `n` is 1, `many` with the count in place
@@ -745,8 +793,17 @@ impl Notes {
out
}
- fn counts(&self, skipped: usize) -> Counts {
- Counts { skipped, merged: self.merged.len(), unmerged: self.unmerged, unclipped: self.unclipped, clipped_out: self.clipped_out }
+ fn counts(&self, spent: u64, skipped: usize, unknocked: usize, blank: usize) -> Counts {
+ Counts {
+ spent,
+ skipped,
+ unknocked,
+ merged: self.merged.len(),
+ unmerged: self.unmerged,
+ unclipped: self.unclipped,
+ clipped_out: self.clipped_out,
+ blank,
+ }
}
}
@@ -767,12 +824,47 @@ struct Builder<'a, F> {
notes: Notes,
/// The records [`Notes`] counted.
noted: Vec,
+ /// Those records, in the order they were counted.
+ noted_log: Vec,
/// The records counted as hidden layers left out.
skipped: Vec,
/// Those records, in the order they were counted.
skip_log: Vec,
+ /// The records counted as knockouts not applied.
+ unknocked: Vec,
+ /// Those records, in the order they were counted.
+ unknock_log: Vec,
+ /// The records counted as layers clipped to a fill that isn't drawn.
+ clipped_out: Vec,
+ /// Those records, in the order they were counted.
+ clipped_out_log: Vec,
+ /// The records counted as clipped layers left unclipped.
+ unclipped: Vec,
+ /// Those records, in the order they were counted.
+ unclip_log: Vec,
+ /// The records that came in as layers of the document (hidden ones too, with `hidden`): not left
+ /// out, though a drawing for a merge that wasn't made counted them.
+ kept: Vec,
/// Bytes of layer and mask pixels decoded, and of canvases the merges made, so far.
spent: Cell,
+ /// Those bytes that merges not made, and merges a hidden layer would need, took: given back to
+ /// `spent` and counted here instead, against the same limit.
+ wasted: Cell,
+ /// `spent` when the innermost merge being tried began: until it is made or given up, it may
+ /// spend the whole allowance past that (see [`Self::spend`]).
+ trial: Cell,
+ /// The layers whose pixels were read so far (each time they were).
+ painted: Cell,
+ /// What each group gave when drawn alone without reading any layer's pixels (nothing, or a
+ /// canvas without pixels, whatever the memory left): drawing it again gives that without
+ /// walking its layers.
+ blank: Vec>,
+ /// The pass-through groups that laid nothing onto nothing (see [`Self::laid_nothing`]).
+ laid_blank: Vec,
+ /// The groups of both, in the order they were found.
+ blank_log: Vec,
+ /// How many times a merge was counted as not made because it needed more memory than allowed.
+ squeezed: usize,
}
impl [f32; 3]> Builder<'_, F> {
@@ -786,10 +878,38 @@ impl [f32; 3]> Builder<'_, F> {
}
/// Count `bytes` of decoded pixels, or of a canvas a merge makes, against the whole import's
- /// allowance, [`TOTAL_DECODED`] times the memory allowed for one image.
+ /// allowance, [`TOTAL_DECODED`] times the memory allowed for one image. While a merge is tried
+ /// (see [`Self::try_from_here`]), only what it spent counts against the allowance.
fn spend(&self, bytes: u64) -> Result<(), String> {
let total = self.spent.get().saturating_add(bytes);
self.spent.set(total);
+ if total.saturating_sub(self.trial.get()) > self.max_alloc.saturating_mul(TOTAL_DECODED) {
+ return Err("the PSD file's layers take more memory to read than allowed".into());
+ }
+ Ok(())
+ }
+
+ /// Start trying a merge that may not be made: what it spends counts against the whole
+ /// allowance, however much was spent before it. Gives what [`Self::tried`] takes back.
+ fn try_from_here(&self) -> u64 {
+ self.trial.replace(self.spent.get())
+ }
+
+ /// End the merge tried since [`Self::try_from_here`] gave `outer`. A merge that is `made` keeps
+ /// what it spent, which must then fit the allowance with what was spent before it.
+ fn tried(&self, outer: u64, made: bool) -> Result<(), String> {
+ self.trial.set(outer);
+ if made { self.spend(0) } else { Ok(()) }
+ }
+
+ /// Move the bytes spent since `spent` was the count to [`Self::wasted`], which has an allowance
+ /// of its own as large: what a merge that isn't made decoded doesn't take the room for reading
+ /// the layers apart.
+ fn refund(&self, spent: u64) -> Result<(), String> {
+ let since = self.spent.get().saturating_sub(spent);
+ self.spent.set(self.spent.get().min(spent));
+ let total = self.wasted.get().saturating_add(since);
+ self.wasted.set(total);
if total > self.max_alloc.saturating_mul(TOTAL_DECODED) {
return Err("the PSD file's layers take more memory to read than allowed".into());
}
@@ -814,6 +934,7 @@ impl [f32; 3]> Builder<'_, F> {
Paint::Cmyk(ink) => (self.cmyk)(ink),
};
let px = image::Rgba([byte(rgb[0]), byte(rgb[1]), byte(rgb[2]), 255]);
+ self.painted.set(self.painted.get() + 1);
return Ok(Some((0, 0, RgbaImage::from_pixel(h.width, h.height, px))));
}
Content::Pixels | Content::Type | Content::Solid(_) | Content::Fill => rec.bounds.size(),
@@ -845,6 +966,7 @@ impl [f32; 3]> Builder<'_, F> {
let rgb = to_rgb(h, |c| planes.get(c).map_or(0.0, |p| at(p, linear, 0.0)), &self.cmyk);
image::Rgba([byte(rgb[0]), byte(rgb[1]), byte(rgb[2]), byte(at(&alpha, false, 1.0))])
});
+ self.painted.set(self.painted.get() + 1);
Ok(Some((i64::from(rec.bounds.left), i64::from(rec.bounds.top), img)))
}
@@ -897,7 +1019,7 @@ impl [f32; 3]> Builder<'_, F> {
for item in items {
let (i, body) = match item {
Item::Layer(i) => (*i, Body::Layer(*i)),
- Item::Group(i, children) => (*i, Body::Group(children)),
+ Item::Group(i, children) => (*i, Body::Group(*i, children)),
};
let rec = self.record(i)?;
let (name, hidden, clipped, blend) = (rec.name.clone(), rec.hidden, rec.clipped, rec.blend);
@@ -920,14 +1042,26 @@ impl [f32; 3]> Builder<'_, F> {
Some(b) => {
// Counted even when it draws nothing (an adjustment layer).
self.note(i)?;
- if !unclipped && self.clip(&mut out, b, &body, i, &name, blend, opacity)? {
+ // A clipped layer's knockout isn't applied.
+ if self.record(i)?.knockout != 0 {
+ self.unknock(i);
+ }
+ if let Some(u) = out.get_mut(b) {
+ u.base = true;
+ }
+ let spent = self.spent.get();
+ let outer = self.try_from_here();
+ let made = !unclipped && self.clip(&mut out, b, &body, i, &name, blend, opacity)?;
+ self.tried(outer, made)?;
+ if made {
continue;
}
+ self.refund(spent)?;
// The merge doesn't fit: this layer and the next ones clipped to the same
// base come in as layers of their own.
unclipped = true;
- self.notes.unclipped += 1;
- out.push(Unit { name, visible: true, opacity, blend, mask_of: Some(i), record: i, body, clip: None });
+ self.unclip(i);
+ out.push(Unit { name, visible: true, opacity, blend, mask_of: Some(i), record: i, body, clip: None, base: false });
}
}
continue;
@@ -939,7 +1073,7 @@ impl [f32; 3]> Builder<'_, F> {
continue;
}
self.note(i)?;
- out.push(Unit { name, visible: !hidden, opacity, blend, mask_of: Some(i), record: i, body, clip: None });
+ out.push(Unit { name, visible: !hidden, opacity, blend, mask_of: Some(i), record: i, body, clip: None, base: false });
base = Some(Some(out.len() - 1));
}
for u in &mut out {
@@ -962,7 +1096,7 @@ impl [f32; 3]> Builder<'_, F> {
};
// A fill whose shape is a vector mask isn't drawn, and nothing clipped to it is either.
if undrawn && u.clip.is_none() {
- self.notes.clipped_out += 1;
+ self.clip_out(i);
return Ok(true);
}
let layer = match self.draw_body(body, Some(i))? {
@@ -1045,12 +1179,15 @@ impl [f32; 3]> Builder<'_, F> {
// Once, though a merge may draw it again.
match self.noted.get_mut(i) {
Some(true) => return Ok(()),
- Some(n) => *n = true,
+ Some(n) => {
+ *n = true;
+ self.noted_log.push(i);
+ }
None => {}
}
- let (content, empty, effects, vector_mask, knockout) = {
+ let (content, empty, effects, vector_mask) = {
let rec = self.record(i)?;
- (rec.content, rec.stores_nothing(), rec.effects, rec.vector_mask, rec.knockout)
+ (rec.content, rec.stores_nothing(), rec.effects, rec.vector_mask)
};
match content {
Content::Type => self.notes.types += 1,
@@ -1062,10 +1199,59 @@ impl [f32; 3]> Builder<'_, F> {
}
self.notes.effects += usize::from(effects);
self.notes.vector_masks += usize::from(vector_mask);
- self.notes.knockouts += usize::from(knockout);
Ok(())
}
+ /// What [`Self::note`] has counted so far: the length of its log, and the counts.
+ fn noted_so_far(&self) -> (usize, [usize; 5]) {
+ let n = &self.notes;
+ (self.noted_log.len(), [n.types, n.adjustments, n.fills, n.effects, n.vector_masks])
+ }
+
+ /// Forget what [`Self::note`] counted since `so_far`, for layers that are left out.
+ fn unnote(&mut self, (logged, counts): (usize, [usize; 5])) {
+ for i in self.noted_log.split_off(logged) {
+ if let Some(n) = self.noted.get_mut(i) {
+ *n = false;
+ }
+ }
+ let n = &mut self.notes;
+ [n.types, n.adjustments, n.fills, n.effects, n.vector_masks] = counts;
+ }
+
+ /// Count record `i` as a layer whose knockout isn't applied (once).
+ fn unknock(&mut self, i: usize) {
+ if let Some(s) = self.unknocked.get_mut(i)
+ && !*s
+ {
+ *s = true;
+ self.notes.knockouts += 1;
+ self.unknock_log.push(i);
+ }
+ }
+
+ /// Does unit `u`, at `level` above the units `below` it, take a shallow knockout this import
+ /// applies? Only a layer or group in a group, neither clipped nor a base of clipped layers, does;
+ /// in a pass-through group, only when it and the visible units below it are in the Normal mode, so
+ /// that none of them blends with what is below the group. Any other knockout is counted as not
+ /// applied. One at 0 opacity, or with no visible unit below it, changes nothing below it: it needs
+ /// no merge, and a hidden one isn't left out for it.
+ fn knocks(&mut self, u: &Unit<'_>, below: &[Unit<'_>], level: Level) -> Result {
+ let rec = self.record(u.record)?;
+ if rec.knockout == 0 {
+ return Ok(false);
+ }
+ let normal = |u: &Unit<'_>| u.blend == Blend::Mode(BlendMode::Normal);
+ let blends_out = level == Level::Pass && !(normal(u) && below.iter().filter(|b| b.visible).all(normal));
+ let applies = rec.knockout == 1 && level != Level::Top && !blends_out && !rec.clipped && !u.base && !matches!(u.body, Body::Merged(_));
+ // Its fill opacity isn't checked: at 0 fill it still clears what is below it.
+ let changes = rec.opacity > 0.0 && below.iter().any(|b| b.visible);
+ if !applies {
+ self.unknock(u.record);
+ }
+ Ok(applies && changes)
+ }
+
/// Count record `i` as a hidden layer left out (once).
fn skip(&mut self, i: usize) {
if let Some(s) = self.skipped.get_mut(i)
@@ -1077,21 +1263,100 @@ impl [f32; 3]> Builder<'_, F> {
}
}
- /// `items`' units with the layers in blend modes VectorCraft lacks merged with those below.
- fn merged<'i>(&mut self, items: &'i [Item], keep_hidden: bool) -> Result>, String> {
+ /// Count record `i` as a layer clipped to a fill that isn't drawn (once).
+ fn clip_out(&mut self, i: usize) {
+ if let Some(s) = self.clipped_out.get_mut(i)
+ && !*s
+ {
+ *s = true;
+ self.notes.clipped_out += 1;
+ self.clipped_out_log.push(i);
+ }
+ }
+
+ /// Count record `i` as a clipped layer left unclipped (once).
+ fn unclip(&mut self, i: usize) {
+ self.squeezed += 1;
+ if let Some(s) = self.unclipped.get_mut(i)
+ && !*s
+ {
+ *s = true;
+ self.notes.unclipped += 1;
+ self.unclip_log.push(i);
+ }
+ }
+
+ /// `items`' units, at `level`, with the layers in blend modes VectorCraft lacks, and in a group
+ /// the layers with a shallow knockout, merged with those below.
+ fn merged<'i>(&mut self, items: &'i [Item], keep_hidden: bool, level: Level) -> Result>, String> {
+ #[cfg(test)]
+ {
+ let (walked, most) = WALKS.get();
+ if walked >= most {
+ return Err("the import walked more layer lists than the test allows".into());
+ }
+ WALKS.set((walked + 1, most));
+ }
let mut out: Vec> = vec![];
for mut u in self.units(items, keep_hidden)? {
+ // A hidden layer in a mode VectorCraft lacks would need the merge for its mode: it is left
+ // out without being drawn.
+ if !u.visible && matches!(u.blend, Blend::Other(_)) {
+ self.skip(u.record);
+ continue;
+ }
+ if self.knocks(&u, &out, level)? {
+ let saved = self.saved();
+ let noted = self.noted_so_far();
+ let squeezed = self.squeezed;
+ let outer = self.try_from_here();
+ let knocked = self.knock(&out, &u)?;
+ self.tried(outer, u.visible && matches!(knocked, Knocked::Merged(_)))?;
+ match knocked {
+ // A hidden layer that would need the merge is left out, and nothing its drawing
+ // counted is counted.
+ Knocked::Merged(_) | Knocked::TooLarge if !u.visible => {
+ self.restore(saved)?;
+ self.unnote(noted);
+ self.skip(u.record);
+ continue;
+ }
+ Knocked::Merged(canvas) => {
+ self.take_merge(&mut out, &u, canvas);
+ if let Blend::Other(other) = u.blend
+ && !self.notes.merged.contains(&other.label())
+ {
+ self.notes.merged.push(other.label());
+ }
+ continue;
+ }
+ // Nothing below it, or nothing of its own, to knock out: it comes in as a layer,
+ // with the hidden layers its drawing left out (see `kept`). What its drawing
+ // read is read again when it comes in. A hidden one may still be left out by a
+ // later merge: what its drawing counted is counted when it comes in instead.
+ Knocked::Nothing if !u.visible => {
+ self.restore(saved)?;
+ self.unnote(noted);
+ }
+ // A merge below it that its held canvas left without the memory it needed may
+ // be made when they come in without it: what drawing them counted is given back
+ // and counted again then.
+ Knocked::Nothing if self.squeezed != squeezed => self.restore(saved)?,
+ Knocked::Nothing => self.refund(saved.spent)?,
+ Knocked::TooLarge => {
+ self.restore(saved)?;
+ self.squeezed += 1;
+ self.unknock(u.record);
+ }
+ }
+ }
let Blend::Other(other) = u.blend else {
out.push(u);
continue;
};
- // A hidden layer that would need the merge is left out.
- if !u.visible {
- self.skip(u.record);
- continue;
- }
// A merge that can't be made counts nothing its groups would have counted.
- let saved = self.notes.counts(self.skip_log.len());
+ let saved = self.saved();
+ let outer = self.try_from_here();
let made = match out.as_mut_slice() {
// Onto the previous merge alone: composited onto its canvas, in place.
[prev] if prev.is_merge() => {
@@ -1113,45 +1378,20 @@ impl [f32; 3]> Builder<'_, F> {
}
_ => match self.merge(&out, &u)? {
Some(canvas) => {
- let mut name = String::new();
- for (k, b) in out.iter_mut().filter(|b| b.visible).enumerate() {
- if k == 0 {
- name = std::mem::take(&mut b.name);
- } else {
- name.push_str(" + ");
- name.push_str(&b.name);
- }
- }
- if out.iter().any(|b| b.visible) {
- name.push_str(" + ");
- }
- name.push_str(&u.name);
- // Hidden layers below are left out with the rest.
- for b in out.iter().filter(|b| !b.visible).map(|b| b.record).collect::>() {
- self.skip(b);
- }
- out.clear();
- out.push(Unit {
- name,
- visible: true,
- opacity: 1.0,
- blend: Blend::Mode(BlendMode::Normal),
- mask_of: None,
- record: u.record,
- body: Body::Merged(canvas),
- clip: None,
- });
+ self.take_merge(&mut out, &u, canvas);
true
}
None => false,
},
};
+ self.tried(outer, made)?;
if made {
if !self.notes.merged.contains(&other.label()) {
self.notes.merged.push(other.label());
}
} else {
- self.restore(saved);
+ self.restore(saved)?;
+ self.squeezed += 1;
self.notes.unmerged += 1;
u.blend = Blend::Mode(BlendMode::Normal);
out.push(u);
@@ -1160,18 +1400,51 @@ impl [f32; 3]> Builder<'_, F> {
Ok(out)
}
- /// The counts as they were before a merge that couldn't be made.
- fn restore(&mut self, c: Counts) {
+ /// The counts as they are, for [`Self::restore`].
+ fn saved(&self) -> Counts {
+ self.notes.counts(self.spent.get(), self.skip_log.len(), self.unknock_log.len(), self.blank_log.len())
+ }
+
+ /// The counts as they were before a merge that couldn't be made, the bytes it spent counted as
+ /// wasted (see [`Self::refund`]).
+ fn restore(&mut self, c: Counts) -> Result<(), String> {
+ self.refund(c.spent)?;
for i in self.skip_log.split_off(c.skipped) {
if let Some(s) = self.skipped.get_mut(i) {
*s = false;
self.notes.hidden = self.notes.hidden.saturating_sub(1);
}
}
+ for i in self.unknock_log.split_off(c.unknocked) {
+ if let Some(s) = self.unknocked.get_mut(i) {
+ *s = false;
+ self.notes.knockouts = self.notes.knockouts.saturating_sub(1);
+ }
+ }
+ // The groups found since: what their drawing counted is given back, so they are drawn again.
+ for g in self.blank_log.split_off(c.blank) {
+ if let Some(b) = self.blank.get_mut(g) {
+ *b = None;
+ }
+ if let Some(b) = self.laid_blank.get_mut(g) {
+ *b = false;
+ }
+ }
+ for i in self.unclip_log.split_off(c.unclipped) {
+ if let Some(s) = self.unclipped.get_mut(i) {
+ *s = false;
+ self.notes.unclipped = self.notes.unclipped.saturating_sub(1);
+ }
+ }
+ for i in self.clipped_out_log.split_off(c.clipped_out) {
+ if let Some(s) = self.clipped_out.get_mut(i) {
+ *s = false;
+ self.notes.clipped_out = self.notes.clipped_out.saturating_sub(1);
+ }
+ }
self.notes.merged.truncate(c.merged);
self.notes.unmerged = c.unmerged;
- self.notes.unclipped = c.unclipped;
- self.notes.clipped_out = c.clipped_out;
+ Ok(())
}
/// The visible units `below` with `top` composited over them; `None` when the canvas would need
@@ -1186,24 +1459,169 @@ impl [f32; 3]> Builder<'_, F> {
Ok(Some(acc.unwrap_or_default()))
}
+ /// `out` replaced by one layer: `canvas`, the merge of its visible units with `top`, named after
+ /// them, bottom first. Its hidden units are left out.
+ fn take_merge<'i>(&mut self, out: &mut Vec>, top: &Unit<'_>, canvas: Canvas) {
+ let mut name = String::new();
+ for (k, b) in out.iter_mut().filter(|b| b.visible).enumerate() {
+ if k == 0 {
+ name = std::mem::take(&mut b.name);
+ } else {
+ name.push_str(" + ");
+ name.push_str(&b.name);
+ }
+ }
+ if out.iter().any(|b| b.visible) {
+ name.push_str(" + ");
+ }
+ name.push_str(&top.name);
+ // Hidden layers below are left out with the rest.
+ for b in out.iter().filter(|b| !b.visible).map(|b| b.record).collect::>() {
+ self.skip(b);
+ }
+ out.clear();
+ out.push(Unit {
+ name,
+ visible: true,
+ opacity: 1.0,
+ blend: Blend::Mode(BlendMode::Normal),
+ mask_of: None,
+ record: top.record,
+ body: Body::Merged(canvas),
+ clip: None,
+ base: false,
+ });
+ }
+
+ /// The visible units `below` with `top`, a layer with a shallow knockout, knocking them out: where
+ /// `top` has pixels, what is below it in its group is cleared to transparency (the group's own
+ /// backdrop) and `top` is drawn there at its fill opacity; its opacity then fades all of that
+ /// back toward the units below as they were. Its layer mask shapes the cut.
+ fn knock(&mut self, below: &[Unit<'_>], top: &Unit<'_>) -> Result {
+ let (fill, opacity) = {
+ let rec = self.record(top.record)?;
+ (rec.fill, rec.opacity)
+ };
+ let k = match self.draw_body(&top.body, top.mask_of)? {
+ Drawn::Nothing => return Ok(Knocked::Nothing),
+ Drawn::TooLarge => return Ok(Knocked::TooLarge),
+ Drawn::Canvas(c) if c.px.iter().all(|p| p[3] <= 0.0) => return Ok(Knocked::Nothing),
+ Drawn::Canvas(c) => c,
+ };
+ // At 0 fill, beside every layer below it, it cuts nothing: no canvas for them is needed.
+ if fill <= 0.0 && self.beside(below, &k)? {
+ return Ok(Knocked::Nothing);
+ }
+ // The layer's canvas is held while the units below are drawn.
+ let bytes = 16 * k.px.len() as u64;
+ self.held = self.held.saturating_add(bytes);
+ let mut acc: Option = None;
+ let mut drawn = Ok(true);
+ for u in below.iter().filter(|u| u.visible) {
+ drawn = self.composite(&mut acc, u);
+ if !matches!(drawn, Ok(true)) {
+ break;
+ }
+ }
+ self.held = self.held.saturating_sub(bytes);
+ if !drawn? {
+ return Ok(Knocked::TooLarge);
+ }
+ // Nothing below draws.
+ let Some(below) = acc.as_ref() else { return Ok(Knocked::Nothing) };
+ // At 0 fill it draws nothing of its own: where it cuts no painted pixel below, no canvas for
+ // the merge is needed.
+ if fill <= 0.0 && !cuts_paint(below, &k, top.blend, opacity, top.record) {
+ return Ok(Knocked::Nothing);
+ }
+ let clear = |c: &Canvas| c.px.iter().all(|p| p[3] <= 0.0);
+ let below_clear = clear(below);
+ if !knock_onto(&mut acc, &k, top.blend, fill, opacity, top.record, self.room(), &|n| self.spend(n))? {
+ return Ok(Knocked::TooLarge);
+ }
+ // Nothing below to cut, and nothing of its own drawn at its fill opacity.
+ if below_clear && acc.as_ref().is_none_or(clear) {
+ return Ok(Knocked::Nothing);
+ }
+ Ok(acc.map_or(Knocked::Nothing, Knocked::Merged))
+ }
+
+ /// Do the pixels `knock` paints lie outside the bounds of every visible unit `below`? Only the
+ /// bounds of layers and of merged canvases are known without drawing them: with a group below,
+ /// `false`.
+ fn beside(&self, below: &[Unit<'_>], knock: &Canvas) -> Result {
+ let width = knock.width.max(1);
+ let mut painted: Option<[i64; 4]> = None;
+ for (k, _) in knock.px.iter().enumerate().filter(|(_, p)| p[3] > 0.0) {
+ let (x, y) = (knock.left + (k % width) as i64, knock.top + (k / width) as i64);
+ painted = Some(painted.map_or([x, y, x + 1, y + 1], |[l, t, r, b]| [l.min(x), t.min(y), r.max(x + 1), b.max(y + 1)]));
+ }
+ let Some([left, top, right, bottom]) = painted else { return Ok(true) };
+ for u in below.iter().filter(|u| u.visible) {
+ let [l, t, r, b] = match &u.body {
+ Body::Merged(c) => [c.left, c.top, c.left + c.width as i64, c.top + c.height as i64],
+ Body::Layer(i) => {
+ let rec = self.record(*i)?;
+ match rec.content {
+ Content::Adjustment => continue,
+ Content::Solid(Some(_)) if rec.color_over_canvas() => [0, 0, i64::from(self.h.width), i64::from(self.h.height)],
+ _ => {
+ let (w, h) = rec.bounds.size();
+ let (l, t) = (i64::from(rec.bounds.left), i64::from(rec.bounds.top));
+ [l, t, l + w as i64, t + h as i64]
+ }
+ }
+ }
+ Body::Group(..) => return Ok(false),
+ };
+ if l < right && left < r && t < bottom && top < b {
+ return Ok(false);
+ }
+ }
+ Ok(true)
+ }
+
/// The bytes a merge step may still take: the memory allowed, less the copies of what is below
/// the pass-through groups being merged.
fn room(&self) -> u64 {
self.max_alloc.saturating_sub(self.held)
}
+ /// Note pass-through group `g` as laying nothing onto nothing when `acc`, nothing before, still
+ /// is and no layer's pixels were read since `painted`: laying its layers onto nothing again
+ /// gives nothing, with the same notes.
+ fn laid_nothing(&mut self, g: usize, acc: &Option, painted: usize) {
+ if acc.is_none()
+ && self.painted.get() == painted
+ && let Some(b) = self.laid_blank.get_mut(g)
+ && !*b
+ {
+ *b = true;
+ self.blank_log.push(g);
+ }
+ }
+
/// Unit `u` composited onto `acc`. A pass-through group lays its layers onto `acc` one by one,
/// so that they blend with what is below it; at less than full opacity or with a layer mask, the
/// result is then faded back toward `acc` as it was by the opacity and the mask. Anything else
/// is drawn alone first. `false` when the canvas would need more memory than allowed.
fn composite(&mut self, acc: &mut Option, u: &Unit<'_>) -> Result {
- if let (Body::Group(items), Blend::Pass) = (&u.body, u.blend) {
+ if let (Body::Group(g, items), Blend::Pass) = (&u.body, u.blend) {
let mask = match u.mask_of {
Some(i) if self.has_mask(Some(i))? => self.mask(i, false)?,
_ => None,
};
+ // Onto nothing, a group that laid nothing onto nothing before lays nothing again.
+ let (fresh, painted) = (acc.is_none(), self.painted.get());
+ if fresh && self.laid_blank.get(*g) == Some(&true) {
+ return Ok(true);
+ }
if u.opacity >= 1.0 && mask.is_none() {
- return self.lay(acc, items);
+ let laid = self.lay(acc, items, Level::Pass)?;
+ if laid && fresh {
+ self.laid_nothing(*g, acc, painted);
+ }
+ return Ok(laid);
}
let bytes = acc.as_ref().map_or(0, |c| 16 * c.px.len() as u64);
if bytes > self.room() {
@@ -1212,11 +1630,14 @@ impl [f32; 3]> Builder<'_, F> {
self.spend(bytes)?;
let below = acc.clone();
self.held = self.held.saturating_add(bytes);
- let laid = self.lay(acc, items);
+ let laid = self.lay(acc, items, Level::Pass);
self.held = self.held.saturating_sub(bytes);
if !laid? {
return Ok(false);
}
+ if fresh {
+ self.laid_nothing(*g, acc, painted);
+ }
if let Some(after) = acc.as_mut() {
fade(after, below.as_ref(), u.opacity, mask.as_ref());
}
@@ -1230,10 +1651,10 @@ impl [f32; 3]> Builder<'_, F> {
blend_onto(acc, &c, u.blend, u.opacity, u.record, self.room(), &|n| self.spend(n))
}
- /// `items`' layers composited onto `acc` one by one; `false` when a canvas would need more
- /// memory than allowed.
- fn lay(&mut self, acc: &mut Option, items: &[Item]) -> Result {
- for c in self.merged(items, false)? {
+ /// `items`' layers, the layers of a group at `level`, composited onto `acc` one by one; `false`
+ /// when a canvas would need more memory than allowed.
+ fn lay(&mut self, acc: &mut Option, items: &[Item], level: Level) -> Result {
+ for c in self.merged(items, false, level)? {
if !self.composite(acc, &c)? {
return Ok(false);
}
@@ -1271,13 +1692,29 @@ impl [f32; 3]> Builder<'_, F> {
}
None => return Ok(Drawn::Nothing),
},
- Body::Group(items) => {
- let mut acc: Option = None;
- if !self.lay(&mut acc, items)? {
- return Ok(Drawn::TooLarge);
+ Body::Group(g, items) => {
+ let drawn = match self.blank.get(*g).cloned().flatten() {
+ Some(d) => d,
+ None => {
+ let painted = self.painted.get();
+ let mut acc: Option = None;
+ if !self.lay(&mut acc, items, Level::Group)? {
+ return Ok(Drawn::TooLarge);
+ }
+ let d = acc.map_or(Drawn::Nothing, Drawn::Canvas);
+ if self.painted.get() == painted
+ && let Some(b) = self.blank.get_mut(*g)
+ {
+ *b = Some(d.clone());
+ self.blank_log.push(*g);
+ }
+ d
+ }
+ };
+ match drawn {
+ Drawn::Canvas(c) => c,
+ other => return Ok(other),
}
- let Some(acc) = acc else { return Ok(Drawn::Nothing) };
- acc
}
};
if let Some(i) = mask_of {
@@ -1306,10 +1743,10 @@ impl [f32; 3]> Builder<'_, F> {
Ok(n)
}
- /// Layers of the document for `items`, bottom first.
- fn list(&mut self, items: &[Item]) -> Result>, String> {
+ /// Layers of the document for `items`, the layers at `level`, bottom first.
+ fn list(&mut self, items: &[Item], level: Level) -> Result>, String> {
let mut out = vec![];
- for u in self.merged(items, self.hidden)? {
+ for u in self.merged(items, self.hidden, level)? {
if let Some(n) = self.node(u)? {
out.push(Arc::new(n));
}
@@ -1320,6 +1757,9 @@ impl [f32; 3]> Builder<'_, F> {
/// The layer of the document unit `u` becomes; `None` for a layer that draws nothing (an
/// adjustment layer, or one without pixels).
fn node(&mut self, u: Unit<'_>) -> Result, String> {
+ if let Some(k) = self.kept.get_mut(u.record) {
+ *k = true;
+ }
let children = match &u.body {
Body::Layer(i) => match self.image(*i)? {
Some((left, top, img)) => vec![Arc::new(self.image_node(&u.name, left, top, img)?)],
@@ -1329,13 +1769,13 @@ impl [f32; 3]> Builder<'_, F> {
Some((left, top, img)) => vec![Arc::new(self.image_node(&u.name, left, top, img)?)],
None => return Ok(None),
},
- Body::Group(items) => self.list(items)?,
+ Body::Group(_, items) => self.list(items, if u.blend == Blend::Pass { Level::Pass } else { Level::Group })?,
};
let mut layer = self.layer(&u.name);
layer.visible = u.visible;
layer.opacity = u.opacity.clamp(0.0, 1.0);
(layer.blend, layer.isolate) = match u.blend {
- Blend::Mode(m) => (m, matches!(u.body, Body::Group(_))),
+ Blend::Mode(m) => (m, matches!(u.body, Body::Group(..))),
Blend::Pass | Blend::Other(_) => (BlendMode::Normal, false),
};
if let Some(c) = layer.children_mut() {
@@ -1443,6 +1883,71 @@ fn blend_onto(
max_alloc: u64,
spend: &dyn Fn(u64) -> Result<(), String>,
) -> Result {
+ if !cover(acc, src, max_alloc, spend)? {
+ return Ok(false);
+ }
+ let Some(out) = acc.as_mut() else { return Ok(false) };
+ // Only the source's rows and columns change.
+ let (sw, x0, y0) = (src.width.max(1), (src.left - out.left) as usize, (src.top - out.top) as usize);
+ for (k, s) in src.px.iter().enumerate() {
+ let Some(p) = out.px.get_mut((y0 + k / sw) * out.width + x0 + k % sw) else { continue };
+ let a = coverage(blend, s[3] * opacity, src.left + (k % sw) as i64, src.top + (k / sw) as i64, record);
+ *p = over(blend, *p, [s[0], s[1], s[2], a]);
+ }
+ Ok(true)
+}
+
+/// `knock` (of record `record`, in `blend`, with its `fill` and `opacity`), a layer with a shallow
+/// knockout, knocking out `acc`, on a canvas covering both, as [`blend_onto`] makes it. Where
+/// `knock` has pixels, its transparency is the share of `acc` cleared and replaced by its color at
+/// `fill`; `opacity` then fades that back toward `acc` (in Dissolve, each pixel is cleared fully
+/// or not at all, at the share its transparency times `opacity` gives). `false`, with `acc` as it
+/// was, when the canvases would take more than `max_alloc` bytes.
+#[allow(clippy::too_many_arguments)]
+fn knock_onto(
+ acc: &mut Option,
+ knock: &Canvas,
+ blend: Blend,
+ fill: f32,
+ opacity: f32,
+ record: usize,
+ max_alloc: u64,
+ spend: &dyn Fn(u64) -> Result<(), String>,
+) -> Result {
+ if !cover(acc, knock, max_alloc, spend)? {
+ return Ok(false);
+ }
+ let Some(out) = acc.as_mut() else { return Ok(false) };
+ let (fill, opacity) = (fill.clamp(0.0, 1.0), opacity.clamp(0.0, 1.0));
+ let (kw, x0, y0) = (knock.width.max(1), (knock.left - out.left) as usize, (knock.top - out.top) as usize);
+ for (k, s) in knock.px.iter().enumerate() {
+ let Some(p) = out.px.get_mut((y0 + k / kw) * out.width + x0 + k % kw) else { continue };
+ let t = coverage(blend, s[3].clamp(0.0, 1.0) * opacity, knock.left + (k % kw) as i64, knock.top + (k / kw) as i64, record);
+ let below = p[3].clamp(0.0, 1.0);
+ let alpha = (1.0 - t) * below + t * fill;
+ if alpha <= 0.0 {
+ *p = [0.0; 4];
+ continue;
+ }
+ let mix = |i: usize| ((1.0 - t) * below * p[i] + t * fill * s[i]) / alpha;
+ *p = [mix(0), mix(1), mix(2), alpha];
+ }
+ Ok(true)
+}
+
+/// Does `knock`, as [`knock_onto`] takes it, clear any of a pixel of `below` that has paint?
+fn cuts_paint(below: &Canvas, knock: &Canvas, blend: Blend, opacity: f32, record: usize) -> bool {
+ let (kw, opacity) = (knock.width.max(1), opacity.clamp(0.0, 1.0));
+ knock.px.iter().enumerate().any(|(k, s)| {
+ let (x, y) = (knock.left + (k % kw) as i64, knock.top + (k / kw) as i64);
+ below.get(x, y).is_some_and(|b| b[3] > 0.0) && coverage(blend, s[3].clamp(0.0, 1.0) * opacity, x, y, record) > 0.0
+ })
+}
+
+/// `acc` grown, when it doesn't already, to a canvas covering itself and `src` (a new one counted
+/// with `spend`). `false`, with `acc` as it was, when the canvases held, `acc` and `src` and a
+/// larger canvas when one is needed, would take more than `max_alloc` bytes.
+fn cover(acc: &mut Option, src: &Canvas, max_alloc: u64, spend: &dyn Fn(u64) -> Result<(), String>) -> Result {
let (mut left, mut top, mut right, mut bottom) = (src.left, src.top, src.left + src.width as i64, src.top + src.height as i64);
if let Some(a) = acc.as_ref() {
left = left.min(a.left);
@@ -1475,14 +1980,6 @@ fn blend_onto(
}
*acc = Some(out);
}
- let Some(out) = acc.as_mut() else { return Ok(false) };
- // Only the source's rows and columns change.
- let (sw, x0, y0) = (src.width.max(1), (src.left - left) as usize, (src.top - top) as usize);
- for (k, s) in src.px.iter().enumerate() {
- let Some(p) = out.px.get_mut((y0 + k / sw) * width + x0 + k % sw) else { continue };
- let a = coverage(blend, s[3] * opacity, src.left + (k % sw) as i64, src.top + (k / sw) as i64, record);
- *p = over(blend, *p, [s[0], s[1], s[2], a]);
- }
Ok(true)
}
@@ -1521,11 +2018,28 @@ pub(super) fn import(
layers: 0,
notes: Notes::default(),
noted: vec![false; records.len()],
+ noted_log: vec![],
skipped: vec![false; records.len()],
skip_log: vec![],
+ unknocked: vec![false; records.len()],
+ unknock_log: vec![],
+ clipped_out: vec![false; records.len()],
+ clipped_out_log: vec![],
+ unclipped: vec![false; records.len()],
+ unclip_log: vec![],
+ kept: vec![false; records.len()],
spent: Cell::new(0),
+ wasted: Cell::new(0),
+ trial: Cell::new(0),
+ painted: Cell::new(0),
+ blank: vec![None; records.len()],
+ laid_blank: vec![false; records.len()],
+ blank_log: vec![],
+ squeezed: 0,
};
- let layers = b.list(&items)?;
+ let layers = b.list(&items, Level::Top)?;
+ // A drawing for a knockout or a clip leaves hidden layers out; those that came in anyway aren't.
+ b.notes.hidden = b.skipped.iter().zip(&b.kept).filter(|&(s, k)| *s && !*k).count();
let Builder { mut doc, notes, .. } = b;
if !layers.is_empty() {
doc.layers = layers;
diff --git a/crates/engine/src/cmd/fileio/tests_psdlayers.rs b/crates/engine/src/cmd/fileio/tests_psdlayers.rs
index 6c227c0e17..d5dccfd662 100644
--- a/crates/engine/src/cmd/fileio/tests_psdlayers.rs
+++ b/crates/engine/src/cmd/fileio/tests_psdlayers.rs
@@ -646,6 +646,453 @@ fn dissolve_layers_merge_as_opaque_or_transparent_pixels() {
assert!((32..=96).contains(&red), "{red} of 256 pixels show the lower layer: {r}");
}
+/// A layer with a Knockout value of `knko` and a fill opacity of `fill`.
+fn knockout(l: L, knko: u8, fill: u8) -> L {
+ let mut l = l;
+ l.blocks.push((*b"knko", vec![knko, 0, 0, 0]));
+ l.blocks.push((*b"iOpa", vec![fill]));
+ l
+}
+
+/// A green layer under a group of `group_blend` holding a red layer and `cut` above it.
+fn knockout_stack(group_blend: &'static [u8; 4], cut: L) -> Vec {
+ vec![
+ layer("Outside", [0, 0, 4, 4], [0, 255, 0, 255]),
+ group_end(),
+ layer("Lower", [0, 0, 4, 4], [255, 0, 0, 255]),
+ cut,
+ group("Group", group_blend),
+ ]
+}
+
+/// The names of the document's layers, and of the layers in its second one.
+fn knockout_names(s: &Session) -> (Vec, Vec) {
+ let d = &s.doc().unwrap().doc;
+ let names = |ls: &[std::sync::Arc]| ls.iter().map(|l| name(l).to_string()).collect::>();
+ (names(&d.layers), d.layers.get(1).and_then(|g| g.children()).map_or(vec![], |c| names(c)))
+}
+
+/// A layer with a shallow knockout in a group merges with the layers below it in the group: its
+/// shape clears them to transparency, it draws there at its fill opacity, and its opacity fades
+/// that. What is outside the group stays a layer of its own and shows through.
+#[test]
+fn knockout_layers_merge_with_the_layers_below_them_in_their_group() {
+ let cut = |fill: u8, opacity: u8| knockout(L { opacity, ..layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]) }, 1, fill);
+ for (fill, opacity, at_cut) in [(0, 255, [0, 0, 0, 0]), (128, 255, [0, 0, 255, 128]), (0, 128, [255, 0, 0, 127]), (255, 255, [0, 0, 255, 255])] {
+ for group_blend in [b"norm", b"pass"] {
+ let (s, r) = open(&file(4, 4, &knockout_stack(group_blend, cut(fill, opacity)), 8, false, false), json!({}));
+ assert_eq!(r["warnings"], json!([]), "{r}");
+ let (top, inner) = knockout_names(&s);
+ assert_eq!((top, inner), (vec!["Outside".to_string(), "Group".into()], vec!["Lower + Cut".to_string()]), "{fill} {opacity}");
+ let d = &s.doc().unwrap().doc;
+ assert_eq!(d.layers[1].isolate, group_blend == b"norm");
+ let ((x, y), px) = image_of(&s, &d.layers[1].children().unwrap()[0]);
+ assert_eq!(((x, y), px.dimensions()), ((0.0, 0.0), (4, 4)));
+ assert_eq!((px.get_pixel(1, 1).0, px.get_pixel(3, 3).0), (at_cut, [255, 0, 0, 255]), "{fill} {opacity}");
+ }
+ }
+ // A layer mask shapes the cut: where it hides the layer, nothing below is cleared.
+ let mut masked = cut(0, 255);
+ masked.mask = Some(([0, 0, 1, 1], 255, 0, vec![0]));
+ let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", masked), 8, false, false), json!({}));
+ let px = image_of(&s, &s.doc().unwrap().doc.layers[1].children().unwrap()[0]).1;
+ assert_eq!((px.get_pixel(0, 0).0, px.get_pixel(1, 1).0), ([255, 0, 0, 255], [0, 0, 0, 0]), "{r}");
+ // Without a knockout (0), the layers stay apart.
+ let (s, r) =
+ open(&file(4, 4, &knockout_stack(b"norm", knockout(layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]), 0, 0)), 8, false, false), json!({}));
+ assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([])), "{r}");
+}
+
+/// The knockouts this import doesn't apply come in as layers, counted in a warning: at the top level,
+/// on a clipped layer, and with a Knockout value other than 1. Hidden ones that would need the merge
+/// are left out; one that draws nothing, or nothing below it, merges nothing.
+#[test]
+fn knockouts_that_arent_applied_are_said() {
+ const UNAPPLIED: &str = "the knockout of 1 layer wasn't applied";
+ let cut = |l: L, knko: u8| knockout(l, knko, 0);
+ let blue = || layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]);
+ // At the top level.
+ let layers = [layer("Lower", [0, 0, 4, 4], [255, 0, 0, 255]), cut(blue(), 1)];
+ let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({}));
+ assert_eq!((knockout_names(&s).0, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}");
+ // Another Knockout value, and a clipped layer, in a group.
+ let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", cut(blue(), 2)), 8, false, false), json!({}));
+ assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}");
+ let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", cut(L { clipped: true, ..blue() }, 1)), 8, false, false), json!({}));
+ assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower + Cut".to_string()], &json!([UNAPPLIED])), "{r}");
+ // In a pass-through group, a layer below it, or the knockout itself, in another mode blends with
+ // what is outside the group: the layers stay apart, and the lower one still multiplies the green
+ // outside. In an isolated group they merge.
+ let mut multiply = knockout_stack(b"pass", cut(blue(), 1));
+ multiply[2].blend = b"mul ";
+ let (s, r) = open(&file(4, 4, &multiply, 8, false, false), json!({}));
+ assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}");
+ assert_eq!(s.doc().unwrap().doc.layers[1].children().unwrap()[0].blend, BlendMode::Multiply);
+ let (s, r) = open(&file(4, 4, &knockout_stack(b"pass", cut(L { blend: b"mul ", ..blue() }, 1)), 8, false, false), json!({}));
+ assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string(), "Cut".into()], &json!([UNAPPLIED])), "{r}");
+ multiply[4] = group("Group", b"norm");
+ let (s, r) = open(&file(4, 4, &multiply, 8, false, false), json!({}));
+ assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower + Cut".to_string()], &json!([])), "{r}");
+ // A hidden knockout would need the merge: left out, hidden layers asked for or not.
+ for hidden in [false, true] {
+ let (s, r) =
+ open(&file(4, 4, &knockout_stack(b"norm", cut(L { hidden: true, ..blue() }, 1)), 8, false, false), json!({"hiddenLayers": hidden}));
+ assert_eq!((knockout_names(&s).1, &r["warnings"]), (vec!["Lower".to_string()], &json!([HIDDEN_1])), "{hidden}: {r}");
+ }
+ // One that stores no pixels or only transparent ones cuts nothing, and merges nothing.
+ for (l, inner) in [(L { bare: true, ..blue() }, vec!["Lower"]), (layer("Cut", [0, 0, 2, 2], [0, 0, 255, 0]), vec!["Lower", "Cut"])] {
+ let (s, r) = open(&file(4, 4, &knockout_stack(b"norm", cut(l, 1)), 8, false, false), json!({}));
+ assert_eq!((knockout_names(&s).1, &r["warnings"]), (inner.iter().map(|n| n.to_string()).collect(), &json!([])), "{r}");
+ }
+ // Nothing below it in its group: it comes in as a layer.
+ let layers = [group_end(), cut(blue(), 1), group("Group", b"norm"), layer("Over", [0, 0, 1, 1], [9, 9, 9, 255])];
+ let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({}));
+ let d = &s.doc().unwrap().doc;
+ assert_eq!(d.layers[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Cut"], "{r}");
+ assert_eq!(r["warnings"], json!([]), "{r}");
+}
+
+/// A knockout that changes nothing below it leaves the layers apart, hidden ones included: one at 0
+/// opacity, one at 0 fill over layers that are transparent or beside their painted pixels, and one
+/// whose layer mask hides all of it. At 0 fill over painted layers, and
+/// at a fill over transparent ones, it still merges. A knockout at 0 fill over a transparent layer
+/// stays apart without a warning when their merge would need more memory than allowed.
+#[test]
+fn knockouts_that_change_nothing_keep_the_layers_apart() {
+ let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
+ let layers = [
+ group_end(),
+ layer("Lower", [0, 0, 2, 2], [255, 0, 0, 0]),
+ knockout(layer("Cut", [2, 2, 4, 4], [0, 0, 255, 255]), 1, 0),
+ group("Group", b"norm"),
+ ];
+ // The two 2 × 2 layers drawn together fit 256 bytes, but not the 4 × 4 canvas covering both.
+ let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 256, cms).unwrap().unwrap();
+ assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Lower", "Cut"]);
+ assert!(warnings.is_empty(), "{warnings:?}");
+ let lower = |alpha: u8| layer("Lower", [0, 0, 4, 4], [255, 0, 0, alpha]);
+ let hidden = L { hidden: true, ..layer("Hidden", [0, 0, 4, 4], [0, 255, 0, 255]) };
+ let cut = |fill: u8, opacity: u8| knockout(L { opacity, ..layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]) }, 1, fill);
+ let inner = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(vec![], |c| c.iter().map(|l| name(l).to_string()).collect::>());
+ for (alpha, fill, opacity, apart) in [(255, 0, 0, true), (0, 0, 255, true), (255, 0, 255, false), (0, 128, 255, false)] {
+ let layers = [group_end(), lower(alpha), hidden.clone(), cut(fill, opacity), group("Group", b"norm")];
+ let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true}));
+ let (names, warnings) = if apart { (vec!["Lower", "Hidden", "Cut"], json!([])) } else { (vec!["Lower + Cut"], json!([HIDDEN_1])) };
+ assert_eq!((inner(&s), &r["warnings"]), (names.iter().map(|n| n.to_string()).collect(), &warnings), "{alpha} {fill} {opacity}: {r}");
+ }
+ // A hidden knockout that needs no merge comes in with hidden layers: at 0 opacity, with nothing
+ // below it in its group, at 0 fill beside the painted pixels below it, and with a layer mask that
+ // hides all of it.
+ let hidden_cut = |opacity: u8| L { hidden: true, ..cut(0, opacity) };
+ let beside = L { hidden: true, ..knockout(layer("Cut", [0, 0, 2, 2], [0, 0, 255, 255]), 1, 0) };
+ let masked = L { hidden: true, mask: Some(([0, 0, 2, 2], 0, 0, vec![0; 4])), ..cut(255, 255) };
+ for (layers, names) in [
+ (vec![group_end(), lower(255), hidden_cut(0), group("Group", b"norm")], vec!["Lower", "Cut"]),
+ (vec![group_end(), hidden_cut(255), group("Group", b"norm")], vec!["Cut"]),
+ (vec![group_end(), layer("Lower", [2, 2, 4, 4], [255, 0, 0, 255]), beside, group("Group", b"norm")], vec!["Lower", "Cut"]),
+ (vec![group_end(), lower(255), masked.clone(), group("Group", b"norm")], vec!["Lower", "Cut"]),
+ ] {
+ let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true}));
+ assert_eq!((inner(&s), &r["warnings"]), (names.iter().map(|n| n.to_string()).collect(), &json!([])), "{r}");
+ }
+ // With the mask switched off it would need the merge, and is left out.
+ let unmasked = L { mask: Some(([0, 0, 2, 2], 0, 2, vec![0; 4])), ..masked };
+ let (s, r) = open(&file(4, 4, &[group_end(), lower(255), unmasked, group("Group", b"norm")], 8, false, false), json!({"hiddenLayers": true}));
+ assert_eq!((inner(&s), &r["warnings"]), (vec!["Lower".to_string()], &json!([HIDDEN_1])), "{r}");
+ // A hidden knockout group that would need the merge is counted once, as a hidden layer left out:
+ // its type layer and its own hidden layer aren't counted.
+ let mut words = layer("Words", [0, 0, 2, 2], [0, 0, 0, 255]);
+ words.blocks.push((*b"TySh", vec![0; 4]));
+ let layers = [
+ group_end(),
+ lower(255),
+ group_end(),
+ words.clone(),
+ L { hidden: true, ..layer("Inner", [0, 0, 2, 2], [0, 0, 255, 255]) },
+ L { hidden: true, ..knockout(group("Cut", b"norm"), 1, 255) },
+ group("Group", b"norm"),
+ ];
+ let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true}));
+ assert_eq!((inner(&s), &r["warnings"]), (vec!["Lower".to_string()], &json!([HIDDEN_1])), "{r}");
+ // One whose layer mask hides all of it needs no merge, but a knockout above it merges the layers
+ // and leaves it out: it is counted once, without its type layer.
+ let layers = [
+ group_end(),
+ lower(255),
+ group_end(),
+ words,
+ L { hidden: true, mask: Some(([0, 0, 2, 2], 0, 0, vec![0; 4])), ..knockout(group("Masked", b"norm"), 1, 255) },
+ cut(0, 255),
+ group("Group", b"norm"),
+ ];
+ let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true}));
+ assert_eq!((inner(&s), &r["warnings"]), (vec!["Lower + Cut".to_string()], &json!([HIDDEN_1])), "{r}");
+}
+
+/// With hidden layers asked for, the hidden layers of a group drawn for a knockout or a clip that
+/// isn't made come in, and aren't counted as left out: a knockout group over a layer that stores no
+/// pixels, and a clipped group whose merge needs more memory than allowed.
+#[test]
+fn hidden_layers_of_a_group_drawn_for_a_merge_not_made_come_in() {
+ let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
+ let children = |l: &Node| l.children().map_or(vec![], |c| c.iter().map(|l| (name(l).to_string(), l.visible)).collect::>());
+ let shown_and_hidden =
+ || [group_end(), layer("Shown", [0, 0, 2, 2], [0, 0, 255, 255]), L { hidden: true, ..layer("Hidden", [2, 2, 4, 4], [0, 255, 0, 255]) }];
+ let both = vec![("Shown".to_string(), true), ("Hidden".to_string(), false)];
+ // A knockout group over a layer that stores no pixels.
+ let mut layers = vec![group_end(), L { bare: true, ..layer("Lower", [0, 0, 2, 2], [0; 4]) }];
+ layers.extend(shown_and_hidden());
+ layers.extend([knockout(group("Cut", b"norm"), 1, 255), group("Group", b"norm")]);
+ let (s, r) = open(&file(4, 4, &layers, 8, false, false), json!({"hiddenLayers": true}));
+ let d = &s.doc().unwrap().doc;
+ let cut = &d.layers[0].children().unwrap()[0];
+ assert_eq!((name(cut), children(cut), &r["warnings"]), ("Cut", both.clone(), &json!([])), "{r}");
+ // A clipped group whose merge with its base doesn't fit 320 bytes.
+ let mut layers = vec![layer("Base", [0, 0, 2, 2], [255, 0, 0, 255])];
+ layers.extend(shown_and_hidden());
+ layers[2].rect = [0, 0, 4, 4];
+ layers.push(L { clipped: true, ..group("Clipped", b"norm") });
+ let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), true, 320, cms).unwrap().unwrap();
+ let clipped = &doc.layers[1];
+ assert_eq!((name(clipped), children(clipped)), ("Clipped", both), "{warnings:?}");
+ assert_eq!(warnings, ["1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed"]);
+}
+
+/// A knockout's merge whose canvases would need more memory than allowed leaves the layers apart,
+/// with a warning. One at 0 fill beside the painted pixels below it cuts nothing, and stays apart
+/// whatever the memory.
+#[test]
+fn a_knockout_merge_past_the_memory_allowed_leaves_the_layers_apart() {
+ let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
+ let stack = |cut: [i32; 4]| {
+ let layers = [
+ group_end(),
+ layer("Lower", [0, 0, 2, 2], [255, 0, 0, 255]),
+ knockout(layer("Cut", cut, [0, 0, 255, 255]), 1, 0),
+ group("Group", b"norm"),
+ ];
+ file(4, 4, &layers, 8, false, false)
+ };
+ let names = |doc: &vectorcraft_doc::Document| doc.layers[0].children().unwrap().iter().map(|c| name(c).to_string()).collect::>();
+ let f = stack([1, 1, 3, 3]);
+ // Each 2 × 2 layer fits 128 bytes (16 a pixel), but not the canvas of the layer below with the
+ // knockout's canvas held beside it.
+ let (doc, warnings) = psdlayers::import(&f, false, 128, cms).unwrap().unwrap();
+ assert_eq!(names(&doc), ["Lower", "Cut"]);
+ assert_eq!(warnings, ["the knockout of 1 layer wasn't applied"]);
+ let (doc, warnings) = psdlayers::import(&f, false, 1 << 20, cms).unwrap().unwrap();
+ assert_eq!(names(&doc), ["Lower + Cut"]);
+ assert!(warnings.is_empty(), "{warnings:?}");
+ for max_alloc in [128, 1 << 20] {
+ let (doc, warnings) = psdlayers::import(&stack([2, 2, 4, 4]), false, max_alloc, cms).unwrap().unwrap();
+ assert_eq!(names(&doc), ["Lower", "Cut"], "{max_alloc}");
+ assert!(warnings.is_empty(), "{max_alloc}: {warnings:?}");
+ }
+}
+
+/// A knockout that cuts nothing gives back what drawing the layers below it counted: here a
+/// knockout at 0 fill beside a group, whose own knockout doesn't fit 192 bytes while the outer
+/// knockout's canvas is held, but merges when the group comes in.
+#[test]
+fn a_knockout_that_cuts_nothing_doesnt_keep_what_drawing_below_it_counted() {
+ let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
+ let layers = [
+ group_end(),
+ group_end(),
+ layer("Opaque", [0, 0, 2, 2], [255, 0, 0, 255]),
+ knockout(layer("Inner cut", [0, 0, 1, 2], [0, 0, 255, 255]), 1, 0),
+ group("Inner", b"norm"),
+ knockout(layer("Outer cut", [2, 2, 4, 4], [0, 0, 255, 255]), 1, 0),
+ group("Outer", b"norm"),
+ ];
+ let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 192, cms).unwrap().unwrap();
+ let outer = doc.layers[0].children().unwrap();
+ assert_eq!(outer.iter().map(|c| name(c)).collect::>(), ["Inner", "Outer cut"], "{warnings:?}");
+ assert_eq!(outer[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Opaque + Inner cut"], "{warnings:?}");
+ assert!(warnings.is_empty(), "{warnings:?}");
+}
+
+/// A knockout merge that can't be made leaves the import the whole allowance for reading the layers
+/// apart: here the merge decodes 22 layers over one another before the layer beside them makes its
+/// canvas too large, which used up nearly all of eight times 64 KiB. The merge has that allowance
+/// also after five layers below the group were read, and a knockout at 0 fill over 22 transparent
+/// layers, which cuts no paint after they are drawn, leaves the same room.
+#[test]
+fn a_knockout_merge_not_made_leaves_room_to_read_the_layers() {
+ let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
+ let mut layers = vec![group_end()];
+ layers.extend((0..22).map(|_| layer("Lower", [0, 0, 32, 32], [255, 0, 0, 255])));
+ layers.push(layer("Beside", [0, 64, 32, 96], [0, 255, 0, 255]));
+ layers.extend([knockout(layer("Cut", [0, 0, 32, 32], [0, 0, 255, 255]), 1, 0), group("Group", b"norm")]);
+ let (doc, warnings) = psdlayers::import(&file(96, 32, &layers, 8, false, false), false, 64 << 10, cms).unwrap().unwrap();
+ assert_eq!(doc.layers[0].children().unwrap().len(), 24, "{warnings:?}");
+ assert_eq!(warnings, ["the knockout of 1 layer wasn't applied"]);
+ let mut after_five = vec![layer("Outside", [0, 0, 32, 32], [0, 0, 0, 255]); 5];
+ after_five.extend(layers);
+ let (doc, warnings) = psdlayers::import(&file(96, 32, &after_five, 8, false, false), false, 64 << 10, cms).unwrap().unwrap();
+ assert_eq!((doc.layers.len(), doc.layers[5].children().unwrap().len()), (6, 24), "{warnings:?}");
+ assert_eq!(warnings, ["the knockout of 1 layer wasn't applied"]);
+ let mut layers = vec![group_end()];
+ layers.extend((0..22).map(|_| layer("Lower", [0, 0, 32, 32], [255, 0, 0, 0])));
+ layers.extend([knockout(layer("Cut", [0, 0, 32, 32], [0, 0, 255, 255]), 1, 0), group("Group", b"norm")]);
+ let (doc, warnings) = psdlayers::import(&file(32, 32, &layers, 8, false, false), false, 64 << 10, cms).unwrap().unwrap();
+ assert_eq!(doc.layers[0].children().unwrap().len(), 23, "{warnings:?}");
+ assert!(warnings.is_empty(), "{warnings:?}");
+}
+
+/// A hidden knockout in a mode VectorCraft lacks is left out without being drawn, hidden layers
+/// asked for: here its pixels are larger than the memory allowed for one image.
+#[test]
+fn a_hidden_knockout_in_a_mode_vectorcraft_lacks_is_left_out_unread() {
+ let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
+ let layers = [
+ group_end(),
+ layer("Lower", [0, 0, 2, 2], [255, 0, 0, 255]),
+ L { hidden: true, blend: b"diss", ..knockout(layer("Cut", [0, 0, 8, 8], [0, 0, 255, 255]), 1, 255) },
+ group("Group", b"norm"),
+ ];
+ let (doc, warnings) = psdlayers::import(&file(8, 8, &layers, 8, false, false), true, 128, cms).unwrap().unwrap();
+ assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Lower"]);
+ assert_eq!(warnings, [HIDDEN_1]);
+}
+
+/// A Dissolve knockout at part opacity clears each pixel below it fully or not at all, at the share
+/// its opacity gives, as a Dissolve layer merges.
+#[test]
+fn a_dissolve_knockout_at_part_opacity_clears_whole_pixels() {
+ let cut = knockout(L { blend: b"diss", opacity: 128, ..layer("Cut", [0, 0, 16, 16], [0, 0, 255, 255]) }, 1, 0);
+ let layers = [group_end(), layer("Lower", [0, 0, 16, 16], [255, 0, 0, 255]), cut, group("Group", b"norm")];
+ let (s, r) = open(&file(16, 16, &layers, 8, false, false), json!({}));
+ let d = &s.doc().unwrap().doc;
+ let (_, px) = image_of(&s, &d.layers[0].children().unwrap()[0]);
+ assert!(px.pixels().all(|p| p.0 == [255, 0, 0, 255] || p.0[3] == 0), "{r}");
+ let red = px.pixels().filter(|p| p.0 == [255, 0, 0, 255]).count();
+ assert!((32..=224).contains(&red), "{red} of 256 pixels keep the lower layer: {r}");
+}
+
+/// The knockout of a layer that another is clipped to isn't applied, also when the clipped layer's
+/// merge with it needs more memory than allowed and the two come in apart.
+#[test]
+fn a_clipping_base_knockout_isnt_applied_when_its_clip_doesnt_fit() {
+ let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
+ // The 4 × 4 clipped layer and its 2 × 2 base don't fit 320 bytes together for the clip; the
+ // base's knockout merge with the 2 × 2 layer below would.
+ let layers = [
+ group_end(),
+ layer("Lower", [0, 0, 2, 2], [255, 0, 0, 255]),
+ knockout(layer("Base", [0, 0, 2, 2], [0, 0, 255, 255]), 1, 0),
+ L { clipped: true, ..layer("Clipped", [0, 0, 4, 4], [0, 255, 0, 255]) },
+ group("Group", b"norm"),
+ ];
+ let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 320, cms).unwrap().unwrap();
+ assert_eq!(doc.layers[0].children().unwrap().iter().map(|c| name(c)).collect::>(), ["Lower", "Base", "Clipped"], "{warnings:?}");
+ assert_eq!(
+ warnings,
+ ["the knockout of 1 layer wasn't applied", "1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed"]
+ );
+}
+
+/// A knockout group that comes in as a layer counts each layer clipped in it once in the warnings,
+/// though its layers are also drawn for the knockout: one clipped to a fill that isn't drawn, and
+/// one that a merge past the memory allowed leaves unclipped.
+#[test]
+fn a_knockout_group_that_comes_in_as_a_layer_counts_its_clipped_layers_once() {
+ let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
+ let empty = L { bare: true, ..layer("Empty", [0, 0, 2, 2], [0, 0, 0, 0]) };
+ // A fill whose shape is a vector mask, with a layer clipped to it: neither is drawn.
+ let mut soco = vec![0; 8];
+ for (key, v) in [(b"Rd doub", 255.0f64), (b"Grn doub", 0.0), (b"Bl doub", 51.0)] {
+ soco.extend(key);
+ soco.extend(v.to_be_bytes());
+ }
+ let mut outline = layer("Outline", [0, 0, 0, 0], [0; 4]);
+ outline.blocks.push((*b"SoCo", soco));
+ outline.blocks.push((*b"vsms", vec![0; 8]));
+ let on_outline = L { clipped: true, ..layer("On outline", [0, 0, 2, 2], [1, 1, 1, 255]) };
+ // Each 2 × 2 layer fits 128 bytes, and so do the two drawn together, but not the merge of the
+ // clipped one with the one below.
+ let base = layer("Base", [0, 0, 2, 2], [255, 0, 0, 255]);
+ let clipped = L { clipped: true, ..layer("Clipped", [0, 0, 2, 2], [0, 0, 255, 255]) };
+ for (inner, said) in [
+ (vec![outline, on_outline], "1 layer clipped to a fill layer that wasn't drawn was left out"),
+ (vec![base, clipped], "1 layer clipped to the layer below came in unclipped: the merge needs more memory than allowed"),
+ ] {
+ let mut layers = vec![layer("Outside", [0, 0, 4, 4], [0, 255, 0, 255]), group_end(), empty.clone(), group_end()];
+ layers.extend(inner);
+ layers.extend([knockout(group("Cut", b"norm"), 1, 255), group("Group", b"norm")]);
+ let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 128, cms).unwrap().unwrap();
+ assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Outside", "Group"]);
+ assert!(warnings.iter().any(|w| w == said), "{said}: {warnings:?}");
+ }
+}
+
+/// A pass-through group that draws nothing still counts what its layers count in it, also when it
+/// is drawn again inside a group that merges: a knockout above a Multiply layer isn't applied in a
+/// pass-through group, though drawn alone it would be.
+#[test]
+fn a_pass_through_group_that_draws_nothing_still_counts_its_unapplied_knockouts() {
+ let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
+ let empty = |name: &'static str, blend: &'static [u8; 4]| L { bare: true, blend, ..layer(name, [0, 0, 2, 2], [0, 0, 0, 0]) };
+ let layers = [
+ layer("Lower", [0, 0, 4, 4], [255, 0, 0, 255]),
+ group_end(),
+ empty("Empty", b"norm"),
+ group_end(),
+ empty("Multiplied", b"mul "),
+ knockout(empty("Cut", b"norm"), 1, 255),
+ knockout(group("Through", b"pass"), 1, 255),
+ group("Dissolved", b"diss"),
+ ];
+ let (doc, warnings) = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 1 << 20, cms).unwrap().unwrap();
+ assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Lower + Dissolved"], "{warnings:?}");
+ assert_eq!(warnings, ["the knockout of 1 layer wasn't applied".to_string(), psdlayers::MERGED_WARNING.replace("{modes}", "Dissolve")]);
+}
+
+/// A group that draws nothing is drawn once, however deep the groups like it nest: here each holds
+/// a layer that stores no pixels and, above it, the next group, with a knockout. The import walks
+/// at most as many layer lists as the file has records, with isolated groups, with groups that
+/// alternate with pass-through ones, with pass-through groups inside the outermost one (whose
+/// knockouts aren't applied), and with a layer in a mode VectorCraft lacks in each (a merge of
+/// nothing, a canvas without pixels).
+#[test]
+fn groups_that_draw_nothing_are_drawn_once_however_deep_they_nest() {
+ const LEVELS: usize = 48;
+ let cms = |c: [f32; 4]| [c[0], c[1], c[2]];
+ let empty = |name: &'static str, blend: &'static [u8; 4]| L { bare: true, blend, ..layer(name, [0, 0, 2, 2], [0, 0, 0, 0]) };
+ // Which levels are pass-through groups.
+ let none: fn(usize) -> bool = |_| false;
+ let odd: fn(usize) -> bool = |k| k % 2 == 1;
+ let all: fn(usize) -> bool = |k| k > 0;
+ for (case, pass, dissolve, warned) in [
+ ("isolated", none, false, vec![]),
+ ("alternating", odd, false, vec![]),
+ ("pass-through", all, false, vec![format!("the knockout of {} layers wasn't applied", LEVELS - 1)]),
+ ("dissolved", none, true, vec![psdlayers::MERGED_WARNING.replace("{modes}", "Dissolve")]),
+ ] {
+ let mut layers = vec![layer("Outside", [0, 0, 4, 4], [0, 255, 0, 255])];
+ for _ in 0..=LEVELS {
+ layers.push(group_end());
+ if dissolve {
+ layers.push(empty("Dissolved", b"diss"));
+ }
+ layers.push(empty("Empty", b"norm"));
+ }
+ for k in (0..=LEVELS).rev() {
+ let g = group("Group", if pass(k) { b"pass" } else { b"norm" });
+ layers.push(if k == 0 { g } else { knockout(g, 1, 255) });
+ }
+ psdlayers::WALKS.set((0, layers.len()));
+ let imported = psdlayers::import(&file(4, 4, &layers, 8, false, false), false, 1 << 20, cms);
+ let (walked, _) = psdlayers::WALKS.replace((0, usize::MAX));
+ let (doc, warnings) = imported.unwrap().unwrap();
+ assert!(walked <= layers.len(), "{case}: {walked} walks for {} records", layers.len());
+ assert_eq!(doc.layers.iter().map(|l| name(l)).collect::>(), ["Outside", "Group"], "{case}");
+ let mut expected = warned;
+ expected.push(vectorcraft_doc::depth::merged_note());
+ assert_eq!(warnings, expected, "{case}");
+ }
+}
+
#[test]
fn what_doesnt_come_in_is_said() {
let mut text = layer("Words", [0, 0, 2, 2], [0, 0, 0, 255]);
diff --git a/crates/engine/src/cmd/freeform.rs b/crates/engine/src/cmd/freeform.rs
index 71a5e36ccf..b238dd865a 100644
--- a/crates/engine/src/cmd/freeform.rs
+++ b/crates/engine/src/cmd/freeform.rs
@@ -19,7 +19,7 @@ pub fn specs() -> Vec {
"Add Freeform Point",
[],
None,
- "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (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 points); the points on a label's characters are not stored → {index}",
+ "{at: [x,y] (document coordinates), color? (default: the gradient's colour there; #rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %; the radius of pure colour around the point, a fraction of half the object's larger side; default 0), line?: true (join it to the selected point: extends the line ending there, else starts one), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point to the freeform gradient (an unplaced one keeps its automatic points first) and select it. On a path directly in a graph series, the graph also stores the edited gradient when it is on the topmost visible fill or stroke, as for the other paint.freeform edits (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 points); the points on a label's characters are not stored → {index}",
has_doc,
add_point
),
@@ -28,7 +28,7 @@ pub fn specs() -> Vec {
"Edit Freeform Point",
[],
None,
- "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
+ "{index? (default: the selected point), at?: [x,y] (document coordinates), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), opacity?: 0..1 (or 0..100), spread?: 0..1 (or 0..100 %), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} move or recolour a point of the freeform gradient → {index}",
has_doc,
set_point
),
@@ -37,7 +37,7 @@ pub fn specs() -> Vec {
"Delete Freeform Point",
[],
None,
- "{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}",
+ "{index? (default: the selected point), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} remove a point (never the last one); lines through it close up around it and lines left with one point go → {index}",
has_doc,
delete_point
),
@@ -46,7 +46,7 @@ pub fn specs() -> Vec {
"Add Freeform Line",
[],
None,
- "{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}",
+ "{points: [index, …] (at least two), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} join points with a smooth line through them, in order → {line}",
has_doc,
add_line
),
@@ -55,7 +55,7 @@ pub fn specs() -> Vec {
"Split Freeform Line",
[],
None,
- "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}",
+ "{line: line index, segment: the segment from the line's point `segment` to the next, t?: 0..1 along it (default 0.5), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind; without one, a Live Paint group's faces take a fill edit and its edges take a stroke edit), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\"} add a point on a line there (colour, opacity and spread between the segment's ends) and select it → {index}",
has_doc,
split_line
),
@@ -182,8 +182,9 @@ fn edit(s: &mut Session, p: &Value, cmd: &str, mut f: impl FnMut(&mut Freefor
let item = item_target(s, p, cmd)?;
let stroke = edits_stroke(s, p, item, !s.fill_active, cmd)?;
let item = item.of_kind(s, !stroke);
- // The art of a graph design in a series keeps the design's gradient.
- let ids = super::appearance::without_design_art(&s.doc()?.doc, item.targets(s, p)?, cmd)?;
+ // The art of a graph design in a series keeps the design's gradient; a Live Paint group's fill is on its faces and its
+ // stroke on its edges.
+ let ids = super::appearance::without_design_art(&s.doc()?.doc, item.targets_for(s, p, !stroke)?, cmd)?;
if ids.is_empty() {
return Err(bad(cmd, "select an object with a freeform gradient"));
}
diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs
index 53e0f5456f..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. 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
),
@@ -33,7 +33,7 @@ pub fn specs() -> Vec {
"Gradient Vector",
[],
None,
- "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (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 the placement this command sets, fitted to each label",
+ "{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial, conic and diamond: the extent's height / width across the vector, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic or diamond gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.editGradient), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space). On a path directly in a graph series, the graph also stores the gradient with its placement relative to the path's box when it is on the topmost visible fill or stroke, and every path of the series takes it at the same place on its own box (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 the placement this command sets, fitted to each label; without item, a Live Paint group's faces take a fill edit and its edges take a stroke edit",
has_doc,
set_gradient_geom
),
@@ -92,6 +92,9 @@ fn select_stop(s: &mut Session, p: &Value) -> Result {
pub(crate) struct StopOwner {
doc: Option,
object: Option,
+ /// The object whose paint the active proxy shows: a Live Paint group without faces (or edges)
+ /// first in the selection shows the next object's.
+ source: Option,
part: bool,
fill: bool,
item: Option,
@@ -104,6 +107,7 @@ impl StopOwner {
Self {
doc: s.active,
object: st.and_then(|d| d.selection.objects.first().copied()),
+ source: s.proxy_source(!s.fill_active).map(|(n, _)| n.id),
part: st.is_some_and(|d| d.selection.symbol_part.is_some()),
fill: s.fill_active,
item: s.appearance_item(),
@@ -113,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).
@@ -539,10 +554,16 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result {
check_switches(p, &["reverse", "dither"], C)?;
check_numbers(p, &["angle"], C)?;
let item = item.of_kind(s, !stroke);
- let ids = item.targets(s, p)?;
- // Objects were given or selected, even when all of them are graph design art left out below: the stroke mode is then
- // not one for new art.
- let selected = !ids.is_empty();
+ let (ids, skipped) = item.targets_and_skipped(s, p, !stroke)?;
+ // 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") {
@@ -778,7 +799,10 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result {
let item = item.of_kind(s, !stroke);
let targets = match item {
ItemTarget::Top => {
- leaf_targets(s, &super::given_objects(s, p, C)?.map_or_else(|| selected_roots(s), |ids| Ok(outermost(&s.doc()?.doc, ids)))?)?
+ let roots = super::given_objects(s, p, C)?.map_or_else(|| selected_roots(s), |ids| Ok(outermost(&s.doc()?.doc, ids)))?;
+ // A Live Paint group's fill gradient is on its faces and its stroke gradient on its edges.
+ let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &roots, !stroke);
+ leaf_targets(s, &roots)?.into_iter().filter(|id| !skipped.contains(id)).collect()
}
_ => item.targets(s, p)?,
};
diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs
index 23b74f2fa6..d9d0905140 100644
--- a/crates/engine/src/cmd/newart.rs
+++ b/crates/engine/src/cmd/newart.rs
@@ -228,9 +228,11 @@ impl Session {
if !self.prefs.new_art_basic {
return;
}
- let has_paint = self
- .proxy_source(false)
- .is_some_and(|(n, _)| matches!(n.kind, NodeKind::Text(_)) || !n.appearance.items.is_empty() || n.extras().colorize.is_some());
+ // A Live Paint group with edges and no faces shows only a stroke.
+ let has_paint = [false, true].into_iter().any(|stroke| {
+ self.proxy_source(stroke)
+ .is_some_and(|(n, _)| matches!(n.kind, NodeKind::Text(_)) || !n.appearance.items.is_empty() || n.extras().colorize.is_some())
+ });
if !has_paint {
return;
}
diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs
index 2f80e3b6c6..e5ff38efa6 100644
--- a/crates/engine/src/cmd/object/commands.rs
+++ b/crates/engine/src/cmd/object/commands.rs
@@ -305,7 +305,7 @@ pub fn specs() -> Vec {
"Live Shape Properties",
[],
None,
- "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
+ "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
has_selection,
set_live_shape
),
diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs
index 02edf6193b..b2e69cc279 100644
--- a/crates/engine/src/cmd/object/shape.rs
+++ b/crates/engine/src/cmd/object/shape.rs
@@ -202,6 +202,16 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result {
// A polygon's Polygon Properties: its angle, radius or side length, Make Sides Equal.
let (polygon_angle, polygon_radius, side) = (angle("polygonAngle")?, length("polygonRadius")?, length("sideLength")?);
let equal = p.get("makeSidesEqual").and_then(Value::as_bool) == Some(true);
+ // A rectangle's Rectangle Angle and an ellipse's Ellipse Angle, as `polygonAngle` turns a polygon.
+ let (rectangle_angle, ellipse_angle) = (angle("rectangleAngle")?, angle("ellipseAngle")?);
+ // Whether a shape at `now` already stands at `a`: a turn the rounding of an earlier one left
+ // (89.999999999°, or 359.9999999999° against 0°) counts as no change.
+ let at_angle = |now: Option, a: f64| {
+ now.is_some_and(|n| {
+ let d = (n - a).rem_euclid(360.0);
+ d.min(360.0 - d) < 1e-9
+ })
+ };
// A line's Line Properties: its length (its first end stays) and its angle (about its midpoint).
// A line's length can reach across the whole canvas, past `MAX_COORD`: its ends are checked below.
let line_length = number("lineLength", |x| x > 0.0, "a length in points above 0")?;
@@ -249,12 +259,15 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result {
Some(l @ LiveShape::Polygon { sides: now, .. })
if !(sides.is_none_or(|n| n.clamp(3, 1000) == u64::from(*now))
&& (!equal || l.polygon_sides_equal())
- && polygon_angle.is_none_or(|a| l.polygon_angle() == Some(a))
+ && polygon_angle.is_none_or(|a| at_angle(l.polygon_angle(), a))
&& side.and_then(|len| l.polygon_radius_for_side(len)).or(polygon_radius).is_none_or(|r| l.polygon_radius() == Some(r))) =>
{
return false;
}
- Some(LiveShape::Ellipse { pie, .. }) if pie_of(*pie) != *pie => return false,
+ Some(l @ LiveShape::Ellipse { pie, .. }) if pie_of(*pie) != *pie || ellipse_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => {
+ return false;
+ }
+ Some(l @ LiveShape::Rectangle { .. }) if rectangle_angle.is_some_and(|a| !at_angle(l.shape_angle(), a)) => return false,
_ => {}
}
if relative_radii.is_some_and(|on| live.as_deref().map(|l| l.radii_relative()) != Some(on)) {
@@ -298,9 +311,18 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result {
}
*path = l.to_path();
}
- if let Some(l @ LiveShape::Ellipse { .. }) = live.as_deref_mut()
- && (pie_start.is_some() || pie_end.is_some() || invert)
+ if let Some(a) = rectangle_angle
+ && let Some(l @ LiveShape::Rectangle { .. }) = live.as_deref_mut()
{
+ l.set_shape_angle(a);
+ *path = l.to_path();
+ }
+ if let Some(l @ LiveShape::Ellipse { .. }) = live.as_deref_mut()
+ && (pie_start.is_some() || pie_end.is_some() || invert || ellipse_angle.is_some())
+ {
+ if let Some(a) = ellipse_angle {
+ l.set_shape_angle(a);
+ }
if let LiveShape::Ellipse { pie, .. } = l {
*pie = pie_of(*pie);
}
@@ -339,6 +361,11 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result {
for id in &ids {
super::pixelgrid::resnap(d, *id);
}
+ // A shape named in `ids` and not selected is not checked after the edit: one that a turn or
+ // a new radius would take past the coordinate limit is an error here, and nothing changes.
+ if !crate::sanity::objects_in_range(d, &ids) {
+ return Err(bad("object.setLiveShape", format!("coordinate out of range (limit ±{MAX_COORD} pt)")));
+ }
Ok(())
})?;
ok()
diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs
index 6115e18b81..071c5f9862 100644
--- a/crates/engine/src/cmd/paint.rs
+++ b/crates/engine/src/cmd/paint.rs
@@ -4,7 +4,9 @@ use std::borrow::Cow;
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Color, GradientPaint, Paint};
-use vectorcraft_doc::{Appearance, CharStyle, Document, GraySource, Node, NodeId, NodeKind};
+use vectorcraft_doc::appearance::{FillLayer, StrokeLayer};
+use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, GraySource, Node, NodeId, NodeKind};
+use vectorcraft_tools::builder::{edges, faces, is_live_paint};
use super::appearance::{ItemTarget, edit_items, edit_items_then, item_target, row_targets};
use super::gradient::{item_paint_bounds, place_paint, place_run_paint, run_paint_mut, run_stroke_weight, unplaced};
@@ -25,7 +27,7 @@ pub fn specs() -> Vec {
"Fill",
[],
None,
- "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. 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 color the bucket paints with) and the selection keeps its paint → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
+ "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. 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 color the bucket paints with) and the selection keeps its paint → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
has_doc,
|s, p| set_paint(s, p, true)
),
@@ -34,7 +36,7 @@ pub fn specs() -> Vec {
"Stroke",
[],
None,
- "{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
+ "{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke; without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
has_doc,
|s, p| { set_paint(s, p, false) }
),
@@ -43,7 +45,7 @@ pub fn specs() -> Vec {
"Swap Fill and Stroke",
[],
Some("Shift+X"),
- "{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change",
+ "{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ (a freeform gradient counts as differing), or that has no face or no edge, keeps its paint. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change",
has_doc,
swap
),
@@ -52,7 +54,7 @@ pub fn specs() -> Vec {
"Default Fill and Stroke",
[],
Some("D"),
- "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change",
+ "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, in place of their whole appearance and also when the Default Graphic Style is redefined, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change",
has_doc,
default_paint
),
@@ -100,7 +102,7 @@ pub fn proxy_specs() -> Vec {
"Invert",
[],
None,
- "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or 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), invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
+ "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or 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), invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md); no undo step when no color changes → {changed}",
has_doc,
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
),
@@ -109,7 +111,7 @@ pub fn proxy_specs() -> Vec {
"Complement",
[],
None,
- "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or 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), the default; no undo step when no color changes → {changed}",
+ "{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or 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), the default; no undo step when no color changes → {changed}",
has_doc,
|s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model())
),
@@ -158,7 +160,7 @@ pub fn proxy_specs() -> Vec {
"Fill and Stroke",
[],
None,
- "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors)}",
+ "{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors)}",
always,
proxies
),
@@ -182,10 +184,11 @@ impl Session {
/// The fill and stroke the Fill/Stroke proxies show: the Appearance panel's active item (in the
/// first selected object's own stack) for the proxy of its kind, else the first selected
- /// object's (a group's first painted object's; type: its first run's), else the defaults for
- /// new art. When the object whose fill the proxy shows is a gradient mesh with points picked
- /// ([`Session::fill_mesh_points`]), the fill is its first picked point's color, which a solid
- /// fill color changes.
+ /// object's (a group's first painted object's; a Live Paint group's first face's fill and first
+ /// edge's stroke, or the next selected object's when it has no face or edge; type: its first
+ /// run's), else the defaults for new art. When the object whose fill the proxy shows is a
+ /// gradient mesh with points picked ([`Session::fill_mesh_points`]), the fill is its first
+ /// picked point's color, which a solid fill color changes.
pub fn proxy_paints(&self) -> (Paint, Paint) {
let points = self.fill_mesh_points();
let show = |stroke: bool| match self.proxy_source(stroke) {
@@ -215,9 +218,20 @@ impl Session {
if first.appearance.item_of_kind(item, !stroke).is_some() {
return Some((Cow::Borrowed(first), item));
}
- let mut nodes = vec![];
- painted(first, true, &mut nodes);
- nodes.first().map(|n| (Cow::Borrowed(*n), None))
+ // A Live Paint group without faces (or edges) shows the next selected object's paint; any other
+ // object without a painted object shows the defaults for new art.
+ for id in st.selection.subjects() {
+ let Some(n) = st.doc.node(*id) else { continue };
+ let mut nodes = vec![];
+ painted(n, true, stroke, &mut nodes);
+ if let Some(n) = nodes.first() {
+ return Some((Cow::Borrowed(*n), None));
+ }
+ if !is_live_paint(n) {
+ return None;
+ }
+ }
+ None
}
pub(crate) fn remember_paint_now(&mut self, p: &Paint) {
@@ -258,21 +272,35 @@ fn same_in_proxy(a: &Paint, b: &Paint) -> bool {
}
}
+/// The ids of the faces and edges of `n` when it is a Live Paint group, else none.
+pub(crate) fn live_paint_parts(n: &Node) -> Vec {
+ if !is_live_paint(n) {
+ return vec![];
+ }
+ faces(n).into_iter().chain(edges(n)).map(|part| part.id).collect()
+}
+
/// The objects whose paints the proxies show for a selected `n`, the ones the paint commands
/// change ([`leaf_targets`]): groups and layers stand for their contents (and so do blends and
-/// other containers inside them), a compound path for its parts.
-pub(crate) fn painted<'a>(n: &'a Node, top: bool, out: &mut Vec<&'a Node>) {
+/// other containers inside them), a compound path for its parts. A Live Paint group stands for its
+/// faces in the fill proxy (`stroke` false) and for its edges in the stroke proxy, the parts a fill
+/// or a stroke given to it changes ([`live_paint_parts_skipped`]).
+pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&'a Node>) {
// A ruler guide has no paints.
if n.is_ruler_guide() {
return;
}
+ if is_live_paint(n) {
+ out.extend(if stroke { edges(n) } else { faces(n) }.into_iter().map(|part| &**part));
+ return;
+ }
let expand = match n.kind {
NodeKind::Group { .. } | NodeKind::Layer { .. } => true,
NodeKind::Compound { .. } => false,
_ => !top && n.is_container(),
};
if expand {
- n.children().into_iter().flatten().for_each(|c| painted(c, false, out));
+ n.children().into_iter().flatten().for_each(|c| painted(c, false, stroke, out));
} else {
out.push(n);
}
@@ -301,18 +329,31 @@ impl DocState {
}
// Looking the first object up builds the id cache when there is none.
let first = self.selection.objects.first().and_then(|id| self.doc.node(*id));
- let (mut selected, mut nodes) = (vec![], vec![]);
+ let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
+ // The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
+ let mut covered = std::collections::HashSet::new();
// Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each
// place it appears.
for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) {
#[cfg(test)]
tests::note_gathered();
selected.push(n);
- painted(n, true, &mut nodes);
+ if covered.contains(&n.id) {
+ continue;
+ }
+ covered.extend(live_paint_parts(n));
+ painted(n, true, false, &mut fills);
+ painted(n, true, true, &mut strokes);
}
let differ = |stroke: bool| {
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
- let set = if item.is_some() { &selected } else { &nodes };
+ let set = if item.is_some() {
+ &selected
+ } else if stroke {
+ &strokes
+ } else {
+ &fills
+ };
let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) {
c if c.is_empty() => vec![proxy_paint(n, stroke, item)],
c => c.into_iter().map(Paint::solid).collect(),
@@ -568,7 +609,7 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
}
// Resolve the requested targets before mutating defaults or the active proxy.
let item = item_target(s, p, cmd)?.of_kind(s, fill);
- let selected = item.targets(s, p)?;
+ let selected = item.targets_for(s, p, fill)?;
let ids = super::graph::paint_targets(&s.doc()?.doc, &selected);
let of = super::appearance::reference_of(s, p, item, cmd)?;
let paint = if span {
@@ -717,6 +758,68 @@ pub(crate) fn bucket_color_params(s: &Session, p: &Value, cmd: &str) -> Result Vec<(NodeId, Vec, Vec)> {
+ fn find<'a>(n: &'a Node, top: bool, out: &mut Vec<&'a Node>) {
+ let group = matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. });
+ if is_live_paint(n) {
+ out.push(n);
+ } else if (group || !top) && !n.is_compound_shape() && !matches!(n.kind, NodeKind::Compound { .. }) {
+ n.children().into_iter().flatten().for_each(|c| find(c, false, out));
+ }
+ }
+ let mut found = vec![];
+ for n in roots.iter().filter_map(|r| d.node(*r)) {
+ find(n, true, &mut found);
+ }
+ let mut seen = std::collections::HashSet::new();
+ found.retain(|g| seen.insert(g.id));
+ // A given or selected compound shape or compound path (or one inside a given or selected object) paints its members,
+ // also when one of them is given as well. A Live Paint group given inside one that is not given stays a Live Paint group.
+ let owns = |id: &NodeId| d.node(*id).is_some_and(|n| n.is_compound_shape() || matches!(n.kind, NodeKind::Compound { .. }));
+ let given: std::collections::HashSet = roots.iter().copied().collect();
+ found.retain(|g| {
+ !d.ancestry(g.id).is_some_and(|up| {
+ let outer = up.iter().position(|a| given.contains(a)).unwrap_or(up.len());
+ up.iter().skip(outer).any(|a| *a != g.id && owns(a))
+ })
+ });
+ let kept: std::collections::HashSet = super::appearance::drop_design_art(d, found.iter().map(|g| g.id).collect()).into_iter().collect();
+ let ids = |parts: Vec<&std::sync::Arc>| parts.into_iter().map(|part| part.id).collect();
+ found.into_iter().filter(|g| kept.contains(&g.id)).map(|g| (g.id, ids(faces(g)), ids(edges(g)))).collect()
+}
+
+/// Every object inside the Live Paint groups `groups` (faces, edges and the hidden source paths).
+fn inside_live_paint(d: &Document, groups: &[(NodeId, Vec, Vec)]) -> std::collections::HashSet {
+ let mut out = std::collections::HashSet::new();
+ for n in groups.iter().filter_map(|(g, _, _)| d.node(*g)) {
+ n.walk(&mut |c| {
+ if c.id != n.id {
+ out.insert(c.id);
+ }
+ });
+ }
+ out
+}
+
+/// The objects inside the Live Paint groups in `roots` (or inside them) that a fill (`fill`) or a
+/// stroke given to the whole group leaves as they are: a fill paints the group's faces only, and a
+/// stroke its edges only. Their edges (faces) and hidden source paths are left out.
+pub(crate) fn live_paint_parts_skipped(d: &Document, roots: &[NodeId], fill: bool) -> std::collections::HashSet {
+ let groups = live_paint_groups(d, roots);
+ let mut out = inside_live_paint(d, &groups);
+ for (_, faces, edges) in &groups {
+ for id in if fill { faces } else { edges } {
+ out.remove(id);
+ }
+ }
+ out
+}
+
/// The instance whose object is selected with Direct Selection, and that object's path
/// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands
/// then change that object. A bad `target` or `aligned` is refused as it is for any other selection.
@@ -1021,20 +1124,62 @@ pub(super) fn restore_unpainted_stroke(ap: &mut Appearance, index: Option
}
}
+/// The paint every one of `parts` has on top as its fill (`fill`) or stroke, swatch link included
+/// and gradient placement left out ([`unplaced`]: each part fits it to its own bounds), or None
+/// when they differ or there are none. A freeform gradient's points and their colors belong to the
+/// part they sit on, so a freeform gradient on any part counts as a paint the parts do not share.
+fn shared_paint(d: &Document, parts: &[NodeId], fill: bool) -> Option {
+ let mut paints = parts.iter().filter_map(|id| d.node(*id)).map(|n| if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() });
+ let first = paints.next()?;
+ let freeform =
+ |p: &Paint| matches!(p, Paint::Gradient(g) if g.gradient.kind == vectorcraft_color::GradientKind::Freeform || g.freeform.is_some());
+ if freeform(&first) {
+ return None;
+ }
+ let first = unplaced(&first);
+ paints.all(|p| !freeform(&p) && unplaced(&p) == first).then_some(first)
+}
+
fn swap(s: &mut Session, p: &Value) -> Result {
let bucket = bucket_color_params(s, p, "paint.swap")?;
let p = bucket.as_ref().unwrap_or(p);
let targets = paint_targets(s, p)?;
let given = !targets.is_empty();
- let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets);
+ // A whole Live Paint group: its faces take the stroke its edges share and its edges the fill its faces share.
+ let groups = live_paint_groups(&s.doc()?.doc, &super::targets(s, p)?);
+ let inside = inside_live_paint(&s.doc()?.doc, &groups);
+ let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets.into_iter().filter(|id| !inside.contains(id)).collect());
// Only design art was given or selected: nothing changes, the defaults included.
- if given && ids.is_empty() {
+ if given && ids.is_empty() && groups.is_empty() {
return ok();
}
- if !ids.is_empty() {
+ if !ids.is_empty() || !groups.is_empty() {
// When every object comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
+ // A group whose faces' fills (or edges' strokes) differ or are freeform gradients, or that has no face or no edge,
+ // keeps its paint.
+ let swaps: Vec<(&[NodeId], &[NodeId], Paint, Paint)> = groups
+ .iter()
+ .filter_map(|(_, faces, edges)| {
+ Some((faces.as_slice(), edges.as_slice(), shared_paint(&before, faces, true)?, shared_paint(&before, edges, false)?))
+ })
+ .collect();
+ let parts: Vec = groups.iter().flat_map(|(_, faces, edges)| faces.iter().chain(edges)).copied().collect();
super::overprint::edit_counted(s, "Swap Fill and Stroke", |d| {
+ for (faces, edges, fill, stroke) in &swaps {
+ for id in *faces {
+ if let Some(n) = d.node_mut(*id) {
+ n.appearance.set_fill(stroke.clone());
+ }
+ }
+ for id in *edges {
+ if let Some(n) = d.node_mut(*id) {
+ restore_unpainted_stroke(&mut n.appearance, None, fill);
+ n.appearance.set_stroke(fill.clone());
+ }
+ }
+ }
+ let parts_changed = super::appearance::count_changed(d, &before, &parts);
for id in &ids {
let Some(n) = d.node_mut(*id) else { continue };
if let NodeKind::Text(t) = &mut n.kind {
@@ -1054,7 +1199,7 @@ fn swap(s: &mut Session, p: &Value) -> Result {
// The swap writes the paint of the topmost fill and stroke, not their opacity.
let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (false, false), true, false);
let labels = super::graph::capture_label_changes(&before, d, &ids, false, None);
- Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels))
+ Ok(super::appearance::count_changed(d, &before, &ids) + parts_changed + usize::from(kept || labels))
})?;
}
if s.paint.stroke.is_none() && !s.paint.fill.is_none() && s.paint.stroke_width == 0.0 {
@@ -1064,22 +1209,44 @@ fn swap(s: &mut Session, p: &Value) -> Result {
ok()
}
+/// The weight of the stroke [`paint.default`](default_paint) gives the edges of a whole Live Paint group.
+const LIVE_PAINT_DEFAULT_WEIGHT: f64 = 0.5;
+
fn default_paint(s: &mut Session, p: &Value) -> Result {
let bucket = bucket_color_params(s, p, "paint.default")?;
let p = bucket.as_ref().unwrap_or(p);
let targets = paint_targets(s, p)?;
let given = !targets.is_empty();
- let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets);
+ // A whole Live Paint group: its faces lose their fill and its edges take a black 0.5 pt stroke.
+ let groups = live_paint_groups(&s.doc()?.doc, &super::targets(s, p)?);
+ let inside = inside_live_paint(&s.doc()?.doc, &groups);
+ let ids = super::appearance::drop_design_art(&s.doc()?.doc, targets.into_iter().filter(|id| !inside.contains(id)).collect());
// Only design art was given or selected: nothing changes, the defaults included.
- if given && ids.is_empty() {
+ if given && ids.is_empty() && groups.is_empty() {
return ok();
}
- if !ids.is_empty() {
+ if !ids.is_empty() || !groups.is_empty() {
// When every object comes out as it was, the document and its undo history stay as they are.
let before = s.doc()?.doc.clone();
// A redefined Default Graphic Style gives other art its fills, strokes and effects, placed on each object.
let style = super::newart::redefined_default_style(&before).cloned();
+ let parts: Vec = groups.iter().flat_map(|(_, faces, edges)| faces.iter().chain(edges)).copied().collect();
super::overprint::edit_counted(s, "Default Fill and Stroke", |d| {
+ for (_, faces, edges) in &groups {
+ let face = Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(Paint::None))], ..Appearance::default() };
+ let edge = Appearance {
+ items: vec![AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), LIVE_PAINT_DEFAULT_WEIGHT))],
+ ..Appearance::default()
+ };
+ for (ids, look) in [(faces, &face), (edges, &edge)] {
+ for id in ids {
+ if let Some(n) = d.node_mut(*id) {
+ n.appearance = look.clone().into();
+ }
+ }
+ }
+ }
+ let parts_changed = super::appearance::count_changed(d, &before, &parts);
for id in &ids {
let Some(n) = d.node_mut(*id) else { continue };
match &mut n.kind {
@@ -1106,10 +1273,20 @@ fn default_paint(s: &mut Session, p: &Value) -> Result {
st.stroke = Paint::None;
});
let lines = super::graph::capture_line_fill_stroke_rows(d, &ids);
- Ok(super::appearance::count_changed(d, &before, &ids) + usize::from(kept || labels || lines))
+ Ok(super::appearance::count_changed(d, &before, &ids) + parts_changed + usize::from(kept || labels || lines))
})?;
}
- super::newart::reset(s);
+ if ids.is_empty() && !groups.is_empty() {
+ // With only whole Live Paint groups given or selected, new art takes what their parts took, and nothing else.
+ s.paint = vectorcraft_tools::PaintDefaults {
+ fill: Paint::None,
+ stroke: Paint::solid(Color::BLACK),
+ stroke_width: LIVE_PAINT_DEFAULT_WEIGHT,
+ ..Default::default()
+ };
+ } else {
+ super::newart::reset(s);
+ }
ok()
}
@@ -1215,11 +1392,20 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
if roots.is_empty() {
return Ok(json!({ "changed": 0 }));
}
- let art = super::appearance::design_art_in(d, &roots).into_iter().collect();
- // The fill or stroke the proxy shows of each group among the roots, before the edit.
+ // A Live Paint group's fill is its faces' fills and its stroke its edges' strokes, also with `target: "contents"`;
+ // like any group, it recolors rows of its own as well.
+ let parts_skipped = live_paint_parts_skipped(d, &ids, !stroke);
+ let roots: Vec = roots.into_iter().filter(|id| !parts_skipped.contains(id)).collect();
+ if roots.is_empty() {
+ return Ok(json!({ "changed": 0 }));
+ }
+ let mut art: std::collections::HashSet = super::appearance::design_art_in(d, &roots).into_iter().collect();
+ art.extend(parts_skipped.iter().copied());
+ // The fill or stroke the proxy shows of each group among the roots, before the edit (a Live Paint group shows
+ // its faces' or edges').
let own = |d: &Document, id: NodeId| {
d.node(id)
- .filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }))
+ .filter(|n| matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !is_live_paint(n))
.and_then(|n| n.proxy_paint_only(stroke, None))
.cloned()
};
@@ -1237,7 +1423,8 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
shown_at = Some((*id, None));
break;
}
- if let Some(leaf) = super::appearance::drop_design_art(d, leaf_targets(s, &[*id])?).first() {
+ let leaves = leaf_targets(s, &[*id])?.into_iter().filter(|leaf| !parts_skipped.contains(leaf)).collect();
+ if let Some(leaf) = super::appearance::drop_design_art(d, leaves).first() {
shown_at = Some((*leaf, None));
break;
}
diff --git a/crates/engine/src/cmd/paint/tests.rs b/crates/engine/src/cmd/paint/tests.rs
index 3da5d73d9e..77e061e993 100644
--- a/crates/engine/src/cmd/paint/tests.rs
+++ b/crates/engine/src/cmd/paint/tests.rs
@@ -11,7 +11,7 @@ use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind};
use vectorcraft_geom::{Rect, shapes};
-use super::{painted, picked_colors, proxy_paint, same_in_proxy};
+use super::{live_paint_parts, painted, picked_colors, proxy_paint, same_in_proxy};
use crate::{DocState, Session};
thread_local! {
@@ -38,17 +38,28 @@ fn walked(st: &DocState, item: Option, points: &[(NodeId, Vec)]) -
return (false, false);
}
let ids: HashSet = st.selection.objects.iter().copied().collect();
- let (mut selected, mut nodes) = (vec![], vec![]);
+ let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
+ let mut covered = HashSet::new();
st.doc.walk(|n| {
if ids.contains(&n.id) {
selected.push(n);
- painted(n, true, &mut nodes);
+ if !covered.contains(&n.id) {
+ covered.extend(live_paint_parts(n));
+ painted(n, true, false, &mut fills);
+ painted(n, true, true, &mut strokes);
+ }
}
});
let first = st.selection.objects.first().and_then(|id| st.doc.node(*id));
let differ = |stroke: bool| {
let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke));
- let set = if item.is_some() { &selected } else { &nodes };
+ let set = if item.is_some() {
+ &selected
+ } else if stroke {
+ &strokes
+ } else {
+ &fills
+ };
let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) {
c if c.is_empty() => vec![proxy_paint(n, stroke, item)],
c => c.into_iter().map(Paint::solid).collect(),
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 7925c841d4..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",
@@ -463,6 +464,7 @@ pub(super) const ALLOWED: &[&str] = &[
"path.mirrorCut",
"path.moveAnchor",
"path.moveAnchors",
+ "path.quickPen",
"path.rectCut",
"path.removeAnchor",
"path.removeAnchors",
@@ -570,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/stroke.rs b/crates/engine/src/cmd/stroke.rs
index f43a63853e..f1e47b889a 100644
--- a/crates/engine/src/cmd/stroke.rs
+++ b/crates/engine/src/cmd/stroke.rs
@@ -8,9 +8,10 @@ use vectorcraft_doc::{
Unit, WidthProfile,
};
use vectorcraft_geom::PathData;
+use vectorcraft_tools::builder::is_live_paint;
use super::appearance::{ItemTarget, edit_items, item_target};
-use super::paint::painted;
+use super::paint::{live_paint_parts, live_paint_parts_skipped, painted};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ok, str_param};
use crate::DocState;
use crate::inspect::{ALIGNS, CAPS, JOINS, StrokeMixed, node_stroke, scale_layer};
@@ -22,7 +23,7 @@ pub fn specs() -> Vec {
"Stroke Options",
["Window", "Stroke"],
None,
- "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}",
+ "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}",
has_doc,
stroke_set
),
@@ -31,7 +32,7 @@ pub fn specs() -> Vec {
"Stroke Weight Up",
[],
Some("Cmd+Alt+."),
- "{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke are left alone. With nothing selected (and no ids), the weight of the next object drawn, and so while the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none). On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {objects}",
+ "{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke, and a Live Paint group's faces, are left alone. With nothing selected (and no ids), the weight of the next object drawn, and so while the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none). On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {objects}",
has_doc,
|s, p| stroke_step(s, p, true)
),
@@ -49,7 +50,7 @@ pub fn specs() -> Vec {
"Stroke Options",
[],
None,
- "{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn, and so while the Live Paint Bucket is the active tool and no ids, id, item or brush are given, a null ids or id counting as none)",
+ "{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn, and so while the Live Paint Bucket is the active tool and no ids, id, item or brush are given, a null ids or id counting as none; without item, a Live Paint group's edges take them and its faces are left alone)",
has_doc,
stroke_advanced
),
@@ -210,20 +211,25 @@ fn no_targets(ids: &[vectorcraft_doc::NodeId], p: &Value) -> bool {
/// The objects `stroke.set` edits with no `item`: a selected group or layer with a stroke row of
/// its own edits that row, as the Stroke panel does with the group targeted (#6739); the other
-/// targets reach their painted leaves, as before.
+/// targets reach their painted leaves, as before (a Live Paint group's edges, not its faces).
fn own_stroke_or_leaves(s: &Session, p: &Value) -> Result> {
let picked = super::targets(s, p)?;
let d = &s.doc()?.doc;
+ // A Live Paint group's stroke is its edges' strokes, also when it has a stroke row of its own.
let own = |id: &vectorcraft_doc::NodeId| {
d.node(*id).is_some_and(|n| {
- matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape() && n.appearance.stroke().is_some()
+ matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })
+ && !n.is_compound_shape()
+ && n.appearance.stroke().is_some()
+ && !is_live_paint(n)
})
};
let (mut out, rest): (Vec<_>, Vec<_>) = picked.into_iter().partition(own);
+ let faces = live_paint_parts_skipped(d, &rest, false);
// A leaf already listed is skipped; a set keeps this linear in the number of leaves.
let mut seen: std::collections::HashSet = out.iter().copied().collect();
for id in super::leaf_targets(s, &rest)? {
- if seen.insert(id) {
+ if !faces.contains(&id) && seen.insert(id) {
out.push(id);
}
}
@@ -246,11 +252,13 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result {
} else {
item.targets(s, p)?
};
- let new_art = bucket || no_targets(&ids, p);
- let given = !ids.is_empty();
+ // A Live Paint group without edges was still selected or given: the options do not go to new art.
+ let live_paint = !bucket && item == ItemTarget::Top && !live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, false).is_empty();
+ let new_art = bucket || (no_targets(&ids, p) && !live_paint);
+ let given = !ids.is_empty() || live_paint;
// The art of a graph design in a series keeps the design's stroke.
ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?;
- // With only design art, the weight for new art stays as it is too.
+ // With only design art, or only Live Paint groups without edges, the weight for new art stays as it is too.
let only_design_art = given && ids.is_empty();
if item == ItemTarget::Top {
// Images and symbol instances take no stroke from the panel.
@@ -388,8 +396,8 @@ fn stroke_step(s: &mut Session, p: &Value, up: bool) -> Result {
let bucket = bucket_p.is_some();
let p = bucket_p.as_ref().unwrap_or(p);
let item = item_target(s, p, c)?.of_kind(s, false);
- let ids = if bucket { vec![] } else { item.targets(s, p)? };
- if bucket || no_targets(&ids, p) {
+ let (ids, skipped) = if bucket { (vec![], false) } else { item.targets_and_skipped(s, p, false)? };
+ if bucket || (no_targets(&ids, p) && !skipped) {
let w = step_weight(s.paint.stroke_width, unit, up);
s.paint.stroke_width = w;
if let Some(st) = s.new_art_stroke_mut() {
@@ -428,8 +436,9 @@ impl Session {
/// The stroke the Stroke panel, the Control bar and the Properties panel show, picked as the
/// Stroke proxy picks its paint: the Appearance panel's active item when it is a stroke, else
- /// the first selected object's (a group's first painted object's) top stroke, type's first
- /// run's character stroke; with an object of a dynamic symbol instance selected
+ /// the first selected object's (a group's first painted object's, a Live Paint group's first
+ /// edge's, or the next selected object's when a Live Paint group has no edge) top stroke, type's
+ /// first run's character stroke; with an object of a dynamic symbol instance selected
/// ([`DocState::selected_symbol_part`]), that object's as the instance draws it; with nothing
/// selected, the next object drawn's ([`Session::new_art_stroke`]), and so while the Live Paint
/// Bucket is the active tool (the stroke it paints with). None without a document or the
@@ -447,9 +456,20 @@ impl Session {
if let Some(i) = first.appearance.item_of_kind(self.appearance_item(), false) {
return first.appearance.stroke_at(Some(i)).cloned();
}
- let mut nodes = vec![];
- painted(first, true, &mut nodes);
- node_stroke(nodes.first()?)
+ // A Live Paint group without edges shows the next selected object's stroke; any other object
+ // without a painted object shows none.
+ for id in &st.selection.objects {
+ let Some(n) = st.doc.node(*id) else { continue };
+ let mut nodes = vec![];
+ painted(n, true, true, &mut nodes);
+ if let Some(n) = nodes.first() {
+ return node_stroke(n);
+ }
+ if !is_live_paint(n) {
+ return None;
+ }
+ }
+ None
}
/// Do all the strokes that `stroke.set` edits without `ids` or `item` draw with a brush
@@ -508,12 +528,13 @@ impl DocState {
let part = self.selected_symbol_part();
let mut nodes = vec![];
if let Some(part) = &part {
- painted(part, true, &mut nodes);
+ painted(part, true, true, &mut nodes);
} else {
- for id in &self.selection.objects {
- if let Some(n) = self.doc.node(*id) {
- painted(n, true, &mut nodes);
- }
+ let selected: Vec<&Node> = self.selection.objects.iter().filter_map(|id| self.doc.node(*id)).collect();
+ // The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
+ let covered: std::collections::HashSet = selected.iter().flat_map(|n| live_paint_parts(n)).collect();
+ for n in selected.into_iter().filter(|n| !covered.contains(&n.id)) {
+ painted(n, true, true, &mut nodes);
}
}
let mut strokes = vec![];
@@ -594,8 +615,8 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result {
let bucket = bucket_p.is_some();
let p = bucket_p.as_ref().unwrap_or(p);
let item = item_target(s, p, C)?.of_kind(s, false);
- let ids = if bucket { vec![] } else { item.targets(s, p)? };
- let new_art = bucket || no_targets(&ids, p);
+ let (ids, skipped) = if bucket { (vec![], false) } else { item.targets_and_skipped(s, p, false)? };
+ let new_art = bucket || (no_targets(&ids, p) && !skipped);
// The art of a graph design in a series keeps the design's stroke.
let ids = super::appearance::drop_design_art_rows(s, ids, item, false, C)?;
let arrows_and_profile = |st: &mut StrokeLayer| {
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/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 d023d66088..0b785456a2 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -155,6 +155,7 @@ mod printps;
mod printtiling;
mod proxyitems;
mod puppetwarp;
+mod quickpen;
mod rasterfilters;
mod rastersettings;
mod recolor;
@@ -207,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..3ed90b8f2c 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,6 +120,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"energy-beams",
"dry-media",
"tech-circuit",
+ "engraving",
"arrows",
"image-brush"
]
@@ -169,6 +171,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"),
@@ -272,6 +275,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 +546,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 fade868bb6..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]
@@ -3784,6 +3846,419 @@ fn live_paint_fill_skips_hidden_faces() {
assert!(!node(&s, hidden).visible);
}
+/// The appearance of each face and each edge of Live Paint group `g`.
+fn part_looks(s: &Session, g: NodeId) -> (Vec, Vec) {
+ use vectorcraft_tools::builder::{edges, faces};
+ let n = node(s, g);
+ let looks = |parts: Vec<&Arc>| parts.iter().map(|p| (*p.appearance).clone()).collect();
+ (looks(faces(&n)), looks(edges(&n)))
+}
+
+/// The appearance of each hidden source path of Live Paint group `g`.
+fn sources_looks(s: &Session, g: NodeId) -> Vec {
+ let n = node(s, g);
+ let src = vectorcraft_tools::builder::sources(&n).unwrap();
+ src.children().unwrap().iter().map(|c| (*c.appearance).clone()).collect()
+}
+
+/// With a tool other than the Live Paint Bucket, a fill given to a whole selected Live Paint group
+/// paints its faces and leaves its edges as they are, and a stroke paints its edges and leaves its
+/// faces as they are. The Fill and Stroke proxies show the faces' fill and the edges' stroke.
+#[test]
+fn live_paint_group_fill_goes_to_faces_and_stroke_to_edges() {
+ let mut s = session();
+ let g = live(&mut s);
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ let (faces0, edges0) = part_looks(&s, g);
+ let magenta = Paint::solid(Color::from_hex("#ff00ff").unwrap());
+ let sources0 = sources_looks(&s, g);
+ assert_eq!(s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap()["objects"], faces0.len());
+ let (faces1, edges1) = part_looks(&s, g);
+ assert!(faces1.iter().all(|f| f.fill_paint() == magenta));
+ assert_eq!(edges1, edges0, "edges take no fill");
+ let p = s.execute("paint.proxies", &json!({})).unwrap();
+ assert_eq!(p["fillMixed"], false);
+ assert_eq!(p["fill"], serde_json::to_value(&magenta).unwrap());
+ let blue = Paint::solid(Color::from_hex("#0000ff").unwrap());
+ assert_eq!(s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap()["objects"], edges0.len());
+ assert_eq!(sources_looks(&s, g), sources0, "the hidden source paths keep their paint");
+ let (faces2, edges2) = part_looks(&s, g);
+ assert!(edges2.iter().all(|e| e.stroke_paint() == blue));
+ assert_eq!(faces2, faces1, "faces take no stroke");
+ let p = s.execute("paint.proxies", &json!({})).unwrap();
+ assert_eq!(p["strokeMixed"], false);
+ assert_eq!(p["stroke"], serde_json::to_value(&blue).unwrap());
+ // The same with the group given by id, and inside a selected group.
+ s.execute("paint.setFill", &json!({"ids": [g.0], "color": "#00ff00"})).unwrap();
+ let (faces3, edges3) = part_looks(&s, g);
+ assert_eq!(edges3, edges2, "edges take no fill given by id");
+ let green = Paint::solid(Color::from_hex("#00ff00").unwrap());
+ assert!(faces3.iter().all(|f| f.fill_paint() == green));
+ s.execute("object.group", &json!({"ids": [g.0]})).unwrap();
+ s.execute("paint.setStroke", &json!({"color": "#ff0000"})).unwrap();
+ let (faces4, edges4) = part_looks(&s, g);
+ assert_eq!(faces4, faces3, "faces of a grouped Live Paint group take no stroke");
+ assert!(edges4.iter().all(|e| e.stroke_paint() == Paint::solid(Color::from_hex("#ff0000").unwrap())));
+ // The bucket then paints one face, and nothing in the group draws a fill over it.
+ let r = s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50], "color": "#ffff00"})).unwrap();
+ let face = NodeId(r["face"].as_u64().unwrap());
+ assert_eq!(node(&s, face).appearance.fill_paint(), Paint::solid(Color::from_hex("#ffff00").unwrap()));
+ assert!(part_looks(&s, g).1.iter().all(|e| e.fill_paint().is_none()));
+}
+
+/// Swap Fill and Stroke on a whole selected Live Paint group gives its faces the stroke its edges
+/// share and its edges the fill its faces share; with faces of different fills, or without faces,
+/// it leaves the group as it is.
+#[test]
+fn live_paint_group_swap_trades_the_faces_fill_and_the_edges_stroke() {
+ let mut s = session();
+ let g = live(&mut s);
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ let sources0 = sources_looks(&s, g);
+ // The faces are red and blue: nothing on the group changes, in no undo step.
+ let (faces0, edges0) = part_looks(&s, g);
+ let depth = history_state(&s).0;
+ s.execute("paint.swap", &json!({})).unwrap();
+ assert_eq!(part_looks(&s, g), (faces0, edges0));
+ assert_eq!(history_state(&s).0, depth);
+ // One fill on every face: the faces take the edges' black, the edges the faces' red, at their weight.
+ s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
+ s.execute("stroke.set", &json!({"weight": 2})).unwrap();
+ s.execute("paint.swap", &json!({})).unwrap();
+ let (faces1, edges1) = part_looks(&s, g);
+ assert!(faces1.iter().all(|f| f.fill_paint() == Paint::solid(Color::BLACK)));
+ assert!(edges1.iter().all(|e| e.stroke_paint() == Paint::solid(Color::rgb(1.0, 0.0, 0.0)) && e.stroke_width() == 2.0));
+ assert!(edges1.iter().all(|e| e.fill_paint().is_none()), "edges take no fill");
+ assert_eq!(sources_looks(&s, g), sources0);
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert!(part_looks(&s, g).0.iter().all(|f| f.fill_paint() == Paint::solid(Color::rgb(1.0, 0.0, 0.0))), "one undo step");
+ // A gradient placed on each face's own bounds is one shared fill: the edges take it, fitted to each edge.
+ s.execute("paint.setFill", &json!({"gradient": {"aspect": 50}})).unwrap();
+ let placed: Vec = part_looks(&s, g).0.iter().map(|f| f.fill_paint()).collect();
+ assert!(placed.iter().all(|p| matches!(p, Paint::Gradient(gr) if gr.geom.is_some())) && placed[0] != placed[1]);
+ s.execute("paint.swap", &json!({})).unwrap();
+ let (faces2, edges2) = part_looks(&s, g);
+ assert!(faces2.iter().all(|f| f.fill_paint() == Paint::solid(Color::BLACK)));
+ assert!(edges2.iter().all(|e| matches!(e.stroke_paint(), Paint::Gradient(gr) if gr.geom.is_none() && gr.freeform.is_none())));
+ // A freeform gradient's points belong to its face: faces with freeform fills keep their paint, in no undo step.
+ s.execute("paint.setFill", &json!({"gradient": {"kind": "freeform"}})).unwrap();
+ assert!(
+ part_looks(&s, g)
+ .0
+ .iter()
+ .all(|f| matches!(f.fill_paint(), Paint::Gradient(gr) if gr.gradient.kind == vectorcraft_color::GradientKind::Freeform))
+ );
+ let looks = part_looks(&s, g);
+ let depth = history_state(&s).0;
+ s.execute("paint.swap", &json!({})).unwrap();
+ assert_eq!(part_looks(&s, g), looks);
+ assert_eq!(history_state(&s).0, depth);
+ // A group with edges and no faces keeps its paint.
+ let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 300, "x2": 100, "y2": 300})).unwrap()["id"].as_u64().unwrap());
+ let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap());
+ assert!(part_looks(&s, edges_only).0.is_empty());
+ s.execute("select.set", &json!({"ids": [edges_only.0]})).unwrap();
+ let looks = part_looks(&s, edges_only);
+ s.execute("paint.swap", &json!({})).unwrap();
+ assert_eq!(part_looks(&s, edges_only), looks);
+}
+
+/// Default Fill and Stroke on a whole selected Live Paint group leaves its faces with no fill and
+/// gives its edges a 0.5 pt black stroke, and new art takes the same; other art selected with it
+/// takes the white fill and 1 pt black stroke.
+#[test]
+fn live_paint_group_default_clears_the_faces_and_gives_the_edges_a_thin_black_stroke() {
+ let mut s = session();
+ let g = live(&mut s);
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ let sources0 = sources_looks(&s, g);
+ s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
+ s.execute("paint.default", &json!({})).unwrap();
+ let (faces, edges) = part_looks(&s, g);
+ assert!(faces.iter().all(|f| f.fill_paint().is_none() && f.stroke_paint().is_none()));
+ assert!(edges.iter().all(|e| e.stroke_paint() == Paint::solid(Color::BLACK) && e.stroke_width() == 0.5 && e.fill_paint().is_none()));
+ assert_eq!(sources_looks(&s, g), sources0);
+ assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width), (Paint::None, Paint::solid(Color::BLACK), 0.5));
+ let p = s.execute("paint.proxies", &json!({})).unwrap();
+ assert_eq!((p["fillMixed"].clone(), p["strokeMixed"].clone()), (json!(false), json!(false)));
+ // The next shape drawn has no fill and a 0.5 pt black stroke.
+ let next = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
+ let look = node(&s, next).appearance.clone();
+ assert!(!look.has_visible_fill());
+ assert_eq!((look.stroke_paint(), look.stroke_width()), (Paint::solid(Color::BLACK), 0.5));
+ // With a plain rectangle selected too, the rectangle and new art take the white fill and 1 pt black stroke.
+ let r = rect(&mut s, 300.0, 0.0, 50.0, 50.0);
+ s.execute("paint.setFill", &json!({"ids": [r.0], "color": "#00ff00"})).unwrap();
+ s.execute("select.set", &json!({"ids": [g.0, r.0]})).unwrap();
+ s.execute("paint.default", &json!({})).unwrap();
+ assert_eq!(node(&s, r).appearance.fill_paint(), Paint::solid(Color::WHITE));
+ assert_eq!(part_looks(&s, g), (faces.clone(), edges.clone()));
+ assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::solid(Color::WHITE), 1.0));
+ // A redefined Default Graphic Style goes to other art; the parts still take no fill and a 0.5 pt black stroke.
+ s.execute("select.set", &json!({"ids": [r.0]})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
+ s.execute("graphicStyle.redefine", &json!({"name": "Default Graphic Style"})).unwrap();
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
+ s.execute("stroke.set", &json!({"weight": 3})).unwrap();
+ s.execute("select.set", &json!({"ids": [g.0, r.0]})).unwrap();
+ s.execute("paint.default", &json!({})).unwrap();
+ assert_eq!(part_looks(&s, g), (faces, edges), "the parts do not take the redefined style");
+ assert_eq!(node(&s, r).appearance.fill_paint(), Paint::solid(Color::from_hex("#00ff00").unwrap()));
+}
+
+/// Invert on a whole selected Live Paint group recolors its faces' fills and leaves its edges and
+/// hidden source paths as they are.
+#[test]
+fn live_paint_group_invert_recolors_the_faces_fill() {
+ let mut s = session();
+ let g = live(&mut s);
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
+ let sources0 = sources_looks(&s, g);
+ let (_, edges0) = part_looks(&s, g);
+ s.execute("paint.invert", &json!({"stroke": false})).unwrap();
+ let (faces, edges) = part_looks(&s, g);
+ assert!(faces.iter().all(|f| f.fill_paint() == Paint::solid(Color::rgb(0.0, 1.0, 1.0))));
+ assert_eq!(edges, edges0);
+ assert_eq!(sources_looks(&s, g), sources0);
+ // The same with `target: "contents"`, for the stroke.
+ s.execute("paint.invert", &json!({"stroke": true, "target": "contents"})).unwrap();
+ let (faces1, edges1) = part_looks(&s, g);
+ assert_eq!(faces1, faces);
+ assert!(edges1.iter().all(|e| e.stroke_paint() == Paint::solid(Color::WHITE)));
+ assert_eq!(sources_looks(&s, g), sources0);
+ // A gradient edit of the fill goes to the faces only.
+ s.execute("paint.setFill", &json!({"gradient": {}})).unwrap();
+ s.execute("paint.editGradient", &json!({"stroke": false, "angle": 45})).unwrap();
+ let (faces2, edges2) = part_looks(&s, g);
+ assert!(faces2.iter().all(|f| matches!(f.fill_paint(), Paint::Gradient(_))));
+ assert_eq!(edges2, edges1, "edges take no fill gradient");
+ assert_eq!(sources_looks(&s, g), sources0);
+ // Selecting a Live Paint group with edges and no faces gives new art its edges' stroke.
+ let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 300, "x2": 100, "y2": 300})).unwrap()["id"].as_u64().unwrap());
+ let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap());
+ s.execute("paint.setStroke", &json!({"ids": [edges_only.0], "color": "#00ff00"})).unwrap();
+ s.execute("select.none", &json!({})).unwrap();
+ s.paint.stroke = Paint::None;
+ s.execute("select.set", &json!({"ids": [edges_only.0]})).unwrap();
+ assert_eq!(s.paint.stroke, Paint::solid(Color::from_hex("#00ff00").unwrap()));
+}
+
+/// A gradient vector or freeform point edit of a whole selected Live Paint group's fill changes its
+/// faces' gradients and leaves its edges and hidden source paths as they are.
+#[test]
+fn live_paint_group_gradient_vector_and_freeform_edits_change_its_faces() {
+ let mut s = session();
+ let g = live(&mut s);
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ s.execute("paint.setFill", &json!({"gradient": {}})).unwrap();
+ let sources0 = sources_looks(&s, g);
+ let (_, edges0) = part_looks(&s, g);
+ let face_ids: Vec = vectorcraft_tools::builder::faces(&node(&s, g)).iter().map(|f| f.id.0).collect();
+ let r = s.execute("paint.setGradientGeom", &json!({"stroke": false, "start": [0, 0], "end": [100, 0]})).unwrap();
+ let mut changed: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
+ changed.sort_unstable();
+ let mut faces = face_ids.clone();
+ faces.sort_unstable();
+ assert_eq!(changed, faces, "only the faces take the vector");
+ assert_eq!(part_looks(&s, g).1, edges0);
+ assert_eq!(sources_looks(&s, g), sources0);
+ s.execute("paint.setFill", &json!({"gradient": {"kind": "freeform"}})).unwrap();
+ s.execute("paint.freeform.addPoint", &json!({"stroke": false, "at": [25, 50], "color": "#00ff00"})).unwrap();
+ assert!(part_looks(&s, g).0.iter().all(|f| matches!(f.fill_paint(), Paint::Gradient(gr) if gr.freeform.is_some())));
+ assert_eq!(part_looks(&s, g).1, edges0);
+ assert_eq!(sources_looks(&s, g), sources0);
+}
+
+/// The Live Paint rules stop where a paint command stops: a Live Paint group in a compound shape or
+/// a blend keeps its parts' paint when the compound shape or blend takes the default, Invert
+/// remembers the faces' color the proxy shows, and a Live Paint group without faces lets the Fill
+/// proxy show the next selected object's fill, while an empty plain group does not.
+#[test]
+fn live_paint_group_rules_stop_where_paint_commands_stop() {
+ let mut s = session();
+ let g = live(&mut s);
+ let looks = part_looks(&s, g);
+ let r = rect(&mut s, 300.0, 0.0, 50.0, 50.0);
+ s.execute("select.set", &json!({"ids": [g.0, r.0]})).unwrap();
+ let c = NodeId(s.execute("object.compoundShape.make", &json!({"mode": "add"})).unwrap()["id"].as_u64().unwrap());
+ s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
+ s.execute("paint.default", &json!({})).unwrap();
+ s.execute("paint.swap", &json!({})).unwrap();
+ assert_eq!(part_looks(&s, g), looks, "a compound shape's member keeps its paint");
+ s.execute("paint.default", &json!({"ids": [c.0, g.0]})).unwrap();
+ assert_eq!(part_looks(&s, g), looks, "a compound shape's member given as well keeps its paint");
+ // Given alone, the member is a Live Paint group: a fill paints its faces and leaves its edges.
+ s.execute("paint.setFill", &json!({"ids": [g.0], "color": "#ff00ff"})).unwrap();
+ let (faces, edges) = part_looks(&s, g);
+ assert!(faces.iter().all(|f| f.fill_paint() == Paint::solid(Color::from_hex("#ff00ff").unwrap())));
+ assert_eq!(edges, looks.1, "the edges of a member given alone take no fill");
+
+ // A Live Paint group selected with one of its edges: the edge counts with the group.
+ let mut s = session();
+ let g = live(&mut s);
+ let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id;
+ s.execute("select.set", &json!({"ids": [g.0, edge.0]})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
+ assert_eq!(s.execute("paint.proxies", &json!({})).unwrap()["fillMixed"], false);
+ assert!(node(&s, edge).appearance.fill_paint().is_none(), "an edge selected with its group takes no fill");
+ // The same for an edge given in `ids` with its group.
+ s.execute("paint.setFill", &json!({"ids": [g.0, edge.0], "color": "#0000ff"})).unwrap();
+ assert!(node(&s, edge).appearance.fill_paint().is_none(), "an edge given with its group takes no fill");
+
+ // The same for a blend's key.
+ let mut s = session();
+ let g = live(&mut s);
+ let looks = part_looks(&s, g);
+ let r = rect(&mut s, 300.0, 0.0, 50.0, 50.0);
+ s.execute("select.set", &json!({"ids": [g.0, r.0]})).unwrap();
+ let b = NodeId(s.execute("object.blend.make", &json!({})).unwrap()["id"].as_u64().unwrap());
+ s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
+ s.execute("paint.default", &json!({})).unwrap();
+ s.execute("paint.swap", &json!({})).unwrap();
+ assert_eq!(part_looks(&s, g), looks, "a blend's key keeps its paint");
+
+ // A Live Paint group inside a selected group: Invert recolors its faces' fills only.
+ let mut s = session();
+ let g = live(&mut s);
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
+ let sources0 = sources_looks(&s, g);
+ let (_, edges0) = part_looks(&s, g);
+ s.execute("object.group", &json!({"ids": [g.0]})).unwrap();
+ s.execute("paint.invert", &json!({"stroke": false})).unwrap();
+ assert!(part_looks(&s, g).0.iter().all(|f| f.fill_paint() == Paint::solid(Color::rgb(0.0, 1.0, 1.0))));
+ assert_eq!(part_looks(&s, g).1, edges0);
+ assert_eq!(sources_looks(&s, g), sources0);
+
+ let mut s = session();
+ let g = live(&mut s);
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
+ s.edit("t", |d, _| {
+ d.node_mut(g).unwrap().appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0)));
+ Ok(())
+ })
+ .unwrap();
+ s.execute("paint.invert", &json!({"stroke": false})).unwrap();
+ // Like any group's, the group's own row is recolored too; the color remembered is the faces' one the proxy shows.
+ assert_eq!(node(&s, g).appearance.fill_paint(), Paint::solid(Color::rgb(1.0, 1.0, 0.0)));
+ assert!(part_looks(&s, g).0.iter().all(|f| f.fill_paint() == Paint::solid(Color::rgb(0.0, 1.0, 1.0))));
+ assert_eq!(s.last_solid, Color::rgb(0.0, 1.0, 1.0));
+
+ let mut s = session();
+ 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());
+ assert!(part_looks(&s, edges_only).0.is_empty());
+ let r = rect(&mut s, 300.0, 0.0, 50.0, 50.0);
+ set_fill(&mut s, r, Color::from_hex("#00ff00").unwrap());
+ s.execute("select.set", &json!({"ids": [edges_only.0, r.0]})).unwrap();
+ let p = s.execute("paint.proxies", &json!({})).unwrap();
+ assert_eq!(p["fill"], serde_json::to_value(Paint::solid(Color::from_hex("#00ff00").unwrap())).unwrap());
+ // The edges-only group shows its edges' stroke in the Stroke panel.
+ let edge_width = part_looks(&s, edges_only).1[0].stroke_width();
+ assert_eq!(s.shown_stroke().map(|st| st.width), Some(edge_width));
+
+ // Any other object with nothing painted in it first in the selection (a group left empty) shows
+ // the defaults for new art, not the next object's paint.
+ let inner = rect(&mut s, 0.0, 300.0, 50.0, 50.0);
+ let empty = NodeId(s.execute("object.group", &json!({"ids": [inner.0]})).unwrap()["id"].as_u64().unwrap());
+ s.edit("t", |d, _| {
+ d.children_mut(Some(empty)).unwrap().clear();
+ Ok(())
+ })
+ .unwrap();
+ s.execute("stroke.set", &json!({"ids": [r.0], "weight": 7})).unwrap();
+ s.paint.fill = Paint::None;
+ s.execute("select.set", &json!({"ids": [empty.0, r.0]})).unwrap();
+ let p = s.execute("paint.proxies", &json!({})).unwrap();
+ assert_eq!(p["fill"], serde_json::to_value(Paint::None).unwrap());
+ assert!(s.shown_stroke().is_none());
+}
+
+/// Stroke panel edits of a whole selected Live Paint group (a weight, a step up or down, options)
+/// change its edges and leave its faces as they are, and the panel shows the edges' stroke.
+#[test]
+fn live_paint_group_stroke_panel_edits_change_its_edges() {
+ let mut s = session();
+ let g = live(&mut s);
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ let (faces0, edges0) = part_looks(&s, g);
+ assert_eq!(s.execute("stroke.set", &json!({"weight": 5})).unwrap()["objects"], edges0.len());
+ let (faces1, edges1) = part_looks(&s, g);
+ assert_eq!(faces1, faces0, "faces take no stroke weight");
+ assert!(edges1.iter().all(|e| e.stroke().is_some_and(|st| st.width == 5.0)));
+ assert_eq!(s.shown_stroke().map(|st| st.width), Some(5.0));
+ assert!(!s.doc().unwrap().stroke_mixed().weight);
+ s.execute("stroke.weightUp", &json!({})).unwrap();
+ s.execute("stroke.set", &json!({"cap": "round"})).unwrap();
+ let (faces2, edges2) = part_looks(&s, g);
+ assert_eq!(faces2, faces0, "faces take no stroke step or cap");
+ assert!(edges2.iter().all(|e| e.stroke().is_some_and(|st| st.width == 6.0 && st.cap == LineCap::Round)));
+ // A stroke on the faces (from a file, say) leaves the panel showing the edges' stroke.
+ let face_ids: Vec = vectorcraft_tools::builder::faces(&node(&s, g)).iter().map(|f| f.id).collect();
+ s.edit("t", |d, _| {
+ for id in &face_ids {
+ let face = d.node_mut(*id).unwrap();
+ face.appearance.set_stroke(Paint::solid(Color::BLACK));
+ face.appearance.stroke_at_mut(None).unwrap().width = 2.0;
+ }
+ Ok(())
+ })
+ .unwrap();
+ assert_eq!(s.shown_stroke().map(|st| st.width), Some(6.0));
+ assert!(!s.doc().unwrap().stroke_mixed().weight);
+ // A face selected with its group counts with the group, whose stroke is its edges'.
+ s.execute("select.set", &json!({"ids": [g.0, face_ids[0].0]})).unwrap();
+ assert!(!s.doc().unwrap().stroke_mixed().weight);
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ // A stroke row on the group itself: a weight still goes to the edges the panel shows.
+ s.edit("t", |d, _| {
+ d.node_mut(g).unwrap().appearance.set_stroke(Paint::solid(Color::BLACK));
+ Ok(())
+ })
+ .unwrap();
+ s.execute("stroke.set", &json!({"weight": 3})).unwrap();
+ assert!(part_looks(&s, g).1.iter().all(|e| e.stroke_width() == 3.0));
+ assert_eq!(node(&s, g).appearance.stroke().map(|st| st.width), Some(1.0));
+}
+
+/// A selected Live Paint group with no part of the edited kind is still a selection: a stroke edit
+/// of a group without edges, or a fill gradient edit of a group without faces, changes nothing and
+/// leaves the settings for new art as they are.
+#[test]
+fn live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone() {
+ let mut s = session();
+ let g = live(&mut s);
+ let edge_ids: Vec = vectorcraft_tools::builder::edges(&node(&s, g)).iter().map(|e| e.id).collect();
+ s.edit("t", |d, _| {
+ d.children_mut(Some(g)).unwrap().retain(|c| !edge_ids.contains(&c.id));
+ Ok(())
+ })
+ .unwrap();
+ assert!(part_looks(&s, g).1.is_empty());
+ s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
+ let looks = part_looks(&s, g);
+ let (paint0, stroke0) = (s.paint.clone(), s.new_art_stroke());
+ s.execute("stroke.set", &json!({"cap": "round"})).unwrap();
+ s.execute("stroke.set", &json!({"weight": 4})).unwrap();
+ s.execute("stroke.weightUp", &json!({})).unwrap();
+ s.execute("stroke.setAdvanced", &json!({"arrowScale": [200, 150]})).unwrap();
+ assert_eq!((s.paint.clone(), s.new_art_stroke()), (paint0, stroke0), "new art keeps its stroke");
+ assert_eq!(part_looks(&s, g), looks);
+
+ let mut s = session();
+ 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 looks = part_looks(&s, edges_only);
+ let paint0 = s.paint.clone();
+ s.execute("paint.editGradient", &json!({"stroke": false, "angle": 45})).unwrap();
+ assert_eq!(s.paint, paint0, "new art keeps its fill");
+ assert_eq!(part_looks(&s, edges_only), looks);
+}
+
/// A Live Paint group of 50 pt squares side by side, 50 pt tall, with their left sides at each of
/// `xs`.
fn live_squares(s: &mut Session, xs: &[f64]) -> NodeId {
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/livecorners.rs b/crates/engine/src/tests/livecorners.rs
index e372467603..1ea6e5091f 100644
--- a/crates/engine/src/tests/livecorners.rs
+++ b/crates/engine/src/tests/livecorners.rs
@@ -585,6 +585,106 @@ fn a_polygon_takes_its_angle_radius_side_length_and_equal_sides() {
}
}
+/// Rectangle Angle and Ellipse Angle: `rectangleAngle` and `ellipseAngle` turn each selected live
+/// rectangle or ellipse about its own center, keeping its size, corners and pie, as one undo step.
+/// The angle it already has records no step, each key leaves the other kind as it is, and a value
+/// that is not a number is an error.
+#[test]
+fn a_rectangle_and_an_ellipse_take_their_angle() {
+ let (mut s, rect) = session();
+ run(&mut s, json!({"radius": 8}));
+ let ellipse = NodeId(s.execute("shape.ellipse", &json!({"x": 200, "y": 200, "width": 120, "height": 80})).unwrap()["id"].as_u64().unwrap());
+ run(&mut s, json!({"pieStart": 30, "pieEnd": 120}));
+ let live = |s: &Session, id: NodeId| {
+ let n = s.doc().unwrap().doc.node(id).unwrap();
+ (n.live_shape().unwrap().clone(), n.geometric_bounds().unwrap())
+ };
+ let steps = |s: &Session| s.doc().unwrap().history.undo.len();
+ let close = |a: f64, b: f64| (a - b).abs() < 1e-6;
+ let angle = |s: &Session, id: NodeId| live(s, id).0.shape_angle().unwrap();
+ // The ellipse's center: the middle of its untransformed box, wherever its pie leaves the path.
+ let ellipse_center = |s: &Session| match live(s, ellipse).0 {
+ LiveShape::Ellipse { w, h, xf, .. } => xf * vectorcraft_geom::Point::new(w / 2.0, h / 2.0),
+ l => panic!("{l:?}"),
+ };
+ let center = ellipse_center(&s);
+
+ s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
+ let n = steps(&s);
+ run(&mut s, json!({"rectangleAngle": 90}));
+ let (l, b) = live(&s, rect);
+ assert!(close(angle(&s, rect), 90.0), "{l:?}");
+ // 100 × 60 at (10, 10) turned about (60, 40): 60 wide, 100 tall, same center.
+ assert!(close(b.width(), 60.0) && close(b.height(), 100.0) && close(b.center().x, 60.0) && close(b.center().y, 40.0), "{b:?}");
+ let LiveShape::Rectangle { w, h, radii, .. } = &l else { panic!("{l:?}") };
+ assert!(close(*w, 100.0) && close(*h, 60.0) && *radii == [8.0; 4], "{w} {h} {radii:?}");
+ assert_eq!(steps(&s), n + 1, "one undo step");
+ for same in [json!({"rectangleAngle": 90}), json!({"rectangleAngle": 450}), json!({"rectangleAngle": -270}), json!({"ellipseAngle": 10})] {
+ run(&mut s, same.clone());
+ assert_eq!(steps(&s), n + 1, "{same} records no undo step");
+ }
+ // A turn the field gives back rounded is the angle the shape has: typing it again records no step.
+ run(&mut s, json!({"rectangleAngle": 33.3}));
+ let now = angle(&s, rect);
+ run(&mut s, json!({"rectangleAngle": now}));
+ run(&mut s, json!({"rectangleAngle": 33.3}));
+ assert_eq!(steps(&s), n + 2);
+ for bad in [json!({"rectangleAngle": "left"}), json!({"ellipseAngle": "up"}), json!({"rectangleAngle": true})] {
+ assert!(s.execute("object.setLiveShape", &bad).is_err(), "{bad}");
+ assert_eq!(steps(&s), n + 2, "{bad} changes nothing");
+ }
+
+ // The ellipse turns about its center and keeps its pie.
+ s.execute("select.set", &json!({"ids": [ellipse.0]})).unwrap();
+ run(&mut s, json!({"ellipseAngle": 90}));
+ let (l, b) = live(&s, ellipse);
+ assert!(close(angle(&s, ellipse), 90.0), "{l:?}");
+ let LiveShape::Ellipse { pie, .. } = &l else { panic!("{l:?}") };
+ assert_eq!(*pie, (30.0, 120.0));
+ let now = ellipse_center(&s);
+ assert!(close(now.x, center.x) && close(now.y, center.y), "{center:?} → {now:?}");
+ assert!(b.width() < b.height(), "120 × 80 turned a quarter turn: {b:?}");
+
+ // Both selected: each key turns its own kind only, each about its own center.
+ s.execute("select.set", &json!({"ids": [rect.0, ellipse.0]})).unwrap();
+ run(&mut s, json!({"rectangleAngle": 45}));
+ assert!(close(angle(&s, rect), 45.0) && close(angle(&s, ellipse), 90.0));
+ let b = live(&s, rect).1;
+ assert!(close(b.center().x, 60.0) && close(b.center().y, 40.0), "{b:?}");
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert!(close(angle(&s, rect), 33.3));
+
+ // A reflected rectangle takes the angle too, about its center.
+ s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
+ s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
+ let before = live(&s, rect).1.center();
+ run(&mut s, json!({"rectangleAngle": 20}));
+ let after = live(&s, rect).1.center();
+ assert!(close(angle(&s, rect), 20.0) && close(before.x, after.x) && close(before.y, after.y), "{before:?} → {after:?}");
+}
+
+/// A shape named in `ids` that a turn would take past the coordinate limit (±4,000,000 pt) is an
+/// error that changes nothing, whether or not it is selected.
+#[test]
+fn a_turn_past_the_coordinate_limit_is_an_error() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
+ let mut add = |cmd: &str, p: Value| s.execute(cmd, &p).unwrap()["id"].as_u64().unwrap();
+ // Each reaches within 10 pt of the limit and past it when turned.
+ let rect = add("shape.rectangle", json!({"x": 3_999_890, "y": 100, "width": 100, "height": 100}));
+ let ellipse = add("shape.ellipse", json!({"x": 3_999_950, "y": 100, "width": 40, "height": 100}));
+ let polygon = add("shape.polygon", json!({"cx": 3_999_955, "cy": 200, "radius": 50, "sides": 6}));
+ for (id, key, angle) in [(rect, "rectangleAngle", 45), (ellipse, "ellipseAngle", 90), (polygon, "polygonAngle", 90)] {
+ for selected in [false, true] {
+ s.execute("select.set", &json!({"ids": if selected { vec![id] } else { vec![] }})).unwrap();
+ let (doc, steps) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len());
+ let e = s.execute("object.setLiveShape", &json!({"ids": [id], key: angle})).unwrap_err();
+ assert!(e.to_string().contains("out of range"), "{key}, selected {selected}: {e}");
+ assert!(*s.doc().unwrap().doc == *doc && s.doc().unwrap().history.undo.len() == steps, "{key}, selected {selected}: changed");
+ }
+ }
+}
+
/// A live line's Line Properties: Line Length keeps its first end in place, Line Angle (degrees
/// counterclockwise, any finite value brought into 0 to 360) turns it about its midpoint, the
/// length applies before the angle, every selected line takes them in one undo step, and a value
diff --git a/crates/engine/src/tests/pattern.rs b/crates/engine/src/tests/pattern.rs
index fafcc80ac6..01f8e76fbc 100644
--- a/crates/engine/src/tests/pattern.rs
+++ b/crates/engine/src/tests/pattern.rs
@@ -212,6 +212,153 @@ fn cancel_new_pattern_removes_it() {
assert_eq!(doc(&s).layers.len(), 1);
}
+/// A 30×40 blue rectangle at (100, 100) with no stroke, selected.
+fn blue_rect(s: &mut Session) -> NodeId {
+ let b = rect(s, 100.0, 100.0, 30.0, 40.0);
+ s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#0000ff"})).unwrap();
+ s.execute("paint.setStroke", &json!({"ids": [b.0], "none": true})).unwrap();
+ sel(s, &[b]);
+ b
+}
+
+/// Replace Pattern Art gives the pattern copies of the selected art as its tile art in one undo
+/// step: the pattern keeps its name, swatch, place, tile and options, art painted with it keeps the
+/// paint, and the selected art stays on the canvas, selected. Undo and Redo swap the two tiles.
+#[test]
+fn replace_art_gives_a_pattern_new_tile_art() {
+ let mut s = session();
+ let red = make_dots(&mut s);
+ let filled = rect(&mut s, 200.0, 200.0, 100.0, 100.0);
+ s.execute("paint.setFill", &json!({"ids": [filled.0], "swatch": "Dots"})).unwrap();
+ s.execute("pattern.options", &json!({"name": "Dots", "tileType": "hexByRow"})).unwrap();
+ let blue = blue_rect(&mut s);
+ let old = doc(&s).pattern("Dots").unwrap().clone();
+ let place = |s: &Session| doc(s).swatches_iter().position(|w| w.name == "Dots");
+ let (at, swatches, steps) = (place(&s), doc(&s).swatches_iter().count(), s.doc().unwrap().history.undo.len());
+ let v = s.execute("object.pattern.replaceArt", &json!({"name": "Dots"})).unwrap();
+ assert_eq!(v["name"], "Dots");
+ let d = doc(&s);
+ let def = d.pattern("Dots").unwrap();
+ assert_eq!(def.art.len(), 1);
+ assert_eq!(def.art[0].kind, node(&s, blue).kind, "the tile art is the blue rectangle");
+ assert_eq!(def.art[0].appearance, node(&s, blue).appearance);
+ assert_ne!(def.art[0].id, blue, "a copy with an id of its own");
+ assert_eq!((def.tile, def.tile_type, &def.name), (old.tile, old.tile_type, &old.name), "the tile and options stay");
+ assert_eq!((d.patterns.len(), place(&s), d.swatches_iter().count()), (1, at, swatches), "no new pattern or swatch");
+ assert!(is_pattern(&node(&s, filled).appearance.fill_paint(), "Dots"), "the filled art keeps the pattern");
+ assert!(d.node(blue).is_some() && d.node(red).is_some(), "the art stays");
+ assert_eq!(s.doc().unwrap().selection.objects.to_vec(), vec![blue], "the art stays selected");
+ let st = s.doc().unwrap();
+ assert_eq!((st.history.undo.len(), st.history.undo.last().map(|e| e.label.as_str())), (steps + 1, Some("Replace Pattern Art")));
+ let new = def.art.clone();
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(doc(&s).pattern("Dots").unwrap(), &old, "Undo gives the old tile art back");
+ s.execute("edit.redo", &json!({})).unwrap();
+ assert_eq!(doc(&s).pattern("Dots").unwrap().art, new, "Redo gives the new tile art");
+}
+
+/// With Size Tile to Art on, the tile fits the new art (and its spacing); `ids` names the art.
+#[test]
+fn replace_art_fits_the_tile_when_size_tile_to_art_is_on() {
+ let mut s = session();
+ make_dots(&mut s);
+ s.execute("pattern.options", &json!({"name": "Dots", "sizeTileToArt": true, "hSpacing": 4, "vSpacing": 6})).unwrap();
+ let blue = blue_rect(&mut s);
+ s.execute("select.set", &json!({"ids": []})).unwrap();
+ s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [blue.0]})).unwrap();
+ assert_eq!(doc(&s).pattern("Dots").unwrap().tile, Rect::new(98.0, 97.0, 132.0, 143.0));
+}
+
+/// Art that matches the tile art already, its own ids aside, records no undo step.
+#[test]
+fn replace_art_that_matches_the_tile_art_records_nothing() {
+ let mut s = session();
+ make_dots(&mut s);
+ blue_rect(&mut s);
+ s.execute("object.pattern.replaceArt", &json!({"name": "Dots"})).unwrap();
+ let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len());
+ s.execute("object.pattern.replaceArt", &json!({"name": "Dots"})).unwrap();
+ assert_eq!(s.doc().unwrap().history.undo.len(), steps);
+ assert_eq!(doc(&s), &before);
+}
+
+/// Replace Pattern Art is refused, changing nothing, for a missing name or pattern, with no art,
+/// while a pattern is edited, and for art painted with the pattern itself, directly, through
+/// another pattern, through a symbol, through the paints a graph stores, through a graph design a
+/// graph draws its columns with, through the art of a brush on a stroke and through the symbol of an
+/// inline graphic in type.
+#[test]
+fn replace_art_is_refused_without_changing_anything() {
+ let mut s = session();
+ make_dots(&mut s);
+ // "Holds dots": a pattern whose tile is painted with Dots.
+ let other = rect(&mut s, 100.0, 100.0, 10.0, 10.0);
+ s.execute("paint.setFill", &json!({"ids": [other.0], "swatch": "Dots"})).unwrap();
+ sel(&mut s, &[other]);
+ s.execute("object.pattern.make", &json!({"name": "Holds dots", "edit": false})).unwrap();
+ let via = rect(&mut s, 150.0, 150.0, 10.0, 10.0);
+ s.execute("paint.setFill", &json!({"ids": [via.0], "swatch": "Holds dots"})).unwrap();
+ let stroked = rect(&mut s, 200.0, 200.0, 10.0, 10.0);
+ s.execute("paint.setStroke", &json!({"ids": [stroked.0], "swatch": "Dots"})).unwrap();
+ sel(&mut s, &[stroked]);
+ let instance = id_of(&s.execute("symbol.new", &json!({"name": "Dotted"})).unwrap());
+ let graph = graph_painted_with(&mut s, "Dots");
+ // A graph whose stored columns name design "Dotted columns", drawn with Dots, before it is drawn
+ // again.
+ let design = rect(&mut s, 300.0, 300.0, 10.0, 10.0);
+ s.execute("paint.setFill", &json!({"ids": [design.0], "swatch": "Dots"})).unwrap();
+ s.execute("graph.design", &json!({"new": "Dotted columns", "ids": [design.0]})).unwrap();
+ let v = s.execute("graph.create", &json!({"type": "column", "x": 300, "y": 200, "width": 60, "height": 40, "csv": ",2024\nQ1,3"}));
+ let designed = id_of(&v.unwrap());
+ let mut extras = doc_mut(&mut s).node_mut(designed).unwrap().extras_mut();
+ extras.graph.as_mut().unwrap().series_columns =
+ vec![Some(vectorcraft_doc::ColumnDesign { design: "Dotted columns".into(), ..Default::default() })];
+ drop(extras);
+ // A path stroked with an art brush whose art is filled with Dots.
+ let brush_art = rect(&mut s, 300.0, 350.0, 20.0, 5.0);
+ s.execute("paint.setFill", &json!({"ids": [brush_art.0], "swatch": "Dots"})).unwrap();
+ s.execute("brush.new", &json!({"type": "art", "name": "Dotted brush", "ids": [brush_art.0]})).unwrap();
+ let brushed = rect(&mut s, 300.0, 380.0, 40.0, 10.0);
+ s.execute("paint.setFill", &json!({"ids": [brushed.0], "none": true})).unwrap();
+ s.execute("paint.setStroke", &json!({"ids": [brushed.0], "color": "#000000"})).unwrap();
+ s.execute("brush.apply", &json!({"name": "Dotted brush", "ids": [brushed.0]})).unwrap();
+ // Type that shows symbol "Dotted" as an inline graphic.
+ let typed = id_of(&s.execute("text.create", &json!({"x": 20, "y": 420, "text": "Hi"})).unwrap());
+ s.execute("text.insertInline", &json!({"id": typed.0, "at": 0, "symbol": "Dotted"})).unwrap();
+ let plain = blue_rect(&mut s);
+ let unchanged = |s: &Session, before: &vectorcraft_doc::Document, steps: usize, case: &str| {
+ assert_eq!(doc(s), before, "{case}: the document stays");
+ assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{case}: no undo step");
+ };
+ let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len());
+ for (case, p, why) in [
+ ("no name", json!({}), "missing name".to_string()),
+ ("no pattern", json!({"name": "Stripes"}), "no pattern `Stripes`".into()),
+ ("no art", json!({"name": "Dots", "ids": [9999]}), "select the art for the pattern tile".into()),
+ ("painted with it", json!({"name": "Dots", "ids": [other.0]}), "art painted with `Dots` can't be its tile".into()),
+ ("through a pattern", json!({"name": "Dots", "ids": [via.0]}), "art painted with `Dots` can't be its tile".into()),
+ ("through a symbol", json!({"name": "Dots", "ids": [instance.0]}), "art painted with `Dots` can't be its tile".into()),
+ ("through a graph's paints", json!({"name": "Dots", "ids": [graph.0]}), "art painted with `Dots` can't be its tile".into()),
+ ("through a graph design", json!({"name": "Dots", "ids": [designed.0]}), "art painted with `Dots` can't be its tile".into()),
+ ("through a brush", json!({"name": "Dots", "ids": [brushed.0]}), "art painted with `Dots` can't be its tile".into()),
+ ("through an inline graphic", json!({"name": "Dots", "ids": [typed.0]}), "art painted with `Dots` can't be its tile".into()),
+ ] {
+ let err = s.execute("object.pattern.replaceArt", &p).unwrap_err();
+ assert!(err.to_string().contains(&why), "{case}: {err}");
+ unchanged(&s, &before, steps, case);
+ }
+ s.execute("select.set", &json!({"ids": []})).unwrap();
+ let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len());
+ let err = s.execute("object.pattern.replaceArt", &json!({"name": "Dots"})).unwrap_err();
+ assert!(err.to_string().contains("select the art for the pattern tile"), "nothing selected: {err}");
+ unchanged(&s, &before, steps, "nothing selected");
+ s.execute("object.pattern.edit", &json!({"name": "Holds dots"})).unwrap();
+ let (before, steps) = (doc(&s).clone(), s.doc().unwrap().history.undo.len());
+ let err = s.execute("object.pattern.replaceArt", &json!({"name": "Dots", "ids": [plain.0]})).unwrap_err();
+ assert!(matches!(&err, EngineError::Disabled(_, w) if w == "finish editing the pattern first"), "while editing: {err}");
+ unchanged(&s, &before, steps, "while editing");
+}
+
fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document {
Arc::make_mut(&mut s.doc_mut().unwrap().doc)
}
diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs
new file mode 100644
index 0000000000..66283183b9
--- /dev/null
+++ b/crates/engine/src/tests/quickpen.rs
@@ -0,0 +1,300 @@
+//! The Quick Pen tool driven through the session, and `path.quickPen`.
+
+use serde_json::{Value, json};
+use vectorcraft_doc::{NodeId, NodeKind};
+use vectorcraft_geom::{PathData, Point, SubPath};
+use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey};
+
+use crate::tooling::ViewInfo;
+use crate::*;
+
+fn session() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
+ s
+}
+
+fn view() -> ViewInfo {
+ ViewInfo { smart_guides: false, ..Default::default() }
+}
+
+fn undo_steps(s: &Session) -> usize {
+ s.doc().unwrap().history.undo.len()
+}
+
+fn paths(s: &Session) -> Vec<(NodeId, PathData)> {
+ let mut v = vec![];
+ s.doc().unwrap().doc.walk(|n| {
+ if let NodeKind::Path { path, .. } = &n.kind {
+ v.push((n.id, path.clone()));
+ }
+ });
+ v
+}
+
+fn only_path(s: &Session) -> SubPath {
+ let all = paths(s);
+ assert_eq!(all.len(), 1, "one path");
+ all[0].1.subpaths[0].clone()
+}
+
+fn pt(x: f64, y: f64) -> Point {
+ Point::new(x, y)
+}
+
+fn press(s: &mut Session, pts: &[(f64, f64)]) {
+ let v = view();
+ s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1), v).unwrap();
+ for &(x, y) in &pts[1..] {
+ s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap();
+ }
+ let l = pts[pts.len() - 1];
+ s.pointer(&PointerEvent::new(PointerKind::Up, l.0, l.1), v).unwrap();
+}
+
+fn click(s: &mut Session, x: f64, y: f64) {
+ press(s, &[(x, y)]);
+}
+
+fn key(s: &mut Session, k: ToolKey) {
+ s.tool_key(k, Mods::default(), view()).unwrap();
+}
+
+fn quick_pen(s: &mut Session) {
+ s.select_tool("quickPen", view()).unwrap();
+}
+
+/// Clicks draw lines; Alt tapped alone switches to the next action, so the next clicks draw a
+/// continuous arc and a sharp-corner half circle. Each piece is one undo step.
+#[test]
+fn clicks_draw_lines_and_arcs_one_undo_step_each() {
+ let mut s = session();
+ quick_pen(&mut s);
+ click(&mut s, 100.0, 100.0);
+ let undo = undo_steps(&s);
+ click(&mut s, 200.0, 100.0);
+ assert_eq!(undo_steps(&s), undo + 1);
+ key(&mut s, ToolKey::AltTap);
+ assert_eq!(s.tool_options()["action"], "continuousArc");
+ click(&mut s, 300.0, 200.0);
+ key(&mut s, ToolKey::AltTap);
+ assert_eq!(s.tool_options()["action"], "sharpArc");
+ click(&mut s, 300.0, 300.0);
+ assert_eq!(undo_steps(&s), undo + 3);
+ let sp = only_path(&s);
+ assert!(!sp.closed);
+ let ends: Vec = sp.anchors.iter().map(|a| a.p).collect();
+ assert_eq!(ends.first(), Some(&pt(100.0, 100.0)));
+ assert_eq!(ends.last(), Some(&pt(300.0, 300.0)));
+ // Line (2 points), quarter circle (1 more), half circle in two quarters (2 more).
+ assert_eq!(ends.len(), 5);
+ // The continuous arc left (200, 100) heading right, as the line arrived.
+ let joint = sp.anchors.get(1).unwrap();
+ assert!((joint.h_out - joint.p).y.abs() < 1e-9 && joint.h_out.x > joint.p.x);
+ // The half circle on (300, 200)–(300, 300) bulges to the left of the way it was drawn
+ // (downward, so to the right on the page): its middle point is at x = 350.
+ assert!(sp.anchors.get(3).unwrap().p.distance(pt(350.0, 250.0)) < 1e-9);
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(only_path(&s).anchors.len(), 3);
+}
+
+/// C flips the last sharp-corner arc, and [ and ] make it 15° smaller or larger, each as one
+/// undo step; the next arc keeps the new size. C is not taken while the last piece is a line.
+#[test]
+fn c_flips_and_brackets_size_the_last_sharp_arc() {
+ let mut s = session();
+ quick_pen(&mut s);
+ s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
+ click(&mut s, 100.0, 300.0);
+ click(&mut s, 300.0, 300.0);
+ assert!(only_path(&s).anchors.get(1).unwrap().p.distance(pt(200.0, 200.0)) < 1e-9, "above the chord");
+ assert!(s.tool_claims_key(ToolKey::Letter('c'), view()));
+ let undo = undo_steps(&s);
+ key(&mut s, ToolKey::Letter('c'));
+ assert!(only_path(&s).anchors.get(1).unwrap().p.distance(pt(200.0, 400.0)) < 1e-9, "below once flipped");
+ assert_eq!(undo_steps(&s), undo + 1);
+ key(&mut s, ToolKey::BracketLeft);
+ assert_eq!(s.tool_options()["turn"], 165.0);
+ let sp = only_path(&s);
+ // A 165° arc is two segments; its middle point lies on the chord's perpendicular bisector,
+ // still below.
+ assert_eq!(sp.anchors.len(), 3);
+ let mid = sp.anchors.get(1).unwrap().p;
+ assert!((mid.x - 200.0).abs() < 1e-9 && mid.y > 300.0);
+ assert_eq!(undo_steps(&s), undo + 2);
+ s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "line"})).unwrap();
+ click(&mut s, 400.0, 300.0);
+ assert!(!s.tool_claims_key(ToolKey::Letter('c'), view()));
+}
+
+/// Alt tapped during a drag draws the piece with the next action: a continuous arc becomes a
+/// sharp-corner arc with a corner where it starts, and the path goes on drawing after it.
+#[test]
+fn an_alt_tap_during_a_drag_switches_the_piece_and_drawing_goes_on() {
+ let mut s = session();
+ quick_pen(&mut s);
+ click(&mut s, 100.0, 100.0);
+ click(&mut s, 200.0, 100.0);
+ s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "continuousArc"})).unwrap();
+ // A quarter circle that arrives at (300, 200) heading down.
+ click(&mut s, 300.0, 200.0);
+ let joint = only_path(&s).anchors.len() - 1;
+ let v = view();
+ s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 300.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, 210.0, 310.0), v).unwrap();
+ assert_eq!(only_path(&s).anchors.get(joint).unwrap().kind, vectorcraft_geom::AnchorKind::Smooth);
+ key(&mut s, ToolKey::AltTap);
+ s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 300.0), v).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 300.0), v).unwrap();
+ assert_eq!(s.tool_options()["action"], "sharpArc");
+ assert_eq!(only_path(&s).anchors.get(joint).unwrap().kind, vectorcraft_geom::AnchorKind::Corner);
+ click(&mut s, 100.0, 300.0);
+ assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(100.0, 300.0), "the same path");
+}
+
+/// A click on the first point closes the path; the next click starts a new one.
+#[test]
+fn a_click_on_the_first_point_closes_the_path() {
+ let mut s = session();
+ quick_pen(&mut s);
+ for (x, y) in [(100.0, 100.0), (200.0, 100.0), (200.0, 200.0), (101.0, 101.0)] {
+ click(&mut s, x, y);
+ }
+ let sp = only_path(&s);
+ assert!(sp.closed);
+ assert_eq!(sp.anchors.len(), 3);
+ click(&mut s, 400.0, 400.0);
+ assert_eq!(paths(&s).len(), 2);
+}
+
+/// Escape ends the path: the next click starts a new path. A press dragged places the piece
+/// where it is let go.
+#[test]
+fn escape_ends_the_path_and_a_drag_places_the_piece() {
+ let mut s = session();
+ quick_pen(&mut s);
+ click(&mut s, 100.0, 100.0);
+ press(&mut s, &[(150.0, 100.0), (180.0, 120.0), (250.0, 150.0)]);
+ assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(250.0, 150.0));
+ assert!(s.tool_ends_on_escape(view()));
+ key(&mut s, ToolKey::Escape);
+ assert!(!s.tool_ends_on_escape(view()));
+ click(&mut s, 500.0, 500.0);
+ assert_eq!(paths(&s).len(), 2);
+}
+
+/// An anchor moved by another command ends the path being drawn: C does not flip the old arc back
+/// over the edit, and the next click starts a new path instead of rebuilding the old one.
+#[test]
+fn an_edit_from_outside_ends_the_path() {
+ let mut s = session();
+ quick_pen(&mut s);
+ s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
+ click(&mut s, 100.0, 300.0);
+ click(&mut s, 300.0, 300.0);
+ let (id, _) = paths(&s)[0].clone();
+ s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 2, "x": 320, "y": 280})).unwrap();
+ assert!(!s.tool_claims_key(ToolKey::Letter('c'), view()));
+ click(&mut s, 500.0, 500.0);
+ let all = paths(&s);
+ assert_eq!(all.len(), 2, "a new path");
+ assert_eq!(all[0].1.subpaths[0].anchors.last().unwrap().p, pt(320.0, 280.0), "the edit stays");
+ // The same for a point of a path the tool went on from, and for the first point of a new path.
+ for new in [true, false] {
+ let mut s = session();
+ let id = if new {
+ quick_pen(&mut s);
+ click(&mut s, 100.0, 100.0);
+ click(&mut s, 200.0, 100.0);
+ paths(&s)[0].0
+ } else {
+ let r = s.execute("shape.line", &json!({"x1": 100, "y1": 100, "x2": 200, "y2": 100})).unwrap();
+ let id = NodeId(r["id"].as_u64().unwrap());
+ s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
+ quick_pen(&mut s);
+ click(&mut s, 200.0, 100.0);
+ click(&mut s, 200.0, 200.0);
+ id
+ };
+ s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap();
+ click(&mut s, 400.0, 400.0);
+ assert_eq!(paths(&s).len(), 2, "a new path (new: {new})");
+ assert_eq!(s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().subpaths[0].anchors.first().unwrap().p, pt(90.0, 90.0));
+ }
+}
+
+/// A click on an end of an open path goes on drawing from it, in the same path; from its start,
+/// the path is reversed first.
+#[test]
+fn a_click_on_an_open_end_continues_the_path() {
+ let mut s = session();
+ let r = s.execute("shape.line", &json!({"x1": 100, "y1": 100, "x2": 200, "y2": 100})).unwrap();
+ let id = NodeId(r["id"].as_u64().unwrap());
+ s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
+ quick_pen(&mut s);
+ click(&mut s, 100.0, 100.0);
+ click(&mut s, 100.0, 200.0);
+ let all = paths(&s);
+ assert_eq!(all.len(), 1);
+ assert_eq!(all[0].0, id);
+ let ends: Vec = all[0].1.subpaths[0].anchors.iter().map(|a| a.p).collect();
+ assert_eq!(ends, [pt(200.0, 100.0), pt(100.0, 100.0), pt(100.0, 200.0)]);
+}
+
+/// `path.quickPen` makes a new path with the current paint, or a black stroke without any.
+#[test]
+fn path_quick_pen_makes_a_stroked_path() {
+ let mut s = session();
+ s.execute("paint.setStroke", &json!({"none": true})).unwrap();
+ s.execute("paint.setFill", &json!({"none": true})).unwrap();
+ let r = s
+ .execute(
+ "path.quickPen",
+ &json!({"start": [0, 0], "pieces": [{"x": 100, "y": 0}, {"x": 100, "y": 100, "action": "sharpArc", "turn": 90, "flip": true}]}),
+ )
+ .unwrap();
+ let id = r["id"].as_u64().unwrap();
+ let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap().clone();
+ assert!(!n.appearance.stroke_paint().is_none(), "a black stroke");
+ assert_eq!(n.path_data().unwrap().subpaths[0].anchors.len(), 3);
+}
+
+/// Bad params are refused and change nothing.
+#[test]
+fn path_quick_pen_refuses_bad_params() {
+ let mut s = session();
+ let r = s.execute("path.quickPen", &json!({"start": [0, 0], "pieces": [{"x": 100, "y": 0}]})).unwrap();
+ let id = r["id"].as_u64().unwrap();
+ let before = paths(&s);
+ let bad: [Value; 11] = [
+ json!({}),
+ json!({"pieces": []}),
+ json!({"start": [0, 0], "pieces": [{"x": 1, "y": 1, "action": "arc"}]}),
+ json!({"start": [0, 0], "pieces": [{"x": 1, "y": 1, "action": "sharpArc", "turn": 0}]}),
+ json!({"start": [0, 0], "pieces": [{"x": 1, "y": 1, "turn": 360}]}),
+ json!({"start": [0, 0], "pieces": [{"x": "1", "y": 1}]}),
+ json!({"start": [0, 0], "pieces": [{"x": 1, "y": 1, "flip": "yes"}]}),
+ json!({"start": [0, 0], "keep": 1}),
+ json!({"id": id, "keep": 0}),
+ json!({"id": id, "keep": 3}),
+ json!({"id": id, "start": [0, 0]}),
+ ];
+ for p in bad {
+ assert!(s.execute("path.quickPen", &p).is_err(), "{p}");
+ }
+ assert!(s.execute("path.quickPen", &json!({"start": [0, 0], "pieces": vec![json!({"x": 1, "y": 1}); 10_001]})).is_err());
+ s.execute("path.quickPen", &json!({"id": id, "closed": true})).unwrap();
+ assert!(s.execute("path.quickPen", &json!({"id": id, "pieces": [{"x": 5, "y": 5}]})).is_err(), "closed");
+ assert_eq!(paths(&s).len(), before.len());
+}
+
+/// With `id` and `keep`, the points after the first `keep` are replaced by the pieces.
+#[test]
+fn path_quick_pen_replaces_the_points_after_keep() {
+ let mut s = session();
+ let r = s.execute("path.quickPen", &json!({"start": [0, 0], "pieces": [{"x": 100, "y": 0}, {"x": 100, "y": 100}]})).unwrap();
+ let id = r["id"].as_u64().unwrap();
+ s.execute("path.quickPen", &json!({"id": id, "keep": 2, "pieces": [{"x": 200, "y": 0}]})).unwrap();
+ let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect();
+ assert_eq!(ends, [pt(0.0, 0.0), pt(100.0, 0.0), pt(200.0, 0.0)]);
+}
diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs
index 10c2edcc17..b2664a9682 100644
--- a/crates/engine/src/tests/recolor.rs
+++ b/crates/engine/src/tests/recolor.rs
@@ -836,6 +836,21 @@ fn a_null_in_group_colors_removes_that_swatch_and_the_ones_after_it_keep_their_p
assert_eq!(link(&s, green), ("#00ff00".into(), Some(names[2].clone())), "art linked to a swatch that stays keeps its link");
}
+/// "keep" in `groupColors` leaves the group's swatch at its place as it is, without Global Adjust,
+/// and past the group's swatches it adds none.
+#[test]
+fn keep_in_group_colors_leaves_that_swatch_as_it_is() {
+ let mut s = session();
+ run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#2878f0", "#ff0000"]}));
+ let p = json!({"map": [], "group": "Brand", "groupColors": ["keep", "#00ff00", "keep"], "globalAdjust": {"brightness": -50}});
+ run(&mut s, "recolor.apply", p);
+ let g = &s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches;
+ let g: Vec = g.iter().map(|w| w.paint.color().unwrap().to_hex()).collect();
+ assert_eq!(g.len(), 2, "{g:?}");
+ assert_eq!(g[0], "#2878f0", "the kept swatch takes no Global Adjust");
+ assert_ne!(g[1], "#00ff00", "the other new color takes it");
+}
+
/// A gradient or pattern swatch of the group keeps its place and its paint when `recolor.apply`
/// rewrites the group: the group's colors, from the rows or from `groupColors`, go to its color
/// swatches in order.
diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs
index 7c8c167527..7653dc083d 100644
--- a/crates/engine/src/tests/script_io.rs
+++ b/crates/engine/src/tests/script_io.rs
@@ -12,12 +12,14 @@ use crate::*;
const DENIED: &str = "Script file access denied";
-/// A fresh folder for test `name`, with a `main` folder inside it for the script.
+/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real
+/// path: kept grants hold real paths, and a path named through a link (macOS's `/var` is
+/// `/private/var`) is refused by its names alone.
fn folder(name: &str) -> PathBuf {
let base = std::env::temp_dir().join(format!("vc-script-io-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("main")).unwrap();
- base
+ std::fs::canonicalize(&base).unwrap()
}
fn write(path: &Path, bytes: &[u8]) {
diff --git a/crates/engine/src/tests/swatchcmds.rs b/crates/engine/src/tests/swatchcmds.rs
index 1b87639ef9..ff02889253 100644
--- a/crates/engine/src/tests/swatchcmds.rs
+++ b/crates/engine/src/tests/swatchcmds.rs
@@ -125,6 +125,69 @@ fn add_used_colors_skips_colours_that_have_swatches() {
assert!(doc(&s).swatch("R=171 G=205 B=239").unwrap().global);
}
+/// A run that finds no new color, over all the art or the selection, records no undo step.
+#[test]
+fn add_used_colors_with_no_new_color_records_no_undo_step() {
+ let mut s = session();
+ let a = rect_filled(&mut s, json!({"color": "#123456"}));
+ run(&mut s, "swatch.addUsedColors", json!({}));
+ run(&mut s, "select.set", json!({"ids": [a.0]}));
+ let before = doc(&s).clone();
+ let undo = undo_len(&s);
+ for p in [json!({}), json!({"selection": true, "global": true})] {
+ assert_eq!(run(&mut s, "swatch.addUsedColors", p), json!({"added": [], "linked": 0}));
+ assert_eq!(undo_len(&s), undo);
+ assert_eq!(*doc(&s), before);
+ }
+ // An empty selection is still an error, with nothing changed.
+ run(&mut s, "select.set", json!({"ids": []}));
+ let undo = undo_len(&s);
+ assert!(s.execute("swatch.addUsedColors", &json!({"selection": true})).is_err());
+ assert_eq!(undo_len(&s), undo);
+}
+
+/// A run that finds no new color, while the Type tool is typing, still ends the typing session: the
+/// typing is its own undo step.
+#[test]
+fn add_used_colors_with_no_new_color_ends_the_typing() {
+ use vectorcraft_tools::{PointerEvent, PointerKind};
+ let mut s = session();
+ let v = ViewInfo::default();
+ let t = NodeId(run(&mut s, "text.create", json!({"x": 10, "y": 10, "text": "Hello"}))["id"].as_u64().unwrap());
+ run(&mut s, "swatch.addUsedColors", json!({}));
+ s.select_tool("type", v).unwrap();
+ let b = doc(&s).bounds_of(&[t], false).unwrap();
+ for kind in [PointerKind::Down, PointerKind::Up] {
+ s.pointer(&PointerEvent::new(kind, b.x1 - 1.0, b.center().y), v).unwrap();
+ }
+ s.tool_text("!", v).unwrap();
+ assert!(crate::cmd::typing_in_progress(&s));
+ let steps = undo_len(&s);
+ assert_eq!(run(&mut s, "swatch.addUsedColors", json!({})), json!({"added": [], "linked": 0}));
+ assert!(!crate::cmd::typing_in_progress(&s));
+ let labels: Vec = s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect();
+ assert_eq!((labels.len(), labels.last().map(String::as_str)), (steps + 1, Some("Typing")));
+}
+
+/// Add Selected Colors while Global Edit is on links only the selected art: a member of the same
+/// shape with another color keeps its color and stays unlinked, and Global Edit stays on.
+#[test]
+fn add_selected_colors_in_global_edit_keeps_the_other_members_colors() {
+ let mut s = session();
+ let a = rect_filled(&mut s, json!({"color": "#123456"}));
+ let b = rect_filled(&mut s, json!({"color": "#654321"}));
+ run(&mut s, "select.set", json!({"ids": [a.0]}));
+ let r = run(&mut s, "select.globalEdit", json!({}));
+ assert_eq!((r["active"].clone(), r["ids"].clone()), (json!(true), json!([a.0, b.0])), "the other rectangle is a member");
+ let other = fill(&s, b);
+ let undo = undo_len(&s);
+ run(&mut s, "swatch.addUsedColors", json!({"selection": true, "global": true}));
+ assert!(matches!(fill(&s, a), Paint::Solid { swatch: Some(_), .. }), "{:?}", fill(&s, a));
+ assert_eq!(fill(&s, b), other, "the unselected member keeps its color");
+ assert_eq!(undo_len(&s), undo + 1);
+ assert!(s.doc().unwrap().global_edit.is_some(), "Global Edit stays on");
+}
+
/// Give `id` the fill `p` exactly as written (a command would round or convert some colors).
fn set_fill(s: &mut Session, id: NodeId, p: Paint) {
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().appearance.set_fill(p);
diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs
index fdcd554991..8036bf04c3 100644
--- a/crates/engine/src/tests/swatchlib.rs
+++ b/crates/engine/src/tests/swatchlib.rs
@@ -160,6 +160,37 @@ fn save_and_load_round_trip_keeps_cmyk_spot_and_groups() {
assert!(s.execute("swatch.library.save", &json!({"user": true})).is_err(), "no user folder in a headless session");
}
+/// A library color group that holds a gradient comes into the document whole, the gradient at its
+/// place in the group, as a `.ai` library's pattern swatch comes in its color group.
+#[test]
+fn add_brings_a_library_color_group_holding_a_gradient_whole() {
+ let mut s = session();
+ run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#123456", "#abcdef"]}));
+ let r = run(&mut s, "swatch.library.save", json!({"names": ["Brand", "Sunset"], "name": "Mixed"}));
+ // Move the Sunset gradient into the library's Brand group, as a hand-edited file can.
+ let mut lib: Value = serde_json::from_str(r["data"].as_str().unwrap()).unwrap();
+ let swatches = lib["swatches"].as_array_mut().unwrap();
+ let at = swatches.iter().position(|w| w["name"] == "Sunset").unwrap();
+ let sunset = swatches.remove(at);
+ lib["groups"][0]["swatches"].as_array_mut().unwrap().insert(1, sunset);
+ let r = run(&mut s, "swatch.library.load", json!({"data": lib.to_string(), "name": "mixed.vcswatches"}));
+ let id = r["library"].as_str().unwrap().to_string();
+ let (_, loaded) = cmd::swatchlib::library(&s, &id).unwrap();
+ assert!(matches!(loaded.groups[0].swatches[1].paint, Paint::Gradient(_)), "the reader keeps the gradient in the group");
+ run(&mut s, "swatch.delete", json!({"names": ["Brand", "Sunset"]}));
+ for p in [json!({"library": id}), json!({"library": id, "names": ["Brand"]})] {
+ let undo = undo_len(&s);
+ let r = run(&mut s, "swatch.library.add", p.clone());
+ assert!(r["added"].as_array().unwrap().iter().any(|n| n == "Sunset"), "{p}: {r}");
+ let brand = doc(&s).swatch_groups.iter().find(|g| g.name == "Brand").map(|g| g.swatches.clone()).unwrap_or_default();
+ let kinds: Vec<(&str, bool)> = brand.iter().map(|w| (w.name.as_str(), matches!(w.paint, Paint::Gradient(_)))).collect();
+ assert_eq!(kinds.len(), 3, "{p}: {kinds:?}");
+ assert_eq!(kinds[1], ("Sunset", true), "{p}: the gradient keeps its place in the group");
+ assert_eq!(undo_len(&s), undo + 1, "{p}: one undo step");
+ run(&mut s, "edit.undo", json!({}));
+ }
+}
+
/// The swatch library commands, and the graphic style library save and load that share their file
/// handling, refuse a parameter of the wrong form, such as `user: "true"` or `names: "Grays"`, with
/// an error that names it; the document keeps its swatches and no undo step is recorded. A null
diff --git a/crates/engine/src/tests/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/tests/color_settings.rs b/crates/engine/tests/color_settings.rs
index 7c0aef252e..c07d741265 100644
--- a/crates/engine/tests/color_settings.rs
+++ b/crates/engine/tests/color_settings.rs
@@ -6,7 +6,7 @@
use std::sync::{Mutex, MutexGuard};
use serde_json::json;
-use vectorcraft_color::cms;
+use vectorcraft_color::{Color, cms};
use vectorcraft_engine::Session;
use vectorcraft_engine::cmd::colormgmt::{PROFILES_KEY, ProfileChoice, ProfileIssue, doc_profiles};
use vectorcraft_engine::store::MAX_PRESET_FILE;
@@ -20,6 +20,22 @@ fn settings() -> MutexGuard<'static, ()> {
SETTINGS.lock().unwrap_or_else(|e| e.into_inner())
}
+/// The working Color Settings as a test found them, put back when it ends (a failing one too)
+/// before the next test takes its turn.
+struct Restored(cms::ColorSettings, #[allow(dead_code)] MutexGuard<'static, ()>);
+
+impl Drop for Restored {
+ fn drop(&mut self) {
+ let _ = cms::set_active(&self.0);
+ }
+}
+
+/// [`settings`], with the working Color Settings put back afterwards.
+fn restored_settings() -> Restored {
+ let g = settings();
+ Restored(cms::working_settings(), g)
+}
+
#[test]
fn color_settings_lists_profiles_and_validates() {
let _g = settings();
@@ -923,6 +939,114 @@ fn saved_color_settings_that_cannot_be_used_leave_the_defaults() {
}
}
+/// View › Proof Setup › Customize's Preserve CMYK Numbers proofs each color from its own inks:
+/// with Device CMYK as the working space, C50 M50 Y50 and K50 show as the same gray, and on
+/// VectorCraft Generic CMYK they print, and so proof, as different grays; a pattern's tile art
+/// proofs the same way. Without it the proof starts from the drawn pixels, which are the same.
+#[test]
+fn preserve_cmyk_numbers_proofs_each_color_from_its_inks() {
+ let _g = restored_settings();
+ let mut s = session();
+ s.execute("edit.colorSettings", &json!({"cmyk": cms::DEVICE_CMYK})).unwrap();
+ let k50 = json!({"c": 0, "m": 0, "y": 0, "k": 50});
+ let cmy = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
+ exec(&mut s, "paint.setFill", json!({"ids": [cmy.0], "color": {"c": 50, "m": 50, "y": 50, "k": 0}}));
+ let k = rect(&mut s, 100.0, 0.0, 100.0, 100.0);
+ exec(&mut s, "paint.setFill", json!({"ids": [k.0], "color": k50}));
+ // A pattern whose tile is all K50, filling a band below the squares.
+ let tile = rect(&mut s, 300.0, 0.0, 10.0, 10.0);
+ exec(&mut s, "paint.setFill", json!({"ids": [tile.0], "color": k50}));
+ exec(&mut s, "object.pattern.make", json!({"ids": [tile.0], "name": "K50 Tile", "edit": false}));
+ let band = rect(&mut s, 0.0, 130.0, 200.0, 40.0);
+ exec(&mut s, "paint.setFill", json!({"ids": [band.0], "swatch": "K50 Tile"}));
+ let proof = |preserve_numbers| vectorcraft_render::proof::ProofSetup {
+ target: vectorcraft_render::proof::ProofTarget::Cmyk(cms::GENERIC_CMYK.into()),
+ preserve_numbers,
+ ..Default::default()
+ };
+ let doc = s.doc().unwrap().doc.clone();
+ let pixel = |px: &[u8], x: usize, y: usize| [px[(y * 200 + x) * 4], px[(y * 200 + x) * 4 + 1], px[(y * 200 + x) * 4 + 2]];
+ // The pixels at the centers of the two squares and in the patterned band.
+ let shown = |proof: Option| {
+ let opts = RenderOptions { proof, background: Some([255, 255, 255, 255]), ..Default::default() };
+ let px = Renderer::new().render(&doc, 200, 200, Affine::IDENTITY, &opts).pixels;
+ (pixel(&px, 50, 50), pixel(&px, 150, 50), pixel(&px, 55, 155))
+ };
+ let (a, b, _) = shown(None);
+ let (pa, pb, _) = shown(Some(proof(false)));
+ let (ca, cb, cp) = shown(Some(proof(true)));
+ let want = |c: Color| cms::active().proof_color(&c, &proof(true)).map(|v| (v * 255.0).round() as i32);
+ let cmy_want = want(Color::cmyk(0.5, 0.5, 0.5, 0.0));
+ let k_want = want(Color::cmyk(0.0, 0.0, 0.0, 0.5));
+ // With Simulate Paper Color the art sits on the device's paper, not on white.
+ let paper = vectorcraft_render::proof::ProofSetup { simulate_paper: true, ..proof(true) };
+ let tint = cms::active().proof_srgb([1.0; 3], &paper).map(|v| (v * 255.0).round() as i32);
+ let opts = RenderOptions { proof: Some(paper), background: Some([255, 255, 255, 255]), ..Default::default() };
+ let bare = pixel(&Renderer::new().render(&doc, 200, 200, Affine::IDENTITY, &opts).pixels, 50, 115);
+ assert_eq!(a, b, "the two builds show as one gray in Device CMYK");
+ assert_eq!(pa, pb, "proofed from the pixels, they stay one gray");
+ assert!(ca != cb, "proofed from their inks, they print differently: {ca:?} vs {cb:?}");
+ let near = |got: [u8; 3], want: [i32; 3]| got.iter().zip(want).all(|(g, w)| (i32::from(*g) - w).abs() <= 2);
+ assert!(near(ca, cmy_want) && near(cb, k_want), "{ca:?} {cmy_want:?}, {cb:?} {k_want:?}");
+ assert!(near(cp, k_want), "the pattern's tile proofs from its inks: {cp:?} vs {k_want:?}");
+ assert!(tint != [255; 3] && near(bare, tint), "the bare page shows the paper: {bare:?} vs {tint:?}");
+}
+
+/// With Preserve CMYK Numbers, an image in an opacity mask keeps its pixels as they are, so the
+/// mask covers the same in a pattern's tile as outside one.
+#[test]
+fn preserve_cmyk_numbers_leaves_mask_images_in_pattern_tiles_as_they_are() {
+ let _g = restored_settings();
+ let mut s = session();
+ // A K100 square masked by a blue image, the same at (0, 0) and as a pattern's tile.
+ let masked = |s: &mut Session, x: f64| {
+ let obj = rect(s, x, 0.0, 20.0, 20.0);
+ exec(s, "paint.setFill", json!({"ids": [obj.0], "color": {"c": 0, "m": 0, "y": 0, "k": 100}}));
+ let blue = rect(s, x, 0.0, 20.0, 20.0);
+ exec(s, "paint.setFill", json!({"ids": [blue.0], "color": "#0000ff"}));
+ select(s, &[blue]);
+ exec(s, "object.rasterize", json!({"ppi": 72}));
+ let image = s.doc().unwrap().selection.objects[0];
+ select(s, &[obj, image]);
+ exec(s, "transparency.makeOpacityMask", json!({"clip": true}));
+ obj
+ };
+ masked(&mut s, 0.0);
+ let tile = masked(&mut s, 300.0);
+ exec(&mut s, "object.pattern.make", json!({"ids": [tile.0], "name": "Masked Tile", "edit": false}));
+ let band = rect(&mut s, 0.0, 100.0, 200.0, 40.0);
+ exec(&mut s, "paint.setFill", json!({"ids": [band.0], "swatch": "Masked Tile"}));
+ // An unmasked K100 square, for the color the masked one covers the page with.
+ let solid = rect(&mut s, 100.0, 0.0, 20.0, 20.0);
+ exec(&mut s, "paint.setFill", json!({"ids": [solid.0], "color": {"c": 0, "m": 0, "y": 0, "k": 100}}));
+ let proof = vectorcraft_render::proof::ProofSetup {
+ target: vectorcraft_render::proof::ProofTarget::Cmyk(cms::GENERIC_CMYK.into()),
+ preserve_numbers: true,
+ ..Default::default()
+ };
+ let doc = s.doc().unwrap().doc.clone();
+ let pixel = |px: &[u8], x: usize, y: usize| [px[(y * 200 + x) * 4], px[(y * 200 + x) * 4 + 1], px[(y * 200 + x) * 4 + 2]];
+ // The masked square, the middle of a tile (the tiles start at the art's left and top edges,
+ // every 20 points), the unmasked square and the bare page.
+ let shown = |proof: Option| {
+ let opts = RenderOptions { proof, background: Some([255, 255, 255, 255]), ..Default::default() };
+ let px = Renderer::new().render(&doc, 200, 200, Affine::IDENTITY, &opts).pixels;
+ (pixel(&px, 10, 10), pixel(&px, 50, 130), pixel(&px, 110, 10), pixel(&px, 190, 60))
+ };
+ let (plain, plain_tile, plain_k, plain_page) = shown(None);
+ let (proofed, proofed_tile, proofed_k, proofed_page) = shown(Some(proof));
+ let near = |a: [u8; 3], b: [u8; 3]| a.iter().zip(b).all(|(a, b)| (i32::from(*a) - i32::from(b)).abs() <= 2);
+ assert!(plain != [255; 3] && near(plain, plain_tile), "the tile shows the masked square: {plain:?} vs {plain_tile:?}");
+ assert!(near(proofed, proofed_tile), "the tile's mask covers as the square's does: {proofed:?} vs {proofed_tile:?}");
+ // The proof changes the ink's color but not how much of the page the mask lets it cover.
+ let channel = |v: [u8; 3], i: usize| f32::from(v[i]);
+ let cover = (0..3).map(|i| (channel(plain_page, i) - channel(plain, i)) / (channel(plain_page, i) - channel(plain_k, i))).sum::() / 3.0;
+ assert!(cover > 0.02 && cover < 0.98, "the mask covers part of the square: {cover}");
+ let want: [u8; 3] =
+ std::array::from_fn(|i| (channel(proofed_page, i) + cover * (channel(proofed_k, i) - channel(proofed_page, i))).round() as u8);
+ assert!(near(proofed, want), "the proofed square keeps the mask's coverage: {proofed:?} vs {want:?}");
+}
+
/// Edit › Color Settings' color management policies decide what opening a document tagged with
/// profiles other than the working spaces does with them: Preserve Embedded Profiles keeps them,
/// Off and Preserve Numbers take them off and keep the color numbers, and Convert to Working Space
diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs
index b8114f705c..1413bb17bb 100644
--- a/crates/engine/tests/command_sweep.rs
+++ b/crates/engine/tests/command_sweep.rs
@@ -1278,6 +1278,39 @@ fn polygon_properties_junk() {
assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n"));
}
+/// A live rectangle's and ellipse's Rectangle and Ellipse Angle with junk values, drawn plain,
+/// scaled unevenly, flattened to nothing and sheared: never a panic, and the document stays sound.
+#[test]
+fn rectangle_and_ellipse_angle_junk() {
+ let mut failures = vec![];
+ for (shape, key) in [("shape.rectangle", "rectangleAngle"), ("shape.ellipse", "ellipseAngle")] {
+ for xf in [
+ None,
+ Some(("object.scale", json!({"sx": 300, "sy": 20}))),
+ Some(("object.scale", json!({"sx": 1e-300, "sy": 100}))),
+ Some(("object.shear", json!({"angle": 40}))),
+ ] {
+ for v in junk_values() {
+ let p = json!({ key: v });
+ let mut s = Fixture::Multi.session();
+ let Ok(_) = no_panic(s.execute(shape, &json!({"x": 60, "y": 60, "width": 80, "height": 50}))) else { continue };
+ if let Some((cmd, q)) = &xf {
+ let _ = no_panic(s.execute(cmd, q));
+ }
+ match catch_quiet(|| no_panic(s.execute("object.setLiveShape", &p))) {
+ Err(m) => failures.push(format!("PANIC object.setLiveShape {p} [{xf:?}]: {m}")),
+ Ok(_) => {
+ if let Err(e) = catch_quiet(|| check_all(&mut s)).unwrap_or_else(|m| Err(format!("panic in checks: {m}"))) {
+ failures.push(format!("object.setLiveShape {p} [{xf:?}]: {e}"));
+ }
+ }
+ }
+ }
+ }
+ }
+ assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n"));
+}
+
/// A live line's Line Properties with junk values (the fixtures have no line), on a line, a line
/// whose ends meet and one at the coordinate limit: never a panic, and the document stays sound.
#[test]
diff --git a/crates/engine/tests/import_fuzz.rs b/crates/engine/tests/import_fuzz.rs
index 27ce315d92..b5c069c749 100644
--- a/crates/engine/tests/import_fuzz.rs
+++ b/crates/engine/tests/import_fuzz.rs
@@ -8465,3 +8465,51 @@ proptest! {
prop_assert_eq!(paths, 2, "{:?}", notes);
}
}
+
+proptest! {
+ #![proptest_config(config())]
+
+ /// A stroke's arrowheads (#8188): its arrowhead entries with any scale of any kind, naming a
+ /// symbol the file defines, one it doesn't or one named in Chinese, the symbol's art any run of
+ /// paths (frames, samples of the line, heads, open and closed, filled, stroked or neither), at
+ /// any weight, the style section cut anywhere, the line drawn as any look. Read as a `.ai` and
+ /// as an EPS, then rendered.
+ #[test]
+ fn ai_arrowhead_strokes_never_panic(
+ scale in prop_oneof![arb_num(), Just("50".to_string())],
+ kind in prop::sample::select(vec!["Real", "Int", "Bool"]),
+ named in prop::sample::select(vec!["W", "Missing", "\u{6954}"]),
+ both in any::(),
+ art in prop::collection::vec(prop::sample::select(vec![
+ "-10 5 m\n10 5 L\n10 -5 L\n-10 -5 L\nn\n",
+ "0 G\n1 w\n-9 0 m\n4 0 l\nS\n",
+ "0 G\n0.5 w\n-9 0 m\n4 0 l\nS\n",
+ "0 g\n2 3 m\n8 0 l\n2 -3 l\nf\n",
+ "0 G\n1 w\n2 3 m\n8 0 l\n2 -3 l\nS\n",
+ "0 g\n1e300 0 m\n-1e300 1 l\nf\n",
+ "0 g\n0 0 m\n0 0 l\nf\n",
+ ]), 0..6),
+ width in arb_num(),
+ cut in 0usize..2000,
+ look in prop::sample::select(vec!["0 G\n2 w\n0 50 m\n96 50 l\nS\n0 g\n94 53 m\n100 50 l\n94 47 l\nf\n", "0 G\n2 w\n0 50 m\n100 50 l\nS\n", ""]),
+ ) {
+ use vectorcraft_testkit::ai;
+ let symbol = format!("%AI5_Begin_NonPrinting\n%AI14_BeginSymbol\n(W)\n0 A\n0 Xw\n0 Ae\nu\n{}U\n%AI10_EndSymbol\n%AI5_End_NonPrinting--\n", art.concat());
+ let start = if both { format!("{scale} /{kind} (BSArrowBeginScale) ,\n/GObjRef : ({named}) /SymbolArt ; (BSArrowBeginSymbol) ,\n") } else { String::new() };
+ let styles = format!(
+ "%AI9_BeginArtStyles\n/KnownStyle :\n(Arrowed) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
+ /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\
+ /BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n/Dictionary : /NotRecorded ,\n\
+ {start}{scale} /{kind} (BSArrowEndScale) ,\n/GObjRef : ({named}) /SymbolArt ; (BSArrowEndSymbol) ,\n; (kAIBeautifulStrokesParamsDictKey) ,\n\
+ /StrokeStyle : 0 R\n0 0 0 1 0 0 0 XA\n0 J 0 j {width} w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n; /Dict ;\n /Part ,\n\
+ /BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n /Part ,\n;\n%AI9_EndArtStyles\n\
+ %AI9_BeginArtStyleList\n(Arrowed)\n%AI9_EndArtStyleList\n"
+ );
+ let styles: String = styles.chars().take(cut).collect();
+ let line = format!("0 Ae\nu\n{look}U\n%_0 50 m\n%_100 50 L\n%_N\n1 (Arrowed) XW\n");
+ let data = ai::editing_data(200.0, 100.0, &format!("{symbol}{styles}{}", ai::layer("L", &line)));
+ survive("arrowhead strokes", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false, false, 1.0).0))?;
+ let eps = ai::eps(data.as_bytes(), ai::page_ps());
+ survive("arrowhead strokes in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?;
+ }
+}
diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs
index 28417f031a..30f3ce2665 100644
--- a/crates/engine/tests/it/dimensions.rs
+++ b/crates/engine/tests/it/dimensions.rs
@@ -118,6 +118,68 @@ fn each_arrow_style_draws_its_stroke_arrowhead_at_both_ends() {
}
}
+/// `arrowHead` draws any built-in stroke arrowhead at both ends of the dimension line, and the
+/// native file keeps it. The saved `arrowStyle` stays one of the four values versions without
+/// `arrowHead` read, and a dimension saved without `arrowHead` draws its arrow style. Options
+/// without a stroke head are saved without `arrowHead`. A custom arrowhead, an unknown name and an
+/// overlong name are refused.
+#[test]
+fn every_stroke_arrowhead_draws_as_a_dimension_arrowhead() {
+ use vectorcraft_doc::{Arrowhead, dimension::ArrowStyle};
+ let ends = |s: &Session, id: u64| -> Vec<_> {
+ let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap();
+ let children = n.children().unwrap();
+ let strokes = children.iter().filter_map(|n| n.appearance.stroke().map(|s| (s.start_arrow.clone(), s.end_arrow.clone())));
+ strokes.filter(|(a, b)| a.is_some() || b.is_some()).collect()
+ };
+ let mut s = session();
+ let mut made = vec![];
+ for head in Arrowhead::ALL {
+ let name = serde_json::to_value(&head).unwrap();
+ let id = run(&mut s, "dimension.create", json!({"a":[0,0],"b":[72,0],"options":{"arrowHead":name}}))["id"].as_u64().unwrap();
+ let drawn = ends(&s, id);
+ assert!(!drawn.is_empty() && drawn.iter().all(|h| *h == (Some(head.clone()), Some(head.clone()))), "{name}: {drawn:?}");
+ let saved = serde_json::to_value(&recipe(&s, id).options).unwrap();
+ assert_eq!((&saved["arrowStyle"], &saved["arrowHead"]), (&json!("filled"), &name));
+ made.push((id, head));
+ }
+ let bytes = vectorcraft_format::save(&s.doc().unwrap().doc, false);
+ let mut reopened = Session::new();
+ reopened.add_document(vectorcraft_format::load(&bytes).unwrap(), None);
+ for (id, head) in made {
+ assert_eq!(recipe(&reopened, id).options.arrowhead(), Some(head));
+ }
+ // A dimension saved before `arrowHead` existed.
+ let id = run(&mut s, "dimension.create", json!({"a":[0,0],"b":[72,0],"options":{"arrowStyle":"open"}}))["id"].as_u64().unwrap();
+ let mut file: Value = serde_json::from_slice(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
+ fn drop_head(v: &mut Value) {
+ match v {
+ Value::Object(m) => {
+ m.remove("arrowHead");
+ m.values_mut().for_each(drop_head);
+ }
+ Value::Array(a) => a.iter_mut().for_each(drop_head),
+ _ => {}
+ }
+ }
+ drop_head(&mut file);
+ let mut older = Session::new();
+ older.add_document(vectorcraft_format::load(&serde_json::to_vec(&file).unwrap()).unwrap(), None);
+ let o = recipe(&older, id).options;
+ assert_eq!((o.arrow_style, o.arrow_head.clone(), o.arrowhead()), (ArrowStyle::Open, None, Some(Arrowhead::TriangleOpen)));
+ // Without a stroke head, the saved and recorded options carry no `arrowHead`, and a null one
+ // is still taken.
+ let saved = serde_json::to_value(&recipe(&s, id).options).unwrap();
+ assert!(saved.get("arrowHead").is_none(), "{saved}");
+ assert!(s.execute("dimension.create", &json!({"a":[0,0],"b":[72,0],"options":{"arrowHead":null}})).is_ok());
+ let custom = json!({"Custom":{"name":"Dot","path":{"subpaths":[]}}});
+ for bad in [json!("Custom"), json!("Arrowhead"), json!("barbed"), json!(3), json!("Barbed".repeat(20)), custom] {
+ let p = json!({"a":[0,0],"b":[72,0],"options":{"arrowHead":bad}});
+ assert!(s.execute("dimension.create", &p).is_err(), "{bad}");
+ }
+ assert!(s.execute("dimension.create", &json!({"a":[0,0],"b":[72,0],"options":{"arrowStyle":"Barbed"}})).is_err());
+}
+
#[test]
fn dimension_angles_circles_arcs_and_curves() {
let mut s = session();
diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs
index c630c9cf43..4c574ce3bb 100644
--- a/crates/eps/src/import/ai.rs
+++ b/crates/eps/src/import/ai.rs
@@ -17,6 +17,7 @@
//! objects and points. Anything it doesn't read is an error: the caller opens the file the way it
//! did before (the printed page, or the PDF), with a warning saying why.
+mod arrowhead;
mod blend;
mod brush;
mod envelope;
diff --git a/crates/eps/src/import/ai/arrowhead.rs b/crates/eps/src/import/ai/arrowhead.rs
new file mode 100644
index 0000000000..f1a30c08af
--- /dev/null
+++ b/crates/eps/src/import/ai/arrowhead.rs
@@ -0,0 +1,244 @@
+//! Arrowheads a file defines: the art of a symbol that a stroke's arrowhead entry names
+//! ([`super::style::StrokeArrows`]), read into a head ([`head`]).
+//!
+//! Not publicly documented. As the files have it, an arrowhead symbol's art (y down here, as the
+//! document's symbols are) points right along a straight, level sample of the line it ends: an
+//! open stroked path with no fill whose anchors and handles all lie on that line, 1 pt wide. The
+//! sample ends where the line stops under the head. The rest of the art that paints is the head;
+//! its tip is its rightmost point, and a symbol unit is one point on a 1 pt stroke at 100 %, so a
+//! unit is the head's weight as it is for VectorCraft's own heads. Art that paints nothing (the
+//! frame of the symbol's box, hidden or fully transparent art) is left out.
+
+use vectorcraft_doc::{AppearanceItem, CustomArrowhead, Node, NodeKind, StrokeLayer};
+use vectorcraft_geom::{Affine, FillRule, PathData, Point};
+
+/// The most anchors an arrowhead symbol's art is read with, outlined strokes included, before its
+/// shapes are united.
+const MAX_ART_ANCHORS: usize = 65_536;
+/// How deep the groups of an arrowhead symbol's art are read.
+const MAX_DEPTH: usize = 16;
+
+/// The head that symbol art `art` (in the document's symbol space) draws, named `name`. `None` when
+/// the art doesn't have exactly one sample of the line, its sample isn't 1 pt wide, it holds
+/// anything but paths, compound paths and groups (a clip group, say), has an effect, a brush, an
+/// opacity mask, partial opacity or a group with fills or strokes of its own, paints no head, or is
+/// too detailed for one; or when the
+/// line would stop past the head's tip or farther back than a head can reach
+/// ([`CustomArrowhead::MAX_UNITS`]).
+pub(super) fn head(name: &str, art: &Node) -> Option {
+ let mut parts = Parts::default();
+ match &art.kind {
+ // The members of the symbol's group are its art's top level, where the sample is.
+ NodeKind::Group { children, clip: false } if art.visible && plain(art) && !paints(art) => {
+ for c in children {
+ parts.member(c, true, 1)?;
+ }
+ }
+ _ => parts.member(art, true, 0)?,
+ }
+ let [(axis, line_end)] = parts.lines.as_slice() else { return None };
+ if parts.shapes.is_empty() {
+ return None;
+ }
+ let refs: Vec<(&PathData, FillRule)> = parts.shapes.iter().map(|(p, r)| (p, *r)).collect();
+ let area = vectorcraft_pathops::try_unite_all(&refs).ok()?;
+ let b = area.bounds().filter(|b| b.is_finite() && b.height() > 1e-9)?;
+ let tip = b.x1;
+ // Head units: x back from the tip, y across to the right of the way the head points (down).
+ let h = CustomArrowhead::new(name.to_string(), area.transformed(Affine::new([-1.0, 0.0, 0.0, 1.0, tip, -axis])));
+ let h = h.with_stop(tip - line_end);
+ (!h.path.subpaths.is_empty() && h.stop.is_some()).then_some(h)
+}
+
+/// What an arrowhead symbol's art is made of.
+#[derive(Default)]
+struct Parts {
+ /// Each sample of the line: the line's y, and the x where the sample ends.
+ lines: Vec<(f64, f64)>,
+ /// The areas the head paints.
+ shapes: Vec<(PathData, FillRule)>,
+ anchors: usize,
+}
+
+impl Parts {
+ /// Read `n`, a member of the art (`top`: of its top level) `depth` groups down. `None` when it
+ /// is something [`head`] doesn't read.
+ fn member(&mut self, n: &Node, top: bool, depth: usize) -> Option<()> {
+ if depth > MAX_DEPTH {
+ return None;
+ }
+ // Hidden or fully transparent art paints nothing.
+ if !n.visible || n.opacity <= 0.0 {
+ return Some(());
+ }
+ if !plain(n) {
+ return None;
+ }
+ match &n.kind {
+ NodeKind::Group { children, clip: false } => {
+ if paints(n) {
+ return None;
+ }
+ children.iter().try_for_each(|c| self.member(c, false, depth + 1))
+ }
+ NodeKind::Path { guide: true, .. } => Some(()),
+ NodeKind::Path { path, rule, .. } => self.painted(n, path, *rule, top),
+ NodeKind::Compound { children, rule } => {
+ let mut subpaths = vec![];
+ for c in children {
+ subpaths.extend(c.path_data()?.subpaths.iter().cloned());
+ }
+ self.painted(n, &PathData::new(subpaths), *rule, false)
+ }
+ _ => None,
+ }
+ }
+
+ /// Read the fills and strokes of path or compound path `n`, its outline `path` filled under
+ /// `rule` (`top`: a member of the art's top level, which may be the sample of the line).
+ fn painted(&mut self, n: &Node, path: &PathData, rule: FillRule, top: bool) -> Option<()> {
+ self.room(path.anchor_count())?;
+ let mut filled = false;
+ let mut strokes: Vec<&StrokeLayer> = vec![];
+ for item in &n.appearance.items {
+ match item {
+ AppearanceItem::Fill(f) if f.visible && f.opacity > 0.0 && !f.paint.is_none() => {
+ if !f.effects.is_empty() || f.opacity < 1.0 {
+ return None;
+ }
+ filled = true;
+ }
+ AppearanceItem::Stroke(s) if s.visible && s.opacity > 0.0 && !s.paint.is_none() && s.width > 0.0 => {
+ if !s.effects.is_empty() || s.brush.is_some() || s.opacity < 1.0 {
+ return None;
+ }
+ strokes.push(s);
+ }
+ _ => {}
+ }
+ }
+ if top
+ && !filled
+ && let [line] = strokes.as_slice()
+ && let Some(sample) = sample_line(path)
+ {
+ // The sample is 1 pt, the weight of a head at one unit; another weight (art stored
+ // at another scale, as a Large Canvas file's) gives the units no known size.
+ if (line.width - 1.0).abs() > 1e-6 {
+ return None;
+ }
+ self.lines.push(sample);
+ return Some(());
+ }
+ if filled {
+ self.shapes.push((path.clone(), rule));
+ }
+ for s in strokes {
+ let outline = vectorcraft_effects::stroke::outline_region(path, rule, s);
+ self.room(outline.anchor_count())?;
+ if !outline.subpaths.is_empty() {
+ self.shapes.push((outline, FillRule::NonZero));
+ }
+ }
+ Some(())
+ }
+
+ /// Count `anchors` more; `None` past [`MAX_ART_ANCHORS`].
+ fn room(&mut self, anchors: usize) -> Option<()> {
+ self.anchors = self.anchors.saturating_add(anchors);
+ (self.anchors <= MAX_ART_ANCHORS).then_some(())
+ }
+}
+
+/// Does `n` draw as its shapes alone: fully opaque, with no effects and no opacity mask applied?
+/// A head is one opaque shape, so partly transparent or masked art isn't read as one.
+fn plain(n: &Node) -> bool {
+ n.opacity >= 1.0 && n.appearance.effects.is_empty() && n.extras().mask.as_ref().is_none_or(|m| m.disabled)
+}
+
+/// Does `n` (a group) have fills or strokes of its own that paint?
+fn paints(n: &Node) -> bool {
+ n.appearance.items.iter().any(|i| match i {
+ AppearanceItem::Fill(f) => f.visible && !f.paint.is_none(),
+ AppearanceItem::Stroke(s) => s.visible && !s.paint.is_none(),
+ })
+}
+
+/// `path` as a sample of the line, when it is one open subpath of two anchors or more whose anchors
+/// and handles all lie level with its first anchor: that y, and the x where it ends (its
+/// rightmost anchor).
+fn sample_line(path: &PathData) -> Option<(f64, f64)> {
+ let [sub] = path.subpaths.as_slice() else { return None };
+ if sub.closed || sub.anchors.len() < 2 {
+ return None;
+ }
+ let y = sub.anchors.first()?.p.y;
+ let level = |q: Point| q.x.is_finite() && (q.y - y).abs() <= 1e-6 * (1.0 + y.abs());
+ if !y.is_finite() || !sub.anchors.iter().all(|a| level(a.p) && level(a.h_in) && level(a.h_out)) {
+ return None;
+ }
+ Some((y, sub.anchors.iter().map(|a| a.p.x).fold(f64::NEG_INFINITY, f64::max)))
+}
+
+#[cfg(test)]
+mod tests {
+ use std::sync::Arc;
+
+ use vectorcraft_color::{Color, Paint};
+ use vectorcraft_doc::{Appearance, Node, NodeId, OpacityMask};
+ use vectorcraft_geom::{PathData, Point, SubPath};
+
+ use super::head;
+
+ fn path(id: u64, points: &[(f64, f64)], closed: bool, appearance: Appearance) -> Arc {
+ let points: Vec