Merge main into feat/3d-custom-bevels

This commit is contained in:
dotCooCoo
2026-11-19 11:13:58 -08:00
303 changed files with 23716 additions and 1340 deletions
+1
View File
@@ -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 |
Generated
+44 -40
View File
@@ -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",
+32 -32
View File
@@ -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" }
+2
View File
@@ -128,6 +128,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-14: Built-in symbol library Weather Icons: adds a sixth procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Sun, Moon, Cloud, Rain, Thunder, Snow) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
- 2026-11-14: Built-in Tech Circuit brush library: Circuit Trace (chamfered art with 45-degree elbows and terminal pads), Bus Lines (parallel conductor pattern) and Terminal Nodes (repeating solder pads, test points and leads), all original geometry generated in code. Ten built-in brush libraries; G5 remaining estimate 3–13 h (estimated), headline numbers unchanged.
- 2026-11-18: Built-in Paint brush library: Flat Sweep, Dry Drag, Loaded Stroke and Fan Sweep, original art brushes generated in code that take the stroke color as tints. Thirteen built-in brush libraries; headline numbers unchanged.
- 2026-11-05: Window › Toolbars › Keep Tools Beside the Canvas, off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and the canvas's left edge then also docks a floating Tools panel (`window.toolsBesideCanvas`, #5395). Workspaces keep the setting; workspaces saved without it keep Tools at the window's edge. An optional VectorCraft layout choice; headline numbers unchanged.
- 2026-11-17: The canvas's left edge docks a floating Tools panel whichever way Keep Tools Beside the Canvas is set: a drop there, right of panels docked on the left, turns the setting on, and a drop on the window's left edge turns it off (#7837). Headline numbers unchanged.
@@ -162,6 +163,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-17: Tangent Circle Tool joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools, and the All Tools drawer): click a path segment, then another, to draw the circle tangent to the first where it was clicked that touches the second; Shift uses the tool's radius and a drag from the second segment sets the radius (Shift in round steps, Cmd/Ctrl slowly), the circle then touching the first segment anywhere along it. The circle shows with its center and radii before the click, one undo step (`tangentCircle`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-18: Common Tangents also takes a point (a path of one anchor) and a convex closed path: the lines from the point that touch the path, and the line from the point to the path's center if asked; a point on the outline gets the one tangent there, and a point inside gets none, with a message (#7846). A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged.
- 2026-11-17: Three-Point Arc tool, in the Line Segment tool's group after the Arc tool: two ends placed by a drag or two clicks, then a third point the open circular arc passes through, or with Third Point Sets Direction (Tool Options, or `]` while drawing) the direction the arc leaves an end in; it previews the arc, its center and, with Measurement Labels on, its radius, and draws it in one undo step (`shape.threePointArc`). Points with no arc are refused with a message. A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-18: Smooth Bridge also joins three or more circles: every two whose outlines are within Reach (10 pt by default) are joined, the bridges that connect become one shape each, and a circle bridged to no other stays as it is (at most 2000 circles); with Constant Gap the arcs' radius is the smaller circle's radius plus a gap (#8030). A VectorCraft addition: headline numbers unchanged.
- 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged.
+1
View File
@@ -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);
+1 -1
View File
@@ -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 }
+1
View File
@@ -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);
+8
View File
@@ -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.
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 18 A8.67 8.67 0 1 1 20 18"/><circle cx="4" cy="18" r="1.6"/><circle cx="12" cy="6" r="1.6"/><circle cx="20" cy="18" r="1.6"/></svg>

After

Width:  |  Height:  |  Size: 327 B

+5 -41
View File
@@ -534,47 +534,13 @@ fn plain(by_pen: &[Vec<Vec<(i64, i64)>>]) -> Vec<u8> {
/// HP-GL/2: `IN;`, the palette, each pen's paths as one `PE`, `PU;SP0;`.
fn encoded(by_pen: &[Vec<Vec<(i64, i64)>>], pens: &[[u8; 3]]) -> Vec<u8> {
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<u8>, 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();
+19
View File
@@ -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()) });
+22 -8
View File
@@ -34,6 +34,7 @@ const WIDE_LINES: &str =
"lines wider than 2.11 mm (the widest lineweight) are written at 2.11 mm: Alter Paths for Appearance writes their true width";
const STROKE_EXTRAS: &str = "stroke alignment, width profiles, arrowheads and brushes are left out (Maximize Editability writes strokes as lines)";
const CLIPPING: &str = "clipping masks are not applied: the art they clip is written whole";
const DISTORTED_IMAGES: &str = "images changed by Perspective Distort or Free Distort are written as the nearest parallelogram";
const TYPE_ITEMS: &str = "fills and strokes added to whole type objects are left out of text entities (outline the text to keep them)";
/// The warning for an image left out because it can't be decoded: the note raster exports give
/// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`).
@@ -671,7 +672,18 @@ impl<'a> Scene<'a> {
self.shape(n, &bp, *rule);
}
NodeKind::Text(t) => self.text(n, t),
NodeKind::Image(im) => self.image(&self.doc.shown_image(n, im)),
NodeKind::Image(im) => match vectorcraft_doc::image_quad::nearest_affine(n) {
// DXF clips nothing, so a distorted image is written at the affine placement nearest
// its corners, with the warning once it is written.
Some(xf) => {
if self.image(&ImageObject { xf, ..self.doc.shown_image(n, im).into_owned() }) {
self.warn(DISTORTED_IMAGES);
}
}
None => {
self.image(&self.doc.shown_image(n, im));
}
},
NodeKind::SymbolInstance { symbol, xf } => {
let doc = self.doc;
if self.symbol_nodes >= vectorcraft_doc::MAX_SYMBOL_NODES {
@@ -1325,18 +1337,19 @@ impl<'a> Scene<'a> {
name
}
/// A placed image, linked to its file (written once per image).
fn image(&mut self, im: &ImageObject) {
/// A placed image, linked to its file (written once per image). False when no `IMAGE` entity is
/// written.
fn image(&mut self, im: &ImageObject) -> bool {
if !self.o.version.handles() {
self.warn(NO_IMAGES);
return;
return false;
}
if !self.o.include_images {
self.note_setting(IMAGES_OFF);
return;
return false;
}
let Some(i) = self.image_def(im) else { return };
let Some((dw, dh)) = self.images.get(i).map(|d| (f64::from(d.size.0), f64::from(d.size.1))) else { return };
let Some(i) = self.image_def(im) else { return false };
let Some((dw, dh)) = self.images.get(i).map(|d| (f64::from(d.size.0), f64::from(d.size.1))) else { return false };
let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
let map = self.to_dxf * im.xf;
let lin = |v: kurbo::Vec2| (map * v.to_point()) - (map * Point::ZERO);
@@ -1349,7 +1362,7 @@ impl<'a> Scene<'a> {
let at = map * Point::new(0.0, h);
let handle = self.handle();
let reactor = self.handle();
let Some(def) = self.images.get_mut(i) else { return };
let Some(def) = self.images.get_mut(i) else { return false };
def.reactors.push((reactor, handle));
let def = def.handle;
let layer = self.layer.clone();
@@ -1375,6 +1388,7 @@ impl<'a> Scene<'a> {
if self.o.version >= crate::DxfVersion::R2010 {
self.e.int(290, 0);
}
true
}
/// The image file for image `im`, encoded once in the chosen format (`None`: left out).
+31
View File
@@ -984,6 +984,37 @@ fn images_can_be_left_out_with_their_files() {
assert!(r12.warnings.iter().any(|w| w.contains("no images")) && r12.setting_notes.is_empty());
}
/// DXF does not clip, so an image changed by Perspective Distort is written as one image at the
/// placement nearest its corners, with a warning; an undistorted image gets no warning.
#[test]
fn a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning() {
let mut d = image_and_fill_doc(Paint::None);
let warned = |o: &DxfOutput| o.warnings.iter().any(|w| w.contains("Perspective Distort or Free Distort"));
assert!(!warned(&export(&d, &opts(&d)).unwrap()));
let id = d.layers[0].children().unwrap()[1].id;
let q = [(12.0, 20.0), (28.0, 20.0), (30.0, 30.0), (10.0, 30.0)].map(|(x, y)| Point::new(x, y));
d.node_mut(id).unwrap().set_image_corners(q).unwrap();
let out = export(&d, &opts(&d)).unwrap();
assert!(warned(&out), "{:?}", out.warnings);
assert_eq!(kinds(&out).iter().filter(|k| *k == "IMAGE").count(), 1, "{:?}", kinds(&out));
// Placed as an undistorted image with the nearest affine placement as its transform would be.
let near = vectorcraft_doc::image_quad::nearest_affine(d.node(id).unwrap()).unwrap();
let mut plain = d.clone();
let n = plain.node_mut(id).unwrap();
n.extras_mut().image_quad = None;
if let NodeKind::Image(im) = &mut n.kind {
im.xf = near;
}
let placement = |o: &DxfOutput| {
let e = entities(o).into_iter().find(|e| kind(e) == "IMAGE").expect("an IMAGE");
[10, 20, 11, 21, 12, 22].map(|c| all(&e, c))
};
assert_eq!(placement(&out), placement(&export(&plain, &opts(&plain)).unwrap()));
// With images left out, no IMAGE is written and the distortion warning does not appear.
let left_out = export(&d, &DxfOptions { include_images: false, ..opts(&d) }).unwrap();
assert!(!warned(&left_out), "{:?}", left_out.warnings);
}
#[test]
fn images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both() {
let d = image_and_fill_doc(Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
+109 -6
View File
@@ -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<ProofLut> {
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")]
+94
View File
@@ -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.
+19
View File
@@ -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]
+6 -3
View File
@@ -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())
+97
View File
@@ -10,6 +10,7 @@ pub mod freeform;
pub mod gradient;
pub mod harmony;
pub mod libraries;
pub mod oklab;
pub mod palette_io;
pub mod recolor;
pub mod swatch;
@@ -340,6 +341,49 @@ pub fn hsb_to_rgb([h, s, v]: [f32; 3]) -> [f32; 3] {
[r + m, g + m, b + m]
}
/// HSL (hue in degrees 0..360, saturation and lightness 0..1) of RGB numbers 0..1, with no color
/// conversion, as CSS Color 4 converts sRGB to HSL
/// (<https://www.w3.org/TR/css-color-4/#rgb-to-hsl>). The hue is 0 while the saturation is
/// powerless, and a color outside 0..1 that gives a negative saturation turns its hue by 180°. As in
/// the specification's conversion, a lightness of 0.00001 or less, a lightness less than 0.00001
/// below 1, or a saturation of 0.00001 or less reads as a gray.
pub fn rgb_to_hsl([r, g, b]: [f32; 3]) -> [f32; 3] {
const EPSILON: f32 = 1e-5;
let max = r.max(g).max(b);
let min = r.min(g).min(b);
let d = max - min;
let l = (max + min) / 2.0;
if d <= 0.0 {
return [0.0, 0.0, l];
}
let mut s = if l.abs() <= EPSILON || (1.0 - l).abs() < EPSILON { 0.0 } else { (max - l) / l.min(1.0 - l) };
let mut h = rgb_to_hsb([r, g, b])[0];
if s < 0.0 {
h += 180.0;
s = -s;
}
if s <= EPSILON {
return [0.0, 0.0, l];
}
let h = h.rem_euclid(360.0);
[if h >= 360.0 { 0.0 } else { h }, s, l]
}
/// RGB numbers 0..1 of HSL `[h, s, l]` (hue in degrees, saturation and lightness 0..1), as CSS
/// Color 4 converts HSL to sRGB (<https://www.w3.org/TR/css-color-4/#hsl-to-rgb>): the inverse of
/// [`rgb_to_hsl`]. A hue outside 0..360 wraps into that range before the conversion, so -120°
/// gives the color of 240° and a hue of 10,000,000,000° the color of 280°. The specification's
/// sample code uses JavaScript's remainder operator and gives a different color for a negative hue.
pub fn hsl_to_rgb([h, s, l]: [f32; 3]) -> [f32; 3] {
let h = h.rem_euclid(360.0);
let a = s * l.min(1.0 - l);
let f = |n: f32| {
let k = (n + h / 30.0).rem_euclid(12.0);
l - a * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0)
};
[f(0.0), f(8.0), f(4.0)]
}
/// `new` expressed in the colour model of `orig` ([`Color::in_model`]): results of colour operations
/// (harmonies, blends, inversions, recolouring) keep the model of the colour they came from.
pub fn keep_model(orig: Color, new: Color) -> Color {
@@ -499,6 +543,59 @@ mod tests {
}
}
/// The HSL examples of CSS Color 4, section 7 (<https://www.w3.org/TR/css-color-4/#the-hsl-notation>),
/// the first six rows, and two hues outside 0..360 that wrap into that range.
#[test]
fn hsl_follows_css_color_4() {
for (hsl, hex) in [
([0.0, 1.0, 0.5], "#ff0000"),
([120.0, 1.0, 0.5], "#00ff00"),
([120.0, 1.0, 0.25], "#008000"),
([120.0, 1.0, 0.75], "#80ff80"),
([240.0, 1.0, 0.5], "#0000ff"),
([60.0, 1.0, 0.5], "#ffff00"),
([360.0, 1.0, 0.5], "#ff0000"),
([-120.0, 1.0, 0.5], "#0000ff"),
] {
let [r, g, b] = hsl_to_rgb(hsl);
assert_eq!(Color::rgb(r, g, b).to_hex(), hex, "{hsl:?}");
}
let [h, s, l] = rgb_to_hsl([1.0, 0.5, 0.0]);
assert!((h - 30.0).abs() < 1e-4 && (s - 1.0).abs() < 1e-6 && (l - 0.5).abs() < 1e-6, "{h} {s} {l}");
let [h, s, l] = rgb_to_hsl(Color::rgb8(255, 128, 0).to_rgb_uncalibrated());
assert!((h - 30.0).abs() < 0.2 && (s - 1.0).abs() < 1e-6 && (l - 0.5).abs() < 1e-3, "{h} {s} {l}");
// A gray has no hue: the hue is 0 and the saturation 0, at any lightness.
for v in [0.0, 0.25, 0.5, 1.0] {
assert_eq!(rgb_to_hsl([v, v, v]), [0.0, 0.0, v]);
}
// Black and white keep any hue and saturation they are given.
assert_eq!(hsl_to_rgb([200.0, 0.7, 0.0]), [0.0, 0.0, 0.0]);
assert_eq!(hsl_to_rgb([200.0, 0.7, 1.0]), [1.0, 1.0, 1.0]);
// A color past the gamut that gives a negative saturation turns its hue by 180°.
let [h, s, _] = rgb_to_hsl([1.2, 1.5, 1.4]);
assert!(s > 0.0 && (h - (160.0 + 180.0)).abs() < 1e-3, "{h} {s}");
// A huge hue wraps before the channels are worked out: 10,000,000,000° is 280°.
let (huge, wrapped) = (hsl_to_rgb([10_000_000_000.0, 1.0, 0.5]), hsl_to_rgb([280.0, 1.0, 0.5]));
assert!((0..3).all(|i| (huge[i] - wrapped[i]).abs() < 1e-6), "{huge:?} {wrapped:?}");
}
/// The 216 web colors go to HSL and back to the same 8-bit color.
#[test]
fn hsl_roundtrip() {
let steps = [0x00, 0x33, 0x66, 0x99, 0xcc, 0xff];
for r in steps {
for g in steps {
for b in steps {
let c = Color::rgb8(r, g, b);
let [h, s, l] = rgb_to_hsl(c.to_rgb_uncalibrated());
assert!((0.0..360.0).contains(&h) && (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&l), "{}", c.to_hex());
let back = hsl_to_rgb([h, s, l]).map(|v| (v * 255.0).round() as u8);
assert_eq!(back, [r, g, b], "{}", c.to_hex());
}
}
}
}
#[test]
fn cmyk_conversions() {
assert_eq!(Color::cmyk(0.0, 0.0, 0.0, 1.0).to_rgb_uncalibrated(), [0.0, 0.0, 0.0]);
+14 -6
View File
@@ -99,18 +99,24 @@ pub fn builtin_library(id: &str) -> Option<Arc<SwatchLibrary>> {
// ---------- colour construction ----------
/// sRGB (0..=1, gamma encoded) of OKLab `(l, a, b)`, unclamped.
/// sRGB (0..=1, gamma encoded) of OKLab `(l, a, b)`, unclamped. A linear channel below
/// −0.0031308 is encoded with the curve's sign turned, as CSS Color 4's extended sRGB does
/// (<https://www.w3.org/TR/css-color-4/#color-conversion-code>).
pub(crate) fn oklab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] {
oklab_to_linear_srgb(l, a, b).map(|v| if v.abs() <= 0.003_130_8 { 12.92 * v } else { v.signum() * (1.055 * v.abs().powf(1.0 / 2.4) - 0.055) })
}
/// Linear sRGB of OKLab `(l, a, b)`, unclamped.
pub(crate) fn oklab_to_linear_srgb(l: f64, a: f64, b: f64) -> [f64; 3] {
let l_ = l + 0.396_337_777_4 * a + 0.215_803_757_3 * b;
let m_ = l - 0.105_561_345_8 * a - 0.063_854_172_8 * b;
let s_ = l - 0.089_484_177_5 * a - 1.291_485_548_0 * b;
let (l3, m3, s3) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
let lin = [
[
4.076_741_662_1 * l3 - 3.307_711_591_3 * m3 + 0.230_969_929_2 * s3,
-1.268_438_004_6 * l3 + 2.609_757_401_1 * m3 - 0.341_319_396_5 * s3,
-0.004_196_086_3 * l3 - 0.703_418_614_7 * m3 + 1.707_614_701_0 * s3,
];
lin.map(|v| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 })
]
}
/// OKLab `[l, a, b]` of a colour's display RGB.
@@ -118,11 +124,13 @@ pub fn to_oklab(c: &Color) -> [f64; 3] {
srgb_to_oklab(c.to_rgb_uncalibrated())
}
/// OKLab `[l, a, b]` of sRGB `rgb` (0..=1, gamma encoded).
/// OKLab `[l, a, b]` of sRGB `rgb` (0..=1, gamma encoded). A channel below −0.04045 is decoded
/// with the curve's sign turned, as CSS Color 4's extended sRGB does
/// (<https://www.w3.org/TR/css-color-4/#color-conversion-code>).
pub(crate) fn srgb_to_oklab(rgb: [f32; 3]) -> [f64; 3] {
let [r, g, b] = rgb.map(|v| {
let v = f64::from(v);
if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
if v.abs() <= 0.040_45 { v / 12.92 } else { v.signum() * ((v.abs() + 0.055) / 1.055).powf(2.4) }
});
let l = (0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b).cbrt();
let m = (0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b).cbrt();
+266
View File
@@ -0,0 +1,266 @@
//! OKLCH, the polar form of Oklab, as CSS Color 4 defines it
//! (<https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch>): lightness L from 0 to 1, chroma
//! C (CSS reads 100% as 0.4) and hue H in degrees from the positive `a` axis. The conversions take
//! and give gamma-encoded sRGB through the Oklab matrices of [`crate::libraries`].
use crate::libraries::{oklab_to_linear_srgb, oklab_to_srgb, srgb_to_oklab};
/// The chroma CSS reads as 100%.
pub const CHROMA_FULL: f64 = 0.4;
/// Chroma at or below which the hue is powerless (CSS Color 4's ε); [`to_oklch`] gives hue 0 there.
pub const POWERLESS_CHROMA: f64 = 0.000_004;
/// How far outside 0..=1 an sRGB component may be and still count as inside the gamut.
const GAMUT_SLACK: f64 = 1e-4;
/// OKLCH `[l, c, h°]` of sRGB `rgb` (gamma encoded). Values outside 0..=1 are converted as they
/// are. The hue is in 0..360, and 0 while the chroma is powerless.
pub fn to_oklch(rgb: [f32; 3]) -> [f64; 3] {
let [l, a, b] = srgb_to_oklab(rgb);
let c = a.hypot(b);
if c <= POWERLESS_CHROMA {
return [l, 0.0, 0.0];
}
[l, c, b.atan2(a).to_degrees().rem_euclid(360.0)]
}
/// sRGB (gamma encoded) of OKLCH `(l, c, h°)`, unclamped.
pub fn oklch_to_srgb(l: f64, c: f64, h: f64) -> [f64; 3] {
let (sin, cos) = h.to_radians().sin_cos();
oklab_to_srgb(l, c * cos, c * sin)
}
/// Whether sRGB `rgb` lies inside the sRGB gamut.
pub fn in_srgb(rgb: [f64; 3]) -> bool {
rgb.iter().all(|v| (-GAMUT_SLACK..=1.0 + GAMUT_SLACK).contains(v))
}
/// The largest chroma sRGB holds at lightness `l` and hue `h°`: 0 at or outside black and white.
pub fn max_chroma(l: f64, h: f64) -> f64 {
largest_fitting_chroma(l, h, f64::INFINITY)
}
/// The largest chroma no more than `limit` that sRGB holds at lightness `l` and hue `h°`: 0 at or
/// outside black and white.
///
/// The chromas sRGB holds along the ray can come in several stretches: at the lightness and hue of
/// blue the ray leaves sRGB at a chroma of about 0.266 and comes back at blue itself, about 0.313,
/// and near black the gamut slack opens stretches of its own. Each linear sRGB channel is a cubic
/// in the chroma, so every stretch ends where a channel's cubic meets a bound of the gamut. The
/// search finds each such chroma between the cubic's turning points and takes the largest one that
/// fits.
fn largest_fitting_chroma(l: f64, h: f64, limit: f64) -> f64 {
if !(l > 0.0 && l < 1.0) || !h.is_finite() {
return 0.0;
}
let top = limit.min(0.5);
if top <= 0.0 {
return 0.0;
}
let fits = |c: f64| in_srgb(oklch_to_srgb(l, c, h));
if fits(top) {
return top;
}
let (sin, cos) = h.to_radians().sin_cos();
let lin = |c: f64| oklab_to_linear_srgb(l, c * cos, c * sin);
// The linear channels at chromas 0, s, 2s and 3s give each cubic's coefficients in t = c / s.
let s = top / 3.0;
let y = [lin(0.0), lin(s), lin(2.0 * s), lin(3.0 * s)];
let bounds = [-GAMUT_SLACK / 12.92, ((1.0 + GAMUT_SLACK + 0.055) / 1.055).powf(2.4)];
let mut ends = vec![0.0];
for ch in 0..3 {
let [y0, y1, y2, y3] = [y[0][ch], y[1][ch], y[2][ch], y[3][ch]];
let (d1, d2, d3) = (y1 - y0, y2 - 2.0 * y1 + y0, y3 - 3.0 * y2 + 3.0 * y1 - y0);
let k = [y0, d1 - d2 / 2.0 + d3 / 3.0, d2 / 2.0 - d3 / 2.0, d3 / 6.0];
let p = |t: f64| ((k[3] * t + k[2]) * t + k[1]) * t + k[0];
// The cubic rises or falls on each stretch between its turning points.
let mut cuts = vec![0.0, 3.0];
cuts.extend(turning_points(3.0 * k[3], 2.0 * k[2], k[1]).into_iter().filter(|t| *t > 0.0 && *t < 3.0));
cuts.sort_by(f64::total_cmp);
ends.extend(cuts.iter().map(|t| t * s));
for w in cuts.windows(2) {
for bound in bounds {
let (mut a, mut b) = (w[0], w[1]);
let fa = p(a) - bound;
if fa * (p(b) - bound) > 0.0 {
continue;
}
for _ in 0..60 {
let mid = (a + b) / 2.0;
if (p(mid) - bound) * fa > 0.0 { a = mid } else { b = mid }
}
ends.extend([a * s, b * s]);
}
}
}
ends.sort_by(|a, b| b.total_cmp(a));
ends.into_iter().flat_map(|c| [c, c - 1e-9]).find(|c| (0.0..=top).contains(c) && fits(*c)).unwrap_or(0.0)
}
/// The real roots of `a t² + b t + c`.
fn turning_points(a: f64, b: f64, c: f64) -> Vec<f64> {
if a.abs() < 1e-15 {
return if b.abs() < 1e-15 { Vec::new() } else { vec![-c / b] };
}
let disc = b * b - 4.0 * a * c;
if disc < 0.0 {
return Vec::new();
}
let r = disc.sqrt();
vec![(-b - r) / (2.0 * a), (-b + r) / (2.0 * a)]
}
/// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered:
/// a color outside sRGB keeps its lightness and hue and takes the largest chroma below it that
/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more.
pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) {
let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) };
let c = if c.is_nan() { 0.0 } else { c.max(0.0) };
let h = if h.is_finite() { h } else { 0.0 };
let exact = oklch_to_srgb(l, c, h);
let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, largest_fitting_chroma(l, h, c), h), true) };
(rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered)
}
#[cfg(test)]
mod tests {
use super::*;
fn eight(rgb: [f32; 3]) -> [u8; 3] {
rgb.map(|v| (v * 255.0).round() as u8)
}
#[test]
fn red_has_the_oklch_of_the_oklab_matrices_and_converts_back() {
let [l, c, h] = to_oklch([1.0, 0.0, 0.0]);
assert!((l - 0.6280).abs() < 5e-5 && (c - 0.2577).abs() < 5e-5 && (h - 29.23).abs() < 5e-3, "{l} {c} {h}");
let (rgb, lowered) = from_oklch(l, c, h);
assert_eq!((eight(rgb), lowered), ([255, 0, 0], false));
}
/// CSS Color 4's examples convert to the hue its oklab() and oklch() forms give.
#[test]
fn the_polar_form_matches_the_css_examples() {
for ([l, a, b], [cl, cc, ch]) in
[([0.40101, 0.1147, 0.0453], [0.40101, 0.12332, 21.555]), ([0.65125, -0.0320, 0.1274], [0.65125, 0.13138, 104.097])]
{
let rgb = oklab_to_srgb(l, a, b).map(|v| v as f32);
let [ol, oc, oh] = to_oklch(rgb);
assert!((ol - cl).abs() < 1e-4 && (oc - cc).abs() < 1e-4 && (oh - ch).abs() < 0.05, "{ol} {oc} {oh}");
}
}
#[test]
fn the_216_web_colors_round_trip() {
let steps = [0u8, 0x33, 0x66, 0x99, 0xcc, 0xff];
for r in steps {
for g in steps {
for b in steps {
let rgb = [r, g, b].map(|v| f32::from(v) / 255.0);
let [l, c, h] = to_oklch(rgb);
assert_eq!(eight(from_oklch(l, c, h).0), [r, g, b], "{l} {c} {h}");
}
}
}
}
#[test]
fn grays_have_no_chroma_and_hue_zero() {
for v in [0.0, 0.5, 1.0] {
let [_, c, h] = to_oklch([v, v, v]);
assert!(c <= POWERLESS_CHROMA && h == 0.0, "{c} {h}");
}
}
/// A chroma past the gamut gives a color inside it with the same lightness and hue, and says so.
#[test]
fn a_chroma_past_the_gamut_is_lowered_keeping_lightness_and_hue() {
let (l, h) = (0.7, 150.0);
let max = max_chroma(l, h);
assert!(max > 0.05 && max < CHROMA_FULL, "{max}");
assert!(in_srgb(oklch_to_srgb(l, max, h)) && !in_srgb(oklch_to_srgb(l, max + 1e-3, h)));
let (rgb, lowered) = from_oklch(l, CHROMA_FULL, h);
assert!(lowered);
let [ol, oc, oh] = to_oklch(rgb);
assert!((ol - l).abs() < 2e-3 && (oh - h).abs() < 1.0 && (oc - max).abs() < 2e-3, "{ol} {oc} {oh}");
assert!(!from_oklch(l, max * 0.5, h).1);
}
/// At the lightness and hue of blue the ray leaves sRGB and comes back at blue itself, so the
/// largest chroma is blue's, and a chroma past it gives blue.
#[test]
fn the_largest_chroma_at_blues_hue_is_blues() {
let [l, c, h] = to_oklch([0.0, 0.0, 1.0]);
let max = max_chroma(l, h);
assert!((max - c).abs() < 1e-4 && in_srgb(oklch_to_srgb(l, max, h)), "{max} {c}");
let (rgb, lowered) = from_oklch(l, CHROMA_FULL, h);
assert_eq!((eight(rgb), lowered), ([0, 0, 255], true));
// A chroma between the two stretches takes the end of the first one, inside sRGB.
let (rgb, lowered) = from_oklch(l, 0.29, h);
let [_, gc, _] = to_oklch(rgb);
assert!(lowered && gc < 0.27 && in_srgb(oklch_to_srgb(l, gc, h)), "{gc}");
// A hue just past blue's: a narrow second stretch ends just below the line from black to blue.
let (l, h) = (0.44, 264.06);
let max = max_chroma(l, h);
assert!(max > 0.304 && max < 0.305 && in_srgb(oklch_to_srgb(l, max, h)), "{max}");
let [_, got, _] = to_oklch(from_oklch(l, 0.35, h).0);
assert!(got > 0.303, "{got}");
// A darker blue on the line from black to blue.
let [l, c, h] = to_oklch([0.0, 0.0, 0.25]);
assert!((max_chroma(l, h) - c).abs() < 1e-4, "{} {c}", max_chroma(l, h));
}
/// Just below blue's lightness the line from black to blue passes a chroma of 0.3125, where a
/// search from 0 to 0.5 lands first. A chroma asked for below that line still gives a color
/// inside sRGB with the lightness and hue asked for.
#[test]
fn a_chroma_below_the_line_from_black_to_blue_stays_inside_srgb() {
let [bl, bc, h] = to_oklch([0.0, 0.0, 1.0]);
let l = bl * 0.3125 / bc;
let (rgb, lowered) = from_oklch(l, 0.29, h);
let [gl, gc, gh] = to_oklch(rgb);
assert!(lowered && gc < 0.29 && in_srgb(oklch_to_srgb(l, gc, h)), "{gc}");
assert!((gl - l).abs() < 2e-3 && (gh - h).abs() < 1.0, "{gl} {gh}");
}
/// sRGB channels below 0 go through the transfer curve with its sign turned, as CSS Color 4's
/// extended sRGB does, in both directions.
#[test]
fn negative_channels_use_the_signed_transfer_curve() {
let linear = -((0.5_f64 + 0.055) / 1.055).powf(2.4);
let [l, c, _] = to_oklch([-0.5; 3]);
assert!((l - linear.cbrt()).abs() < 1e-4 && c <= POWERLESS_CHROMA, "{l} {c}");
for v in oklch_to_srgb(linear.cbrt(), 0.0, 0.0) {
assert!((v + 0.5).abs() < 1e-4, "{v}");
}
// Small values near 0 keep the straight part of the curve.
let [l, _, _] = to_oklch([-0.01; 3]);
assert!((l - (-0.01_f64 / 12.92).cbrt()).abs() < 1e-4, "{l}");
}
/// The largest chroma fits and is at least the largest one a scan in steps of 0.0005 finds, at
/// every hue and at lightnesses near black too, where the ray can come back into sRGB away from
/// any primary color's hue (L 0.02 and H 242° fit up to about 0.022 after leaving near 0.012).
#[test]
fn the_largest_chroma_is_never_below_a_scan_of_the_ray() {
let scan = |l: f64, h: f64| (0..=1000).map(|i| f64::from(i) * 0.0005).filter(|c| in_srgb(oklch_to_srgb(l, *c, h))).fold(0.0, f64::max);
assert!(max_chroma(0.02, 242.0) > 0.02, "{}", max_chroma(0.02, 242.0));
for l in [0.005, 0.02, 0.05, 0.1, 0.3, 0.44, 0.6, 0.8, 0.95, 0.99] {
for h in (0..72).map(|i| f64::from(i) * 5.0 + 2.0) {
let max = max_chroma(l, h);
assert!(in_srgb(oklch_to_srgb(l, max, h)) && max >= scan(l, h), "L {l} H {h}: {max} < {}", scan(l, h));
}
}
}
#[test]
fn black_white_and_bad_numbers_hold_no_chroma() {
assert_eq!(max_chroma(0.0, 30.0), 0.0);
assert_eq!(max_chroma(1.0, 30.0), 0.0);
assert_eq!(max_chroma(f64::NAN, 30.0), 0.0);
assert_eq!(max_chroma(0.5, f64::INFINITY), 0.0);
assert_eq!(eight(from_oklch(f64::NAN, f64::NAN, f64::NAN).0), [0, 0, 0]);
assert_eq!(eight(from_oklch(2.0, -1.0, 0.0).0), [255, 255, 255]);
}
}
+4 -2
View File
@@ -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.
+25 -5
View File
@@ -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<f64>,
}
#[derive(Deserialize)]
@@ -75,11 +79,17 @@ struct CustomArrowheadData {
name: String,
#[serde(default)]
path: PathData,
#[serde(default)]
stop: Option<f64>,
}
impl From<CustomArrowheadData> 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))
}
}
+11 -2
View File
@@ -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");
}
+48
View File
@@ -1156,6 +1156,17 @@ impl Lerp {
(NodeKind::PlacedDocument(o), NodeKind::PlacedDocument(x), NodeKind::PlacedDocument(y)) => o.xf = lerp_affine(x.xf, y.xf, t),
_ => {}
}
// Between distorted images, each step's corners lie between the keys' corners. A
// step whose corners would fold keeps the nearer key's.
if (a.is_distorted_image() || b.is_distorted_image())
&& let (Some(qa), Some(qb)) = (a.image_corners(), b.image_corners())
{
let near = if t < 0.5 { qa } else { qb };
if n.set_image_corners([0, 1, 2, 3].map(|i| qa[i].lerp(qb[i], t))).is_err() {
// The nearer key's corners passed the same check when it was distorted.
let _ = n.set_image_corners(near);
}
}
n.extras_mut().mask = None;
n
}
@@ -2297,6 +2308,43 @@ mod tests {
assert_eq!(m.subpaths[0].anchors[0].p, Point::new(55.0, 0.0));
}
/// A step between two distorted images has its corners between the keys' corners.
#[test]
fn steps_between_distorted_images_have_corners_between_theirs() {
let image = |q: [(f64, f64); 4]| {
let im = crate::ImageObject {
key: "k".into(),
width: 10,
height: 10,
xf: Affine::IDENTITY,
link: None,
placement: Default::default(),
pixels: None,
};
let mut n = Node::new(NodeId(1), NodeKind::Image(Box::new(im)));
n.set_image_corners(q.map(|(x, y)| Point::new(x, y))).unwrap();
n
};
let a = image([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
let b = image([(200.0, 0.0), (300.0, 0.0), (280.0, 100.0), (220.0, 100.0)]);
let mid = Lerp::new(&a, &b, (None, None)).at(0.5);
let want = [(120.0, 0.0), (180.0, 0.0), (190.0, 100.0), (110.0, 100.0)];
let got = mid.image_corners().unwrap();
for (g, (x, y)) in got.iter().zip(want) {
assert!(g.distance(Point::new(x, y)) < 1e-9, "{got:?}");
}
// Toward a key flipped left to right, the middle step's corners would meet: each step
// there keeps the nearer key's corners, whether that key is distorted or not.
let flipped = image([(60.0, 0.0), (40.0, 0.0), (0.0, 100.0), (100.0, 100.0)]);
let mirror = image([(100.0, 0.0), (0.0, 0.0), (0.0, 100.0), (100.0, 100.0)]);
assert!(!mirror.is_distorted_image());
for (b, t) in [(&flipped, 0.5), (&mirror, 0.5), (&mirror, 0.45)] {
let got = Lerp::new(&a, b, (None, None)).at(t).image_corners().unwrap();
let near = (if t < 0.5 { &a } else { b }).image_corners().unwrap();
assert!(got.iter().zip(near).all(|(g, w)| g.distance(w) < 1e-9), "{t}: {got:?} against {near:?}");
}
}
fn key(x: f64) -> Arc<Node> {
Arc::new(Node::path(NodeId(1), vectorcraft_geom::shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::default()))
}
+65 -1
View File
@@ -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<Option<Arrowhead>, 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<Arrowhead>;
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<E: Error>(self) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_unit<E: Error>(self) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
deserializer.deserialize_str(self)
}
fn visit_str<E: Error>(self, name: &str) -> Result<Self::Value, E> {
// No built-in name is this long, so a longer one is refused without parsing it.
let parsed: Result<Arrowhead, serde::de::value::Error> =
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<crate::Arrowhead>,
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<Self, String> {
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<crate::Arrowhead> {
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());
}
+62
View File
@@ -500,11 +500,73 @@ impl Document {
self.patterns.iter_mut().find(|p| p.name == name)
}
/// The [`Self::unknown`] key that holds each symbol set's Symbol Set Density, `{set id: density}`.
/// [`Self::reid`] gives a copy of a set in this document the density recorded for its source, and
/// [`Self::carry_set_densities`] gives a pasted set the density recorded for it at Copy.
pub const SYMBOL_SET_DENSITY_KEY: &'static str = "symbolSetDensity";
/// The Symbol Set Densities recorded for `nodes` and their descendants, by id.
pub fn set_densities_of(&self, nodes: &[Node]) -> std::collections::BTreeMap<NodeId, serde_json::Value> {
let Some(serde_json::Value::Object(record)) = self.unknown.get(Self::SYMBOL_SET_DENSITY_KEY) else { return Default::default() };
let mut out = std::collections::BTreeMap::new();
let mut stack: Vec<&Node> = nodes.iter().collect();
while let Some(n) = stack.pop() {
if let Some(v) = record.get(&n.id.0.to_string()) {
out.insert(n.id, v.clone());
}
stack.extend(n.children().into_iter().flatten().map(|c| &**c));
}
out
}
/// Record for `copy`, a [`Self::reid`] copy of `source`, and its descendants the Symbol Set
/// Densities that `densities` holds for `source` and its descendants, and none for those it
/// holds none for (whatever [`Self::reid`] recorded).
pub fn carry_set_densities(&mut self, source: &Node, copy: &Node, densities: &std::collections::BTreeMap<NodeId, serde_json::Value>) {
if densities.is_empty() && !self.unknown.contains_key(Self::SYMBOL_SET_DENSITY_KEY) {
return;
}
let mut pairs = vec![(source, copy)];
while let Some((s, c)) = pairs.pop() {
match densities.get(&s.id) {
Some(v) => {
if let serde_json::Value::Object(m) =
self.unknown.entry(Self::SYMBOL_SET_DENSITY_KEY).or_insert_with(|| serde_json::Value::Object(Default::default()))
{
m.insert(c.id.0.to_string(), v.clone());
}
}
None => {
if let Some(serde_json::Value::Object(m)) = self.unknown.get_mut(Self::SYMBOL_SET_DENSITY_KEY) {
m.remove(&c.id.0.to_string());
}
}
}
if let (Some(sc), Some(cc)) = (s.children(), c.children()) {
pairs.extend(sc.iter().zip(cc.iter()).map(|(a, b)| (&**a, &**b)));
}
}
}
/// Deep-clone `node` with fresh ids for it and all descendants, its images' own pixels taken
/// in ([`Self::adopt_pixels`]).
pub fn reid(&mut self, node: &Node) -> Node {
let mut n = node.clone();
n.id = self.alloc_id();
// A copy of a symbol set keeps the Symbol Set Density recorded for its source, when the source
// is this document's node with that id; a node from another document may share the id of an
// unrelated set here.
let density = self
.unknown
.get(Self::SYMBOL_SET_DENSITY_KEY)
.and_then(|m| m.get(node.id.0.to_string()))
.filter(|_| self.node(node.id) == Some(node))
.cloned();
if let Some(v) = density
&& let Some(serde_json::Value::Object(m)) = self.unknown.get_mut(Self::SYMBOL_SET_DENSITY_KEY)
{
m.insert(n.id.0.to_string(), v);
}
if let NodeKind::Image(im) = &mut n.kind {
self.adopt_image_pixels(im);
}
+8 -5
View File
@@ -1503,14 +1503,17 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio
// An image is hit within its frame (on the frame's edge only with Selection by Path Only,
// #3291, and in outline mode where the frame is all that is drawn, #6437), and where its
// own fills and strokes paint ([`image_paint`]) except in outline mode.
NodeKind::Image(im) => {
NodeKind::Image(_) => {
// The frame joins the image's corners ([`Node::image_frame`]); a plain image is picked
// inside by its bounds, without building it.
if opt.path_only || (opt.outline && !symbols.document().setup.outline_images) {
use vectorcraft_geom::kurbo::Shape;
let mut frame = Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1);
frame.apply_affine(im.xf);
if stroke_contains(&frame, 0.0, opt.tol, p) {
if n.image_frame().is_some_and(|frame| stroke_contains(&frame, 0.0, opt.tol, p)) {
return Some(HitKind::Outline);
}
} else if let Some(frame) = n.is_distorted_image().then(|| n.image_frame()).flatten() {
if fill_contains(&frame, FillRule::NonZero, p) || stroke_contains(&frame, 0.0, opt.tol, p) {
return Some(HitKind::Bounds);
}
} else if n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) {
return Some(HitKind::Bounds);
}
+599
View File
@@ -0,0 +1,599 @@
//! Perspective Distort and Free Distort on an image: its pixel rectangle's corners placed anywhere
//! on the page, as long as they make a strictly convex quadrilateral.
//!
//! An image whose corners make a parallelogram is placed by its transform alone
//! ([`crate::ImageObject::xf`]). Other corners are kept in the image's extras
//! ([`crate::NodeExtras::image_quad`]), and the image is then drawn through the projective map
//! that takes its pixel rectangle to them. The renderer, the exporters and printing draw it as a
//! raster mesh warp ([`crate::live::mesh_warp_image`]) made from that map ([`distorted_art`]): no
//! warped copy of the pixels is kept. The quad stays with the image's transform: moving, scaling,
//! rotating or shearing the image maps its corners too ([`crate::Node::transform`]).
//!
//! The convexity rule, the tolerance of the mesh and its cell limit are VectorCraft's own.
use std::sync::Arc;
use vectorcraft_geom::kurbo::BezPath;
use vectorcraft_geom::{Affine, Homography, PathData, Point, Rect, SubPath};
use crate::{Appearance, ImageObject, Node, NodeKind};
/// Most cells along each side of the mesh an image is drawn with ([`cells`]).
pub const MAX_CELLS: usize = 64;
/// The cells along each side an image with fewer pixels than this may still take ([`cells`]).
pub const MIN_CELL_CAP: usize = 8;
/// How far (in points) the mesh an image is drawn with in files and print may stray from the exact
/// projective map ([`Density::PAGE`]).
pub const TOLERANCE: f64 = 0.05;
/// How finely [`distorted_art_at`] cuts a distorted image ([`cells`]), and how far each piece
/// reaches into its neighbors. A pixel inside the image draws opaque only when one piece covers
/// it whole, so pieces much smaller than a pixel would let the page show through.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Density {
/// How far (in points) the mesh may stray from the exact projective map.
pub tolerance: f64,
/// The shortest a cell may be along the longest side of the corners, in points.
pub min_cell: f64,
/// How far (in points) each piece reaches past its triangle.
pub overlap: f64,
}
impl Density {
/// For files and print, whose viewing size is not known: within [`TOLERANCE`], cells of at
/// least 2 pt, and pieces that reach half a point past their triangles.
pub const PAGE: Density = Density { tolerance: TOLERANCE, min_cell: 2.0, overlap: 0.5 };
/// For drawing at `scale` device pixels a point: within a quarter of a pixel, cells of at least
/// 4 pixels, and pieces that reach 2 pixels past their triangles.
pub fn at_scale(scale: f64) -> Density {
let s = if scale.is_finite() && scale > 1e-6 { scale } else { 1.0 };
Density { tolerance: 0.25 / s, min_cell: 4.0 / s, overlap: 2.0 / s }
}
/// [`Density::PAGE`] for art that is drawn `scale` times its size (a symbol's art in an
/// instance that scales it): the tolerance, the cell size and the overlap measured on the page.
pub fn page_at(scale: f64) -> Density {
let s = if scale.is_finite() && scale > 1e-6 { scale } else { 1.0 };
let p = Density::PAGE;
Density { tolerance: p.tolerance / s, min_cell: p.min_cell / s, overlap: p.overlap / s }
}
}
/// How much `a` stretches its most stretched direction: the larger singular value of its linear
/// part.
pub fn max_stretch(a: Affine) -> f64 {
let [m0, m1, m2, m3, _, _] = a.as_coeffs();
let sum = m0 * m0 + m1 * m1 + m2 * m2 + m3 * m3;
let det = m0 * m3 - m1 * m2;
((sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt()
}
/// Why corners cannot be an image's.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum QuadError {
/// A corner is not a finite point.
NotFinite,
/// The corners fold over, meet, or lie on one line: the quadrilateral is not strictly convex.
NotConvex,
/// The corners are convex but so close to a line that the perspective map through them cannot
/// place every corner.
TooNarrow,
}
impl std::fmt::Display for QuadError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::NotFinite => "the corners of a distorted image must be finite points",
Self::NotConvex => "the corners of a distorted image must make a convex shape: an image cannot fold over itself or collapse to a line",
Self::TooNarrow => "the corners of a distorted image are too close together for a perspective map",
})
}
}
/// `im`'s pixel rectangle: (0, 0) to its width and height.
fn pixel_rect(im: &ImageObject) -> Rect {
Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height))
}
/// The corners of `r` in the order a quad keeps them: top left, top right, bottom right, bottom
/// left.
fn rect_corners(r: Rect) -> [Point; 4] {
[Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)]
}
/// Whether the corners `q` (in order around the shape) are finite and make a strictly convex
/// quadrilateral, turning either way round. Each turn must be larger than 1e-9 times the product
/// of the two sides it joins, a test that gives the same answer at any scale.
pub fn check(q: &[Point; 4]) -> Result<(), QuadError> {
if q.iter().any(|p| !p.is_finite()) {
return Err(QuadError::NotFinite);
}
let mut sign = 0.0;
for i in 0..4 {
let (a, b, c) = (q[i], q[(i + 1) % 4], q[(i + 2) % 4]);
let (u, v) = (b - a, c - b);
let cross = u.cross(v);
let scale = u.hypot() * v.hypot();
if !cross.is_finite() || !scale.is_finite() || cross.abs() <= 1e-9 * scale || scale == 0.0 {
return Err(QuadError::NotConvex);
}
if sign == 0.0 {
sign = cross.signum();
} else if cross.signum() != sign {
return Err(QuadError::NotConvex);
}
}
// Four turns the same way round can still wind twice (a star); a convex quadrilateral's
// diagonals cross.
let crosses = |a: Point, b: Point, c: Point, d: Point| (b - a).cross(c - a).signum() != (b - a).cross(d - a).signum();
if !crosses(q[0], q[2], q[1], q[3]) || !crosses(q[1], q[3], q[0], q[2]) {
return Err(QuadError::NotConvex);
}
Ok(())
}
/// Whether `q` can be image `im`'s corners: [`check`], and either a parallelogram or corners the
/// perspective map from its pixels ([`pixel_map`]) places, each within a millionth of `q`'s
/// shortest side plus the rounding error of coordinates as far from the origin as `q`'s.
pub fn check_for(im: &ImageObject, q: &[Point; 4]) -> Result<(), QuadError> {
check(q)?;
if parallelogram(im, q).is_some() {
return Ok(());
}
let tol = placement_tolerance(q);
let map = pixel_map(im, q);
let placed = rect_corners(pixel_rect(im)).iter().zip(q).all(|(c, want)| map.apply(*c).is_some_and(|p| p.distance(*want) <= tol));
if placed { Ok(()) } else { Err(QuadError::TooNarrow) }
}
/// How far a map may place a corner from `q`'s: a millionth of `q`'s shortest side plus the
/// rounding error of coordinates as far from the origin as `q`'s.
fn placement_tolerance(q: &[Point; 4]) -> f64 {
let side = (0..4).map(|i| q[i].distance(q[(i + 1) % 4])).fold(f64::INFINITY, f64::min);
let far = q.iter().map(|p| p.x.abs().max(p.y.abs())).fold(0.0, f64::max);
side * 1e-6 + far * 1e-12
}
/// The affine map from `im`'s pixel space that places its corners at `q`, when `q` is a
/// parallelogram (within 1e-9 of the quad's size): the map puts the fourth corner within
/// [`placement_tolerance`] of `q`'s. `None` otherwise.
fn parallelogram(im: &ImageObject, q: &[Point; 4]) -> Option<Affine> {
let size = q.iter().fold(0.0_f64, |m, p| m.max((*p - q[0]).hypot()));
// The affine map through the other three corners misses the bottom right one by this much.
let gap = (q[0].to_vec2() + q[2].to_vec2() - q[1].to_vec2() - q[3].to_vec2()).hypot();
if gap > 1e-9 * size || gap > placement_tolerance(q) {
return None;
}
let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
let (x, y) = ((q[1] - q[0]) / w, (q[3] - q[0]) / h);
let a = Affine::new([x.x, x.y, y.x, y.y, q[0].x, q[0].y]);
a.is_finite().then_some(a)
}
/// The homography taking the unit square's corners (0,0), (1,0), (1,1), (0,1) to `q`.
fn square_to(q: &[Point; 4]) -> Homography {
let [p0, p1, p2, p3] = *q;
let (sx, sy) = (p0.x - p1.x + p2.x - p3.x, p0.y - p1.y + p2.y - p3.y);
let (dx1, dx2, dy1, dy2) = (p1.x - p2.x, p3.x - p2.x, p1.y - p2.y, p3.y - p2.y);
let den = dx1 * dy2 - dx2 * dy1;
let (g, h) = if den.abs() < 1e-300 { (0.0, 0.0) } else { ((sx * dy2 - dx2 * sy) / den, (dx1 * sy - sx * dy1) / den) };
Homography([[p1.x - p0.x + g * p1.x, p3.x - p0.x + h * p3.x, p0.x], [p1.y - p0.y + g * p1.y, p3.y - p0.y + h * p3.y, p0.y], [g, h, 1.0]])
}
impl Node {
/// This image's distortion: where its pixel rectangle's corners stand (top left, top right,
/// bottom right, bottom left) when they do not make a parallelogram. `None` for an image placed
/// by its transform alone, for anything that is not an image, and for corners a file holds
/// that [`check_for`] refuses (the image is then placed by its transform).
pub fn image_quad(&self) -> Option<[Point; 4]> {
let NodeKind::Image(im) = &self.kind else { return None };
let q = **self.extras().image_quad.as_ref()?;
check_for(im, &q).is_ok().then_some(q)
}
/// Whether this is an image with a distortion ([`Self::image_quad`]).
pub fn is_distorted_image(&self) -> bool {
self.image_quad().is_some()
}
/// Where this image's pixel rectangle's corners stand: its distortion, or its transform's
/// corners. `None` for anything that is not an image.
pub fn image_corners(&self) -> Option<[Point; 4]> {
let NodeKind::Image(im) = &self.kind else { return None };
Some(self.image_quad().unwrap_or_else(|| rect_corners(pixel_rect(im)).map(|p| im.xf * p)))
}
/// Place this image's corners at `q` (top left, top right, bottom right, bottom left): by its
/// transform when they make a parallelogram (and the distortion is cleared), else as its
/// distortion. An error, and nothing changes, when `q` fails [`check_for`] or this is not an
/// image.
pub fn set_image_corners(&mut self, q: [Point; 4]) -> Result<(), QuadError> {
let NodeKind::Image(im) = &mut self.kind else { return Err(QuadError::NotConvex) };
check_for(im, &q)?;
match parallelogram(im, &q) {
Some(xf) => {
im.xf = xf;
if self.extras().image_quad.is_some() {
self.extras_mut().image_quad = None;
}
}
None => self.extras_mut().image_quad = Some(Box::new(q)),
}
Ok(())
}
/// The outline of this image's frame on the page: its corners joined by straight lines.
/// `None` for anything that is not an image.
pub fn image_frame(&self) -> Option<BezPath> {
let q = self.image_corners()?;
let mut bp = BezPath::new();
bp.move_to(q[0]);
for p in &q[1..] {
bp.line_to(*p);
}
bp.close_path();
Some(bp)
}
/// The map from this image's pixel space to the page: projective for a distorted image, its
/// transform otherwise. `None` for anything that is not an image.
pub fn image_map(&self) -> Option<Homography> {
let NodeKind::Image(im) = &self.kind else { return None };
Some(match self.image_quad() {
Some(q) => pixel_map(im, &q),
None => Homography::from_affine(im.xf),
})
}
}
/// The projective map from `im`'s pixel space to the page that puts its corners at `q`.
fn pixel_map(im: &ImageObject, q: &[Point; 4]) -> Homography {
let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
square_to(q).then_after(&Homography::from_affine(Affine::scale_non_uniform(1.0 / w, 1.0 / h)))
}
/// How many cells along each side the mesh of a distorted image takes: the fewest (a power of two
/// up to [`MAX_CELLS`]) for which the mesh's triangles, each mapped by the affine map through its
/// corners, stay within `density`'s tolerance of `map` at the middle of every cell and every cell
/// side. An image takes no more cells than it has pixels along its longer side, or
/// [`MIN_CELL_CAP`] when that is more, and no more than leave each cell `density.min_cell` along
/// the longest side of its corners. A perspective that needs more cells than these limits allow is
/// drawn with the cells they allow.
pub fn cells(map: &Homography, im: &ImageObject, density: Density) -> usize {
let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
let corners = [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)].map(|p| map.apply(p));
let longest =
corners.iter().zip(corners.iter().cycle().skip(1)).filter_map(|(a, b)| Some(a.as_ref()?.distance(*b.as_ref()?))).fold(0.0, f64::max);
let by_size = longest / density.min_cell;
let by_size = if by_size.is_finite() { (by_size as usize).max(1) } else { MAX_CELLS };
let most = MAX_CELLS.min((im.width.max(im.height) as usize).max(MIN_CELL_CAP)).min(by_size);
let at = |x: f64, y: f64| map.apply(Point::new(x, y));
let mut k = 1;
while k < most {
let fits = (0..k * k).all(|c| {
let (i, j) = ((c % k) as f64, (c / k) as f64);
let (x0, y0, x1, y1) = (w * i / k as f64, h * j / k as f64, w * (i + 1.0) / k as f64, h * (j + 1.0) / k as f64);
let (Some(a), Some(b), Some(cc), Some(d)) = (at(x0, y0), at(x1, y0), at(x1, y1), at(x0, y1)) else { return false };
let near = |exact: Option<Point>, m: Point| exact.is_some_and(|e| e.distance(m) <= density.tolerance);
near(at((x0 + x1) / 2.0, (y0 + y1) / 2.0), a.midpoint(cc))
&& near(at((x0 + x1) / 2.0, y0), a.midpoint(b))
&& near(at(x1, (y0 + y1) / 2.0), b.midpoint(cc))
&& near(at((x0 + x1) / 2.0, y1), d.midpoint(cc))
&& near(at(x0, (y0 + y1) / 2.0), a.midpoint(d))
});
if fits {
break;
}
k *= 2;
}
k.min(most)
}
/// For a format that cannot clip an image into the pieces of [`distorted_art`]: the affine
/// placement nearest distorted image `n`'s projective map, the one that matches it at the middle
/// of its pixels. `None` when `n` is not a distorted image.
pub fn nearest_affine(n: &Node) -> Option<Affine> {
let NodeKind::Image(im) = &n.kind else { return None };
let q = n.image_quad()?;
pixel_map(im, &q).affine_at(pixel_rect(im).center())
}
/// Distorted image `n` as the art that draws it in files and print: [`distorted_art_at`] with
/// [`Density::PAGE`].
pub fn distorted_art(n: &Node) -> Option<Node> {
distorted_art_at(n, Density::PAGE)
}
/// Distorted image `n` as the art that draws it: a clip group, clipped by its corners, around the
/// raster mesh warp ([`crate::live::mesh_warp_image`]) of its pixels through its projective map,
/// with [`cells`] cells along each side for `density` and each piece reaching `density.overlap`
/// past its triangle. The art has `n`'s id but not its name and transparency (which the caller
/// keeps on the object around the art). `None` when `n` is not a distorted image.
pub fn distorted_art_at(n: &Node, density: Density) -> Option<Node> {
let NodeKind::Image(im) = &n.kind else { return None };
let q = n.image_quad()?;
let map = pixel_map(im, &q);
let k = cells(&map, im, density);
let mut plain = n.clone();
// Whether the image shows is the image's to decide: a hidden source image that a view draws
// anyway (Image Trace's Source Image) draws its art.
plain.visible = true;
// The image's own fills and strokes paint by the image's rules, not on the mesh's group.
plain.appearance = Default::default();
plain.name = None;
plain.opacity = 1.0;
plain.blend = Default::default();
plain.isolate = false;
plain.knockout = Default::default();
plain.knockout_shape = false;
if let Some(e) = plain.extras_if_any() {
e.mask = None;
}
let mut art = crate::live::mesh_warp_image_with(&plain, im, &|p| p, k, n.extras().pixelated, false, Some(density.overlap));
// The pieces along the image's edges reach past its corners too: the corners clip them.
let mut edge = Node::path(n.id, PathData::single(SubPath::polyline(&q, true)), Appearance::default());
if let NodeKind::Path { clipping, .. } = &mut edge.kind {
*clipping = true;
}
let pieces = std::mem::replace(&mut art.kind, NodeKind::Group { children: vec![], clip: true });
let mut mesh = art.clone();
mesh.kind = pieces;
art.knockout = Default::default();
art.kind = NodeKind::Group { children: vec![Arc::new(edge), Arc::new(mesh)], clip: true };
Some(art)
}
/// The pieces of [`distorted_art_at`]'s art: the children of its mesh group.
pub fn distorted_pieces(art: &Node) -> &[Arc<Node>] {
art.children().and_then(|c| c.get(1)).and_then(|m| m.children()).map_or(&[], Vec::as_slice)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::NodeId;
fn image(w: u32, h: u32) -> Node {
let im = ImageObject { key: "k".into(), width: w, height: h, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None };
Node::new(NodeId(1), NodeKind::Image(Box::new(im)))
}
fn pts(v: [(f64, f64); 4]) -> [Point; 4] {
v.map(|(x, y)| Point::new(x, y))
}
#[test]
fn a_convex_quad_either_way_round_passes_and_a_fold_or_line_does_not() {
assert_eq!(check(&pts([(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)])), Ok(()));
assert_eq!(check(&pts([(0.0, 0.0), (0.0, 10.0), (10.0, 10.0), (10.0, 0.0)])), Ok(()));
// Two corners swapped: the sides cross.
assert_eq!(check(&pts([(0.0, 0.0), (10.0, 0.0), (0.0, 10.0), (10.0, 10.0)])), Err(QuadError::NotConvex));
// A dent.
assert_eq!(check(&pts([(0.0, 0.0), (10.0, 0.0), (2.0, 2.0), (0.0, 10.0)])), Err(QuadError::NotConvex));
// Three on a line, and two corners at one point.
assert_eq!(check(&pts([(0.0, 0.0), (5.0, 0.0), (10.0, 0.0), (0.0, 10.0)])), Err(QuadError::NotConvex));
assert_eq!(check(&pts([(0.0, 0.0), (0.0, 0.0), (10.0, 10.0), (0.0, 10.0)])), Err(QuadError::NotConvex));
assert_eq!(check(&pts([(f64::NAN, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)])), Err(QuadError::NotFinite));
}
/// A convex quad with one edge so short that the perspective map through it cannot place the
/// other corners: refused when set, and a file's copy of it leaves the image undistorted.
#[test]
fn corners_the_perspective_map_cannot_place_are_refused() {
let q = pts([(50.0, 0.0), (50.000000005, 0.0), (100.0, 100.0), (0.0, 100.0)]);
assert_eq!(check(&q), Ok(()));
let mut n = image(100, 100);
assert_eq!(n.set_image_corners(q), Err(QuadError::TooNarrow));
assert!(n.extras().image_quad.is_none());
n.extras_mut().image_quad = Some(Box::new(q));
assert_eq!(n.image_quad(), None);
assert!(distorted_art(&n).is_none());
assert_eq!(n.image_corners(), Some(rect_corners(Rect::new(0.0, 0.0, 100.0, 100.0))));
}
#[test]
fn a_parallelogram_goes_into_the_transform_and_other_corners_into_the_quad() {
let mut n = image(100, 50);
n.set_image_corners(pts([(10.0, 0.0), (110.0, 10.0), (100.0, 60.0), (0.0, 50.0)])).unwrap();
assert_eq!(n.image_quad(), None);
let NodeKind::Image(im) = &n.kind else { panic!("an image") };
assert!((im.xf * Point::new(100.0, 50.0)).distance(Point::new(100.0, 60.0)) < 1e-9);
let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
n.set_image_corners(q).unwrap();
assert_eq!(n.image_quad(), Some(q));
assert_eq!(n.image_corners(), Some(q));
let map = n.image_map().unwrap();
for (c, want) in rect_corners(Rect::new(0.0, 0.0, 100.0, 50.0)).iter().zip(q) {
assert!(map.apply(*c).unwrap().distance(want) < 1e-9, "{c:?}");
}
// Back to a rectangle: the quad is cleared.
n.set_image_corners(pts([(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)])).unwrap();
assert!(n.extras().image_quad.is_none());
}
/// Corners whose gap from a parallelogram is tiny next to the quad's size but not next to its
/// shortest side stay a distortion: the affine map would put the bottom right corner twice as
/// low as asked.
#[test]
fn corners_the_affine_map_misses_stay_a_distortion() {
let mut n = image(100, 100);
let q = pts([(0.0, 0.0), (100000.0, 0.0), (100000.0, 0.00005), (0.0, 0.0001)]);
n.set_image_corners(q).unwrap();
assert_eq!(n.image_quad(), Some(q));
let map = n.image_map().unwrap();
for (c, want) in rect_corners(Rect::new(0.0, 0.0, 100.0, 100.0)).iter().zip(q) {
assert!(map.apply(*c).unwrap().distance(want) < 1e-9, "{c:?}");
}
}
/// A scale that squeezes valid corners past what a perspective map can place leaves the image
/// at the placement nearest them, scaled, not at the rectangle it had before.
#[test]
fn a_scale_past_the_perspective_limit_keeps_the_nearest_placement() {
let mut n = image(100, 100);
n.set_image_corners(pts([(0.0, 0.0), (100.0, 0.0), (200.0, 2e-7), (0.0, 2e-7)])).unwrap();
assert!(n.is_distorted_image());
n.transform(Affine::scale_non_uniform(1.0, 0.25), false);
assert!(n.extras().image_quad.is_none());
let b = n.geometric_bounds().unwrap();
assert!(b.height() < 1e-6 && (b.width() - 150.0).abs() < 60.0, "{b:?}");
}
/// A file's corners that the image cannot take are dropped as it is read, so a later scale
/// that would make them valid leaves the image placed by its transform; a list of three
/// points is dropped too, and the rest of the image is read.
#[test]
fn corners_a_file_holds_that_are_refused_or_not_four_are_dropped_as_it_is_read() {
let mut n = image(100, 100);
n.extras_mut().image_quad = Some(Box::new(pts([(0.0, 0.0), (100.0, 0.0), (200.0, 5e-8), (0.0, 5e-8)])));
assert_eq!(n.image_quad(), None);
let mut read: Node = serde_json::from_value(serde_json::to_value(&n).unwrap()).unwrap();
assert!(read.extras().image_quad.is_none());
read.transform(Affine::scale_non_uniform(1.0, 4.0), false);
assert!(!read.is_distorted_image());
assert_eq!(read.geometric_bounds(), Some(Rect::new(0.0, 0.0, 100.0, 400.0)));
let mut v = serde_json::to_value(&n).unwrap();
v["image_quad"] = serde_json::json!([[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]]);
let read: Node = serde_json::from_value(v).unwrap();
assert!(read.extras().image_quad.is_none());
assert!(matches!(read.kind, NodeKind::Image(_)));
// Past a fourth point the rest is skipped without being read as points.
for extra in [serde_json::json!([5.0, 5.0]), serde_json::json!("not a point")] {
let mut v = serde_json::to_value(&n).unwrap();
v["image_quad"] = serde_json::json!([[40.0, 0.0], [60.0, 0.0], [100.0, 100.0], [0.0, 100.0], extra, {"x": 1}]);
let read: Node = serde_json::from_value(v).unwrap();
assert!(read.extras().image_quad.is_none());
}
// Valid corners read back.
let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
n.set_image_corners(q).unwrap();
let read: Node = serde_json::from_value(serde_json::to_value(&n).unwrap()).unwrap();
assert_eq!(read.image_quad(), Some(q));
}
#[test]
fn refused_corners_change_nothing_and_a_bad_quad_in_a_file_is_ignored() {
let mut n = image(10, 10);
let before = n.clone();
assert!(n.set_image_corners(pts([(0.0, 0.0), (10.0, 0.0), (0.0, 10.0), (10.0, 10.0)])).is_err());
assert_eq!(n, before);
n.extras_mut().image_quad = Some(Box::new(pts([(0.0, 0.0), (10.0, 0.0), (0.0, 10.0), (10.0, 10.0)])));
assert_eq!(n.image_quad(), None);
assert_eq!(n.image_corners(), Some(pts([(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)])));
}
#[test]
fn the_mesh_is_as_fine_as_the_perspective_needs() {
let mut n = image(400, 400);
n.set_image_corners(pts([(10.0, 0.0), (400.0, 5.0), (390.0, 400.0), (0.0, 395.0)])).unwrap();
let NodeKind::Image(im) = n.kind.clone() else { panic!("an image") };
let gentle = cells(&n.image_map().unwrap(), &im, Density::PAGE);
n.set_image_corners(pts([(160.0, 0.0), (240.0, 0.0), (400.0, 400.0), (0.0, 400.0)])).unwrap();
let strong = cells(&n.image_map().unwrap(), &im, Density::PAGE);
assert!(gentle < strong && strong <= MAX_CELLS, "{gentle} {strong}");
// Three by two pixels drawn as large still bend, in up to MIN_CELL_CAP cells.
let mut tiny = image(3, 2);
tiny.set_image_corners(pts([(160.0, 0.0), (240.0, 0.0), (400.0, 400.0), (0.0, 400.0)])).unwrap();
let NodeKind::Image(tim) = &tiny.kind else { panic!("an image") };
assert_eq!(cells(&tiny.image_map().unwrap(), tim, Density::PAGE), MIN_CELL_CAP.min(strong));
// Drawn small, the same corners take only cells of at least 4 pixels: their longest side,
// about 431 pt, is about 17 pixels at 1/25 px a point, room for 4 cells.
let map = n.image_map().unwrap();
assert!(cells(&map, &im, Density::at_scale(1.0 / 25.0)) <= 4);
// Drawn large, a quarter of a pixel is finer than 0.05 pt, so no fewer cells than on the page.
assert!(cells(&map, &im, Density::at_scale(8.0)) >= strong);
// Each cell of the page's mesh is at least 2 pt along the longest side: about 32 pt takes
// 16 at most.
let mut small = image(400, 400);
small.set_image_corners(pts([(12.0, 0.0), (18.0, 0.0), (30.0, 30.0), (0.0, 30.0)])).unwrap();
assert!(cells(&small.image_map().unwrap(), &im, Density::PAGE) <= 16);
}
/// Each piece of the art reaches the density's overlap past its triangle, and the corners clip
/// the art, so nothing draws outside them.
#[test]
fn the_pieces_overlap_and_the_corners_clip_them() {
let mut n = image(100, 100);
let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
n.set_image_corners(q).unwrap();
let art = distorted_art_at(&n, Density { tolerance: 1.0, min_cell: 1.0, overlap: 3.0 }).unwrap();
let Some([edge, _]) = art.children().map(Vec::as_slice) else { panic!("an edge and a mesh") };
assert!(matches!(edge.kind, NodeKind::Path { clipping: true, .. }));
assert_eq!(edge.geometric_bounds(), Some(Rect::new(0.0, 0.0, 100.0, 100.0)));
let pieces = distorted_pieces(&art);
assert!(pieces.len() >= 2);
// The first piece's clip triangle reaches 3 pt past the image's top left corner.
let Some([clip, _]) = pieces[0].children().map(Vec::as_slice) else { panic!("a clip and an image") };
let b = clip.geometric_bounds().unwrap();
assert!(b.y0 < -2.0, "{b:?}");
}
#[test]
fn the_art_puts_the_pixel_corners_on_the_quad() {
let mut n = image(100, 100);
n.opacity = 0.5;
let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
n.set_image_corners(q).unwrap();
let art = distorted_art(&n).unwrap();
assert_eq!(art.opacity, 1.0);
let mut corners_seen = [false; 4];
art.walk(&mut |c| {
if let NodeKind::Image(im) = &c.kind {
for (i, (p, want)) in rect_corners(Rect::new(0.0, 0.0, 100.0, 100.0)).iter().zip(q).enumerate() {
if (im.xf * *p).distance(want) < 1e-9 {
corners_seen[i] = true;
}
}
}
});
assert_eq!(corners_seen, [true; 4]);
assert!(distorted_art(&image(4, 4)).is_none());
// A hidden image that a view draws anyway gives art that draws.
n.visible = false;
assert!(distorted_art(&n).unwrap().visible);
// The image's own fills and strokes stay off the mesh's group.
let stroke = vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK);
n.appearance = crate::Appearance::basic(vectorcraft_color::Paint::None, stroke, 1.0).into();
assert!(distorted_art(&n).unwrap().appearance.items.is_empty());
}
#[test]
fn deep_expansion_reaches_a_distorted_image_inside_a_group() {
let mut n = image(100, 100);
n.set_image_corners(pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)])).unwrap();
let inner = Node::new(NodeId(2), NodeKind::Group { children: vec![std::sync::Arc::new(n)], clip: false });
let outer = Node::new(NodeId(3), NodeKind::Group { children: vec![std::sync::Arc::new(inner)], clip: false });
let out = crate::live::expand_deep(&outer, None);
let mut distorted = 0;
let mut pieces = 0;
out.walk(&mut |c| {
distorted += usize::from(c.is_distorted_image());
pieces += usize::from(matches!(c.kind, NodeKind::Image(_)));
});
assert_eq!(distorted, 0);
assert!(pieces > 1, "{pieces}");
}
/// A distorted image with an effect of its own stays an image with its appearance when the
/// art around it is expanded, so the effect still applies where the art is drawn.
#[test]
fn deep_expansion_keeps_a_distorted_image_with_its_own_appearance() {
let mut n = image(100, 100);
n.set_image_corners(pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)])).unwrap();
let effect = crate::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 40}), visible: true };
n.appearance = crate::Appearance { effects: vec![effect], ..Default::default() }.into();
let inner = Node::new(NodeId(2), NodeKind::Group { children: vec![std::sync::Arc::new(n.clone())], clip: false });
let outer = Node::new(NodeId(3), NodeKind::Group { children: vec![std::sync::Arc::new(inner)], clip: false });
let out = crate::live::expand_deep(&outer, None);
let mut kept = vec![];
out.walk(&mut |c| {
if c.is_distorted_image() {
kept.push(c.appearance.clone());
}
});
assert_eq!(kept, vec![n.appearance]);
}
}
+1
View File
@@ -22,6 +22,7 @@ pub mod graph;
mod halftone_radii;
pub mod hit;
mod id_index;
pub mod image_quad;
pub use id_index::{path_lookups, tree_walks};
pub mod inks;
mod inline;
+2 -2
View File
@@ -57,11 +57,11 @@ pub use envelope::{
envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of,
envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid,
};
pub(crate) use expand::max_outset;
pub use expand::{
Hooks, MAX_GENERATED, Outliner, PatternTiles, affine_near, expand_deep, expand_deep_hooks, expand_live, expand_live_hooks, expand_live_with,
expanded_group, expanded_group_hooks, is_live, mesh_quad_nodes, mesh_warp_cost, mesh_warp_image, subtree_has_live,
expanded_group, expanded_group_hooks, is_drawn_live, is_live, mesh_quad_nodes, mesh_warp_cost, mesh_warp_image, subtree_has_live,
};
pub(crate) use expand::{max_outset, mesh_warp_image_with};
#[cfg(test)]
use mesh::grid_eval;
pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds};
+70 -12
View File
@@ -212,12 +212,26 @@ pub fn mesh_warp_cost(cells: usize) -> usize {
/// partly transparent image keeps its own alpha there. More cells than [`MAX_GENERATED`] objects
/// allow make an empty group.
pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, cells: usize, pixelated: bool, masked: bool) -> Node {
mesh_warp_image_with(n, im, f, cells, pixelated, masked, None)
}
/// [`mesh_warp_image`], each piece reaching `overlap` points past its edges when given.
pub(crate) fn mesh_warp_image_with(
n: &Node,
im: &ImageObject,
f: &dyn Fn(Point) -> Point,
cells: usize,
pixelated: bool,
masked: bool,
overlap: Option<f64>,
) -> Node {
let k = cells.max(1);
let mut g = n.clone();
g.kind = NodeKind::Group { children: vec![], clip: false };
g.knockout = crate::Knockout::On;
if let Some(e) = g.extras_if_any() {
e.colorize = None;
e.image_quad = None;
}
if mesh_warp_cost(k) > MAX_GENERATED {
return g;
@@ -228,24 +242,31 @@ pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, c
let color_mask = n.extras().color_mask.clone();
let (pw, ph) = (im.width as f64, im.height as f64);
let at = |i: usize, j: usize| Point::new(pw * i as f64 / k as f64, ph * j as f64 / k as f64);
// A distorted image's pixels reach the page through its projective map.
let to_page = n.image_map().filter(|_| n.is_distorted_image());
let place = |p: Point| to_page.and_then(|m| m.apply(p)).unwrap_or(im.xf * p);
let mut pieces = Vec::with_capacity(2 * k * k);
for j in 0..k {
for i in 0..k {
let s = [at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)];
let d = s.map(|p| f(im.xf * p));
let d = s.map(|p| f(place(p)));
for t in [[0, 1, 2], [0, 2, 3]] {
let (st, dt) = (t.map(|v| s[v]), t.map(|v| d[v]));
let Some(xf) = affine_between(st, dt) else { continue };
let c = Point::new((dt[0].x + dt[1].x + dt[2].x) / 3.0, (dt[0].y + dt[1].y + dt[2].y) / 3.0);
let grow = (dt[0].distance(dt[1]).max(dt[1].distance(dt[2])) * 0.02).min(0.5);
let tri: Vec<Point> = dt
.iter()
.map(|p| {
let v = *p - c;
let len = v.hypot();
if len > 1e-12 { *p + v * (grow / len) } else { *p }
})
.collect();
let tri: Vec<Point> = match overlap {
Some(g) => grown_triangle(dt, g),
None => {
let grow = (dt[0].distance(dt[1]).max(dt[1].distance(dt[2])) * 0.02).min(0.5);
dt.iter()
.map(|p| {
let v = *p - c;
let len = v.hypot();
if len > 1e-12 { *p + v * (grow / len) } else { *p }
})
.collect()
}
};
let shape = PathData::single(SubPath::polyline(&tri, true));
let mut image = Node::new(n.id, NodeKind::Image(Box::new(ImageObject { xf, ..im.clone() })));
image.extras_mut().pixelated = pixelated;
@@ -274,6 +295,23 @@ pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, c
g
}
/// Triangle `t` with each side moved `g` outward: `t` scaled about its incenter. A corner moves
/// at most 8 `g`, so a very thin triangle's sides move less than `g`.
fn grown_triangle(t: [Point; 3], g: f64) -> Vec<Point> {
let side = |i: usize| t[(i + 1) % 3].distance(t[(i + 2) % 3]);
let (a, b, c) = (side(0), side(1), side(2));
let perimeter = a + b + c;
let area = ((t[1] - t[0]).cross(t[2] - t[0]) / 2.0).abs();
if !(perimeter > 1e-12 && area > 0.0 && g.is_finite() && g > 0.0) {
return t.to_vec();
}
let center = Point::new((a * t[0].x + b * t[1].x + c * t[2].x) / perimeter, (a * t[0].y + b * t[1].y + c * t[2].y) / perimeter);
let r = 2.0 * area / perimeter;
let far = t.iter().map(|p| p.distance(center)).fold(0.0, f64::max);
let grow = (g / r).min(8.0 * g / far.max(1e-12));
t.iter().map(|p| center + (*p - center) * (1.0 + grow)).collect()
}
/// Distort Pattern Fills: path or compound path `n` with each visible pattern fill turned into the
/// tiles it paints in a clip group shaped like `n` (with the fill's opacity and blend mode), its
/// other fills and strokes on copies of it, in paint order, under `n`'s transparency. `None`
@@ -353,6 +391,13 @@ pub fn is_live(n: &Node) -> bool {
)
}
/// Is this drawn and written as evaluated art: a live object ([`is_live`]) or a distorted image
/// ([`Node::image_quad`]), whose art is [`crate::image_quad::distorted_art`]. Effects and
/// container paint treat a distorted image as an image, not as live art.
pub fn is_drawn_live(n: &Node) -> bool {
is_live(n) || n.is_distorted_image()
}
/// Mesh tessellation as flat-filled paths (no stroke): each patch cut `n`×`n`, its quads joined
/// where the colour hardly changes ([`GradientMesh::pieces`]).
pub fn mesh_quad_nodes(m: &GradientMesh, n: usize) -> Vec<Node> {
@@ -388,6 +433,7 @@ pub fn expand_live_hooks(n: &Node, hooks: Hooks) -> Vec<Node> {
NodeKind::Repeat(r) => r.expand(hooks.symbols),
NodeKind::PlacedDocument(p) => p.art(n),
NodeKind::Intertwine { children } => crate::intertwine::expand(children),
NodeKind::Image(_) => vec![crate::image_quad::distorted_art(n).unwrap_or_else(|| n.clone())],
_ => vec![n.clone()],
}
}
@@ -429,7 +475,7 @@ pub fn expand_deep(n: &Node, outline: Outliner) -> Node {
/// expands to nothing.
pub fn expand_deep_hooks(n: &Node, hooks: Hooks) -> Node {
let _generating = Generating::enter();
let mut out = if is_live(n) {
let mut out = if is_drawn_live(n) {
let g = expanded_group_hooks(n, hooks);
if !Generating::charge(g.count()) {
return Node::new(n.id, NodeKind::Group { children: vec![], clip: false });
@@ -440,7 +486,12 @@ pub fn expand_deep_hooks(n: &Node, hooks: Hooks) -> Node {
};
if let Some(ch) = out.children_mut() {
for c in ch.iter_mut() {
if subtree_has_live(c) {
// A distorted image with fills, strokes or effects of its own stays an image: whoever
// draws the art draws it with them, as it draws a distorted image anywhere else.
if c.is_distorted_image() && !(c.appearance.items.is_empty() && c.appearance.effects.is_empty()) {
continue;
}
if subtree_has_drawn_live(c) {
*c = Arc::new(expand_deep_hooks(c, hooks));
}
}
@@ -497,6 +548,13 @@ pub fn subtree_has_live(n: &Node) -> bool {
any
}
/// Does `n` or any descendant draw as evaluated art ([`is_drawn_live`])?
fn subtree_has_drawn_live(n: &Node) -> bool {
let mut any = false;
n.walk(&mut |c| any |= is_drawn_live(c));
any
}
/// Largest stroke outset in a subtree (for visual bounds of envelopes, blends and repeats, and the
/// reach of symbol art), type's character strokes included as type's own visual bounds measure them
/// ([`crate::TextObject::char_stroke_outset`]): in an envelope they paint at their own weight
+6 -2
View File
@@ -44,8 +44,12 @@ impl Node {
}
}
NodeKind::Image(im) => {
let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
out.push((frame.to_bezpath(), FillRule::NonZero));
// A distorted image's frame joins its corners.
let frame = match self.image_frame().filter(|_| self.is_distorted_image()) {
Some(bp) => bp,
None => shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf).to_bezpath(),
};
out.push((frame, FillRule::NonZero));
}
NodeKind::PlacedDocument(p) => {
let frame = shapes::rectangle(p.natural()).transformed(p.xf);
+6
View File
@@ -3,6 +3,7 @@ use super::kind::NodeKind;
use super::live_shape::LiveShape;
use super::opacity::OpacityMask;
use super::{Node, PathData};
use vectorcraft_geom::Point;
/// The parts of a [`Node`] that few objects have: kept out of line, so that the nodes without
/// them stay small ([`Node::extras`]).
@@ -87,6 +88,10 @@ pub struct NodeExtras {
/// are applied, one path or compound path per fill and stroke: as the clipping path of a clip group it paints
/// those pieces as the path paints its fills and strokes ([`Node::clip_paint`]).
pub clip_pieces: bool,
/// As an image after Perspective Distort or Free Distort, where its pixel rectangle's corners
/// (top left, top right, bottom right, bottom left in pixel space) stand on the page when they
/// do not make a parallelogram, which its transform alone could place ([`crate::image_quad`]).
pub image_quad: Option<Box<[Point; 4]>>,
}
/// No extras: what [`Node::extras`] gives for a node without any.
@@ -118,6 +123,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
color_mask: None,
warp_piece: false,
clip_pieces: false,
image_quad: None,
};
/// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal
+29 -7
View File
@@ -144,10 +144,36 @@ impl LiveShape {
/// from straight up (the Rotate field's sense). None for other shapes.
pub fn polygon_angle(&self) -> Option<f64> {
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<f64> {
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.
+26 -1
View File
@@ -386,6 +386,10 @@ impl Node {
.filter(|c| c.visible || !matches!(self.kind, NodeKind::Layer { .. }))
.fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric(symbols))),
NodeKind::Text(t) => self.projected(t.bounds()),
// A distorted image is bounded by its corners.
NodeKind::Image(_) if self.is_distorted_image() => {
self.image_corners().map(|q| q[1..].iter().fold(Rect::from_points(q[0], q[0]), |r, p| r.union_pt(*p)))
}
NodeKind::Image(im) => Some(im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, im.width as f64, im.height as f64))),
NodeKind::SymbolInstance { symbol, xf } => {
let art = symbols.and_then(|s| s.art(symbol)).map_or(SYMBOL_SQUARE, |a| a.geometric);
@@ -528,6 +532,9 @@ impl Node {
}
// The path the objects are attached to, before it is transformed.
let on_path_before = self.on_path_data().cloned();
// A distorted image's placement nearest its corners, before they are transformed (`None`
// within when its stored corners are refused, and `None` for anything else).
let image_before = self.extras().image_quad.is_some().then(|| crate::image_quad::nearest_affine(self));
if !self.is_layer() {
self.bbox_angle = crate::orient::transformed_angle(self.bbox_angle, a);
}
@@ -637,7 +644,8 @@ impl Node {
{
Arc::make_mut(&mut m.art).transform_scaled(a, sc);
}
// The area where an Intertwine member is drawn over the others moves with it.
// The area where an Intertwine member is drawn over the others moves with it, and so do a
// distorted image's corners.
if let Some(e) = self.extras_if_any() {
if let Some(area) = e.intertwine.as_mut() {
area.transform(a);
@@ -645,6 +653,23 @@ impl Node {
for area in &mut e.intertwine_tiers {
area.transform(a);
}
if let Some(q) = e.image_quad.as_mut() {
for p in q.iter_mut() {
*p = a * *p;
}
}
}
// Corners that a scale squeezes past what a perspective map can place (or that were
// refused already) leave the image placed by its transform: for valid corners, the
// placement that was nearest them, transformed, rather than the rectangle it had before
// it was distorted.
if let Some(before) = image_before
&& self.image_quad().is_none()
{
if let (Some(near), NodeKind::Image(im)) = (before, &mut self.kind) {
im.xf = a * near;
}
self.extras_mut().image_quad = None;
}
}
+14
View File
@@ -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 };
+48
View File
@@ -59,6 +59,7 @@ impl Serialize for Node {
e.color_mask.is_none(),
is_default(&e.warp_piece),
is_default(&e.clip_pieces),
e.image_quad.is_none(),
];
let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?;
let mut skip = skips.into_iter();
@@ -106,6 +107,7 @@ impl Serialize for Node {
field!("color_mask", &e.color_mask);
field!("warp_piece", &e.warp_piece);
field!("clip_pieces", &e.clip_pieces);
field!("image_quad", &e.image_quad);
st.end()
}
}
@@ -257,10 +259,55 @@ pub(super) struct NodeWire {
warp_piece: bool,
#[serde(default)]
clip_pieces: bool,
#[serde(default, deserialize_with = "image_corners")]
image_quad: Option<Box<[vectorcraft_geom::Point; 4]>>,
}
/// A distorted image's corners as a file holds them: a list of exactly four points, else none (the
/// image is then placed by its transform). At most five points of a longer list are kept while it
/// is read.
fn image_corners<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Box<[vectorcraft_geom::Point; 4]>>, D::Error> {
use vectorcraft_geom::Point;
struct Corners;
impl<'de> serde::de::Visitor<'de> for Corners {
type Value = Option<Box<[Point; 4]>>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a list of points")
}
fn visit_none<E: serde::de::Error>(self) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_some<D: serde::Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
d.deserialize_seq(Corners)
}
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
let mut points = Vec::with_capacity(4);
while points.len() < 4
&& let Some(p) = seq.next_element::<Point>()?
{
points.push(p);
}
// A fifth entry drops the field, so the rest is skipped without decoding it.
let mut extra = false;
while seq.next_element::<serde::de::IgnoredAny>()?.is_some() {
extra = true;
}
Ok(if extra { None } else { <[Point; 4]>::try_from(points).ok().map(Box::new) })
}
}
d.deserialize_option(Corners)
}
impl From<NodeWire> for Node {
fn from(w: NodeWire) -> Self {
// Corners an image cannot take are dropped, so a later transform cannot make them its own.
let image_quad = match &w.kind {
NodeKind::Image(im) => w.image_quad.filter(|q| crate::image_quad::check_for(im, q).is_ok()),
_ => None,
};
let extras = NodeExtras {
mask: w.mask,
trace: w.trace,
@@ -289,6 +336,7 @@ impl From<NodeWire> for Node {
color_mask: w.color_mask,
warp_piece: w.warp_piece,
clip_pieces: w.clip_pieces,
image_quad,
};
Node {
id: w.id,
+37
View File
@@ -686,6 +686,43 @@ fn reid_gives_fresh_ids() {
assert!(!ids.contains(&a) && !ids.contains(&b));
}
/// A copy of a node in the document takes the Symbol Set Density recorded for it; a node from
/// another document with the same id does not.
#[test]
fn reid_copies_the_set_density_of_the_documents_own_node() {
let (mut d, a, _) = doc_with_rects();
d.unknown.insert(Document::SYMBOL_SET_DENSITY_KEY.into(), serde_json::json!({ a.0.to_string(): 2.0 }));
let density = |d: &Document, id: NodeId| d.unknown[Document::SYMBOL_SET_DENSITY_KEY].get(id.0.to_string()).cloned();
let own = d.node(a).cloned().unwrap();
let copy = d.reid(&own);
assert_eq!(density(&d, copy.id), Some(serde_json::json!(2.0)));
let foreign = Node::group(a, vec![]);
let copy = d.reid(&foreign);
assert_eq!(density(&d, copy.id), None);
}
/// A pasted copy and its descendants take the densities recorded at Copy, and none where Copy
/// recorded none, whatever [`Document::reid`] found for an identical node in the document.
#[test]
fn carry_set_densities_gives_the_densities_recorded_at_copy() {
let (mut d, a, b) = doc_with_rects();
d.unknown.insert(Document::SYMBOL_SET_DENSITY_KEY.into(), serde_json::json!({ a.0.to_string(): 2.0 }));
let density = |d: &Document, id: NodeId| d.unknown[Document::SYMBOL_SET_DENSITY_KEY].get(id.0.to_string()).cloned();
let (na, nb) = (d.node(a).cloned().unwrap(), d.node(b).cloned().unwrap());
// Copy recorded nothing for `a`: the copy reid gave a density loses it.
let copy = d.reid(&na);
assert_eq!(density(&d, copy.id), Some(serde_json::json!(2.0)));
d.carry_set_densities(&na, &copy, &Default::default());
assert_eq!(density(&d, copy.id), None);
// Copy recorded 7 for `b` inside a group: the group's copy has none, and `b`'s copy has 7.
let g = d.alloc_id();
let group = Node::group(g, vec![Arc::new(nb)]);
let copy = d.reid(&group);
d.carry_set_densities(&group, &copy, &[(b, serde_json::json!(7.0))].into_iter().collect());
let inner = copy.children().unwrap()[0].id;
assert_eq!((density(&d, copy.id), density(&d, inner)), (None, Some(serde_json::json!(7.0))));
}
#[test]
fn setup_round_trips_and_old_files_load() {
let (mut d, _, _) = doc_with_rects();
+13
View File
@@ -451,12 +451,25 @@ impl TextObject {
/// fractions of the path. False, changing nothing, for other type, when the anchor doesn't
/// exist, a degenerate `xf` or a path that would not be finite.
pub fn set_path_handle(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool) -> bool {
self.set_path_handle_with_symmetry((si, ai), out, pos, independent, false)
}
/// [`Self::set_path_handle`] with an optional mirror of the opposite handle about the anchor
/// in document space, preserving the anchor kind. `independent` takes precedence, and at an
/// open end of the path, where no segment leaves the anchor on that side, the handle moves as
/// it would without `symmetric`. Both handles are edited in one reshape, using the same validated
/// document-to-text map.
pub fn set_path_handle_with_symmetry(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool, symmetric: bool) -> bool {
let xf = self.xf;
matches!(self.kind, TextKind::OnPath { .. })
&& self.reshape_local(|path, to_text| {
let mirror = symmetric && !independent && path.subpaths.get(si).is_some_and(|sp| sp.has_segment(ai, !out));
let Some(a) = path.anchor_mut(si, ai) else { return false };
let mut drawn = a.transform(xf);
drawn.set_handle(out, pos, independent);
if mirror {
let opposite = drawn.p - (pos - drawn.p);
if out { drawn.h_in = opposite } else { drawn.h_out = opposite }
}
*a = drawn.transform(to_text);
true
})
+6 -8
View File
@@ -111,6 +111,8 @@ fn lengths_of(id: &str) -> Lengths {
"sketch.tornEdges" => always(&["smoothness"]),
"sketch.waterPaper" => always(&["fiberLength"]),
TRAP => always(&["thickness", "precision"]),
// The Pathfinder Options' refit tolerance.
id if crate::takes_pathfinder_options(id) => always(&["precision"]),
RASTERIZE => always(&["addAround"]),
// The points one unit of the filter measures.
crate::SVG_FILTER => always(&["scale"]),
@@ -832,15 +834,11 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
}
for (id, label, _) in PATHFINDER_EFFECTS {
if id == "pathfinder.softMix" {
v.push(g(
id,
label,
PATHFINDER,
"{mixingRate?: 1..100 % (50)} blend overlapping fills in CMYK bottom to top (groups and layers: live Pathfinder over the members)",
json!({"mixingRate": 50.0}),
));
v.push(g(id, label, PATHFINDER, crate::group::SOFT_MIX_PARAMS_DOC, json!({"mixingRate": 50.0})));
} else {
v.push(g(id, label, PATHFINDER, "{} (groups and layers: live Pathfinder over the members)", json!({})));
// No dialog defaults, so the Effect menu applies it directly; effect.apply fills its
// Pathfinder Options in.
v.push(g(id, label, PATHFINDER, crate::group::PATHFINDER_PARAMS_DOC, json!({})));
}
}
v.extend(crate::addons::color::catalog());
+121 -8
View File
@@ -51,6 +51,80 @@ fn op_of(id: &str) -> Option<PathfinderOp> {
PATHFINDER_EFFECTS.iter().find(|e| e.0 == id).map(|e| e.2)
}
/// Does effect `id` keep Pathfinder Options of its own ([`PathfinderEffectOptions`]): one of
/// [`PATHFINDER_EFFECTS`] (Trap has options of its own)?
pub fn takes_pathfinder_options(id: &str) -> bool {
op_of(id).is_some()
}
/// The parameters holding a Pathfinder effect's Pathfinder Options.
pub const PATHFINDER_OPTION_KEYS: [&str; 3] = ["precision", "removeRedundantPoints", "removeUnpainted"];
/// The range of a Pathfinder effect's `precision` (pt), the Pathfinder panel's range.
pub const PATHFINDER_EFFECT_PRECISION: std::ops::RangeInclusive<f64> = 0.001..=10.0;
/// The documentation of [`PATHFINDER_OPTION_KEYS`], as a literal for `concat!`.
macro_rules! options_doc {
() => {
"precision?: pt 0.001..10 (effect.apply: Pathfinder Options › Precision; 0.01 when missing; results are refit to within it and pieces thinner than it are dropped), removeRedundantPoints?: bool (effect.apply: Pathfinder Options › Remove Redundant Points; false when missing; results lose the anchors that don't change their shape to within precision), removeUnpainted?: bool (effect.apply: Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork; false when missing; Divide and Outline leave out the pieces of members with no visible fill, a compound shape's area going by the shape's own fill, except that Divide keeps every piece when the group or compound shape has a visible fill of its own; the other operations ignore it)"
};
}
/// The documentation of [`PATHFINDER_OPTION_KEYS`], shared by the Pathfinder effects' parameters.
pub const PATHFINDER_OPTIONS_DOC: &str = options_doc!();
/// The parameters of a Pathfinder effect other than Soft Mix.
pub const PATHFINDER_PARAMS_DOC: &str = concat!("{", options_doc!(), "} (groups and layers: live Pathfinder over the members)");
/// The parameters of Effect › Pathfinder › Soft Mix.
pub const SOFT_MIX_PARAMS_DOC: &str = concat!(
"{mixingRate?: 1..100 % (50), ",
options_doc!(),
"} blend overlapping fills in CMYK bottom to top (groups and layers: live Pathfinder over the members)"
);
/// The Pathfinder Options a Pathfinder effect evaluates with, read from its parameters. An effect
/// without them (saved before effects kept their own) evaluates as it did then: the default
/// precision, with no points or pieces removed.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PathfinderEffectOptions {
/// Refit tolerance of the results, in points ([`PATHFINDER_EFFECT_PRECISION`]).
pub precision: f64,
/// Drop anchors that don't change a result's shape.
pub remove_redundant_points: bool,
/// Divide and Outline leave out the pieces of members with no visible fill.
pub remove_unpainted: bool,
}
impl Default for PathfinderEffectOptions {
fn default() -> Self {
PathfinderEffectOptions { precision: po::DEFAULT_PRECISION, remove_redundant_points: false, remove_unpainted: false }
}
}
impl PathfinderEffectOptions {
/// The options in `p`: a missing or non-numeric value takes its default and a precision out of
/// range its nearest bound, so a live effect always evaluates.
pub fn from_params(p: &Value) -> Self {
let d = PathfinderEffectOptions::default();
let (lo, hi) = (*PATHFINDER_EFFECT_PRECISION.start(), *PATHFINDER_EFFECT_PRECISION.end());
PathfinderEffectOptions {
precision: crate::util::num(p, "precision", d.precision).clamp(lo, hi),
remove_redundant_points: crate::util::flag(p, "removeRedundantPoints", d.remove_redundant_points),
remove_unpainted: crate::util::flag(p, "removeUnpainted", d.remove_unpainted),
}
}
/// These options as the parameters [`PATHFINDER_OPTION_KEYS`] name.
pub fn to_params(self) -> Value {
serde_json::json!({
"precision": self.precision,
"removeRedundantPoints": self.remove_redundant_points,
"removeUnpainted": self.remove_unpainted,
})
}
}
/// Does `n` (a group or layer) carry a visible Pathfinder effect, or is it a compound shape?
pub fn has_pathfinder(n: &Node) -> bool {
n.is_compound_shape()
@@ -503,6 +577,23 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
out.extend(source.iter().skip(art).cloned());
return Some(out);
}
// When the group has a visible fill of its own, that fill paints its members' geometry, a
// compound shape's area included ([`evaluate_container`]), so Remove Unpainted Artwork keeps
// every Divide piece. Outline's open segments still go by their source's fill.
let own_fill = has_visible_fill(group);
// A compound shape's area has no paint of its own: the shape's own appearance paints it. The
// shape's top painting fill is the area's fill for Remove Unpainted Artwork and for Outline's
// strokes, while Divide pieces stay unpainted so that the fill is not drawn twice.
let area_style = group.is_compound_shape().then(|| {
let items = group.appearance.items.iter().filter(|i| paints(i)).cloned().collect();
Node::path(group.id, PathData::default(), Appearance { items, ..Default::default() })
});
let style_of = |s: &Node| -> Option<Node> {
let a = area_style.as_ref().filter(|_| s.id == group.id && s.appearance.items.is_empty())?;
let mut a = a.clone();
(a.opacity, a.blend) = (s.opacity, s.blend);
Some(a)
};
let mut stack: Vec<Arc<Node>> = if group.is_compound_shape() {
// The group's own appearance paints the area ([`evaluate_container`]), so the art has none.
match compound_shape_area(doc, group, hook) {
@@ -535,6 +626,7 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
continue;
}
let Some(op) = op_of(&e.id) else { continue };
let options = PathfinderEffectOptions::from_params(&e.params);
let shape_mode =
matches!(op, PathfinderOp::Unite | PathfinderOp::MinusFront | PathfinderOp::Intersect | PathfinderOp::Exclude | PathfinderOp::MinusBack);
let nodes = SymbolNodes::default();
@@ -558,7 +650,7 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect();
let key = sources.len() as u64;
if let Some(top) = lv.pop() {
shapes.push(po::Shape::new(po::unite_all(&refs), FillRule::NonZero, key));
shapes.push(po::Shape::new(po::unite_all_with(&refs, options.precision), FillRule::NonZero, key));
sources.push(top);
}
} else {
@@ -574,24 +666,40 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
if shapes.is_empty() {
return Some(vec![]);
}
// Remove Redundant Points: each result loses the anchors that don't change its shape.
let tidy = |path: PathData| if options.remove_redundant_points { po::remove_redundant_points(&path, options.precision) } else { path };
stack = if op == PathfinderOp::SoftMix {
let rate = mixing_rate(&e.params);
po::regions(&shapes)
po::regions_with(&shapes, options.precision)
.into_iter()
.filter(|r| !r.path.is_empty())
.map(|r| Arc::new(soft_mix_face(r.path, &r.sources, rate, &shapes, &sources)))
.map(|r| Arc::new(soft_mix_face(tidy(r.path), &r.sources, rate, &shapes, &sources)))
.collect()
} else if op == PathfinderOp::HardMix {
po::regions(&shapes)
po::regions_with(&shapes, options.precision)
.into_iter()
.filter(|r| !r.path.is_empty())
.map(|r| Arc::new(hard_mix_face(r.path, &r.sources, &shapes, &sources)))
.map(|r| Arc::new(hard_mix_face(tidy(r.path), &r.sources, &shapes, &sources)))
.collect()
} else {
po::pathfinder(op, &shapes)
// Divide and Outline Will Remove Unpainted Artwork: the pieces of members with no
// visible fill go.
let unpainted = options.remove_unpainted
&& match op {
PathfinderOp::Divide => !own_fill,
PathfinderOp::Outline => true,
_ => false,
};
let fill_sources: Vec<Option<Node>> = sources.iter().map(style_of).collect();
let fill_source = |k: u64| fill_sources[k as usize].as_ref().unwrap_or(&sources[k as usize]);
po::pathfinder_with(op, &shapes, options.precision)
.into_iter()
.filter(|r| !r.path.is_empty())
.map(|r| Arc::new(styled(&sources[r.key as usize], r.path, op == PathfinderOp::Outline)))
.filter(|r| !r.path.is_empty() && !(unpainted && !has_visible_fill(fill_source(r.key))))
.map(|r| {
let outline = op == PathfinderOp::Outline;
let src = if outline { fill_source(r.key) } else { &sources[r.key as usize] };
Arc::new(styled(src, tidy(r.path), outline))
})
.collect()
};
}
@@ -676,6 +784,11 @@ pub fn paints(item: &AppearanceItem) -> bool {
}
}
/// Has `n` a visible fill that paints, as the Pathfinder panel's Remove Unpainted Artwork counts it?
fn has_visible_fill(n: &Node) -> bool {
n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.visible && !f.paint.is_none()))
}
/// Do the own fills or strokes of `n`, a group or layer, paint anything?
pub(crate) fn has_own_paint(n: &Node) -> bool {
is_container(n) && n.appearance.items.iter().any(paints)
+75
View File
@@ -213,6 +213,81 @@ fn divide_and_outline_draw_nothing_for_unpainted_members() {
}
}
/// With Remove Unpainted Artwork, Divide and Outline keep the area of a compound shape whose own
/// appearance has a visible fill and leave out the area of one without.
#[test]
fn remove_unpainted_keeps_a_filled_compound_shapes_area() {
for effect in ["pathfinder.divide", "pathfinder.outline"] {
for filled in [true, false] {
let mut g = compound_shape(ShapeMode::Add);
if !filled {
g.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into();
}
g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"removeUnpainted": true}), visible: true });
let out = pathfinder_children(None, &g, None).unwrap();
assert_eq!(!out.is_empty(), filled, "{effect}, filled {filled}: {out:#?}");
}
}
}
/// Outline strokes a compound shape's area in the shape's own fill (its top visible one that
/// paints), with Remove Unpainted Artwork on or off, and Divide leaves the area's pieces
/// unpainted for the shape's fill to paint.
#[test]
fn outline_strokes_a_compound_shapes_area_in_its_fill() {
let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0));
for (remove, covered) in [(false, false), (true, false), (false, true), (true, true)] {
for effect in ["pathfinder.divide", "pathfinder.outline"] {
let mut g = compound_shape(ShapeMode::Add);
if covered {
// A hidden fill and an unpainted fill above the green one.
let mut hidden = FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
hidden.visible = false;
let mut a = (*g.appearance).clone();
a.insert_item(a.items.len(), AppearanceItem::Fill(hidden));
a.insert_item(a.items.len(), AppearanceItem::Fill(FillLayer::new(Paint::None)));
g.appearance = a.into();
}
g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"removeUnpainted": remove}), visible: true });
let out = pathfinder_children(None, &g, None).unwrap();
assert!(!out.is_empty(), "{effect}, remove {remove}");
for n in &out {
if effect == "pathfinder.outline" {
assert_eq!(n.appearance.stroke_paint(), green, "{effect}, remove {remove}: {n:#?}");
assert!(n.appearance.fill_paint().is_none(), "{effect}, remove {remove}: {n:#?}");
} else {
assert!(n.appearance.items.is_empty(), "{effect}, remove {remove}: {n:#?}");
}
}
}
}
}
/// With Remove Unpainted Artwork, Divide keeps the pieces of an unfilled member when its group's
/// own visible fill paints them and leaves them out when the group has no fill. Outline leaves out
/// the member's segments either way.
#[test]
fn remove_unpainted_keeps_members_a_groups_own_fill_paints() {
let unfilled = Arc::new(Node::path(
NodeId(2),
shapes::rectangle(Rect::new(5.0, 0.0, 15.0, 10.0)),
Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0),
));
for effect in ["pathfinder.divide", "pathfinder.outline"] {
for filled in [true, false] {
let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), unfilled.clone()]);
if filled {
g.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0).into();
}
g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"removeUnpainted": true}), visible: true });
let out = pathfinder_children(None, &g, None).unwrap();
assert!(out.iter().any(|n| n.id == NodeId(1)), "{effect}, filled {filled}: {out:#?}");
let kept = filled && effect == "pathfinder.divide";
assert_eq!(out.iter().any(|n| n.id == NodeId(2)), kept, "{effect}, filled {filled}: {out:#?}");
}
}
}
/// Returns an "H" in blue type at 100 pt on a baseline at y = 80, with its stems on either
/// side of x = 100.
fn type_h() -> Node {
+3 -2
View File
@@ -75,8 +75,9 @@ pub use bake::{
};
pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent};
pub use group::{
OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder,
is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, pinned_container_appearance, shape_art,
OutlineHook, PATHFINDER_EFFECT_PRECISION, PATHFINDER_EFFECTS, PATHFINDER_OPTION_KEYS, PATHFINDER_OPTIONS_DOC, PathfinderEffectOptions,
compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder, is_pathfinder, member_leaves,
member_shapes, paints, pathfinder_children, pinned_container_appearance, shape_art, takes_pathfinder_options,
};
pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset};
pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner};
+7 -2
View File
@@ -120,7 +120,10 @@ pub fn new_effect(id: &str, params: &Value) -> Option<Effect> {
/// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see
/// [`EffectInfo::lengths`]), and its sizes in raster pixels ([`crate::raster_px_range`]), which
/// keep their share of the object so. A distance left at its default is written out scaled; one
/// the effect doesn't have (Outline Stroke's weight following its stroke) stays absent.
/// the effect doesn't have (Outline Stroke's weight following its stroke) stays absent. A Pathfinder
/// effect without a `precision` gets the precision it evaluates with, scaled. Values are scaled
/// as stored, out of range or not, so a scale and its inverse restore them; evaluation applies
/// each effect's range.
pub fn scale_effect(e: &mut Effect, s: f64) {
let Some(info) = catalog_index().get(e.id.as_str()) else { return };
let merged = merged_params(&e.id, &e.params);
@@ -128,7 +131,9 @@ pub fn scale_effect(e: &mut Effect, s: f64) {
let mut keys: Vec<&str> = info.lengths.keys(relative).collect();
keys.extend(merged.as_object().into_iter().flat_map(|m| m.keys()).map(String::as_str).filter(|k| crate::raster_px_range(&e.id, k).is_some()));
for k in keys {
let v = util::num(&merged, k, f64::NAN);
let missing =
if k == "precision" && crate::takes_pathfinder_options(&e.id) { crate::PathfinderEffectOptions::default().precision } else { f64::NAN };
let v = util::num(&merged, k, missing);
if v.is_finite() {
if !e.params.is_object() {
e.params = Value::Object(Map::new());
+39 -4
View File
@@ -1248,15 +1248,20 @@ fn as_art_opts(
let fx = geometry_effects(n);
let mut art = match &n.kind {
NodeKind::Image(im) => {
let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
// A distorted image's frame joins its corners.
let frame = match n.image_frame().filter(|_| n.is_distorted_image()) {
Some(bp) => PathData::from_bezpath(&bp),
None => shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf),
};
let mut image = Node::new(n.id, n.kind.clone());
// Its pixels draw as the image's do: colorized by a grayscale image's fill color,
// smoothed or not, and with its color mask's masked pixels.
// smoothed or not, with its color mask's masked pixels, and distorted.
{
let mut e = image.extras_mut();
e.colorize = n.extras().colorize.clone();
e.pixelated = n.extras().pixelated;
e.color_mask = n.extras().color_mask.clone();
e.image_quad = n.extras().image_quad.clone();
}
let clipped = || {
let mut clip = Node::path(n.id, frame.clone(), Appearance::default());
@@ -1276,6 +1281,17 @@ fn as_art_opts(
clipped()
} else {
let opaque = std::cell::OnceCell::new();
// A distorted image's opaque area, traced in its pixels, goes to the page through
// its projective map.
let opaque_on_page = || match n.image_map().filter(|_| n.is_distorted_image()) {
Some(map) => {
let plain = ImageObject { xf: Affine::IDENTITY, ..(**im).clone() };
let piece = f64::from(im.width.max(im.height).max(1)) / 64.0;
opaque_area(&[symbols, paint_doc], &plain)
.map(|p| vectorcraft_doc::live::map_nonlinear(&p, piece, |q| map.apply(q).unwrap_or(q)))
}
None => opaque_area(&[symbols, paint_doc], im),
};
let rows = |items: Vec<AppearanceItem>| {
let mut out = vec![];
let mut items = items.into_iter().peekable();
@@ -1285,7 +1301,7 @@ fn as_art_opts(
while let Some(next) = items.next_if(|i| follows_opaque_area(i) == follows) {
run.push(next);
}
let path = if follows { opaque.get_or_init(|| opaque_area(&[symbols, paint_doc], im)).as_ref() } else { None };
let path = if follows { opaque.get_or_init(opaque_on_page).as_ref() } else { None };
let path = path.unwrap_or(&frame);
if !path.is_empty() {
out.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: run, ..Default::default() })));
@@ -3718,8 +3734,21 @@ fn restore_warped_images(n: &mut Node, warped: &WarpedImages, cut: bool) {
// The pieces start from the image as it was placed when it took its first warp.
let first = warps.first().map(|(_, at)| ImageObject { xf: *at, ..(**own).clone() });
let map = warped_map(warps, own.xf);
// A placement with no inverse cannot take a distorted image's corners back.
let det = own.xf.determinant();
let back = warps.first().filter(|_| det.is_finite() && det != 0.0).map(|(_, at)| *at * own.xf.inverse()).filter(Affine::is_finite);
let distorted = image.extras().image_quad.is_some();
*c = Arc::new(match (first, map) {
(Some(first), Some(map)) if cut => {
(Some(first), Some(map)) if cut && (back.is_some() || !distorted) => {
// A distorted image's corners go back to where they stood at its first warp, as
// its placement does: the moves since then are in `map`.
if let Some(back) = back
&& let Some(q) = image.extras_if_any().and_then(|e| e.image_quad.as_mut())
{
for p in q.iter_mut() {
*p = back * *p;
}
}
let pixelated = image.extras().pixelated;
vectorcraft_doc::live::mesh_warp_image(&image, &first, &*map, WARP_IMAGE_CELLS, pixelated, false)
}
@@ -3787,6 +3816,12 @@ fn copy_placed(n: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc:
NodeKind::SymbolInstance { xf: at, .. } => *at = xf * *at,
_ => {}
}
// A distorted image's corners move with it.
if let Some(q) = one.extras_if_any().and_then(|e| e.image_quad.as_mut()) {
for p in q.iter_mut() {
*p = xf * *p;
}
}
// The placed gradients of its own fills and strokes move with it, as a path's do.
if xf != Affine::IDENTITY && one.appearance.has_positioned_gradient() {
one.appearance.transform_gradients(xf);
+6 -7
View File
@@ -8,7 +8,7 @@ use std::borrow::Cow;
use std::sync::Arc;
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeKind};
use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath};
use vectorcraft_geom::{FillRule, PathData, Rect, SubPath};
use vectorcraft_pathops as po;
use super::{MAX_MEMBERS, Scope, geometry, is_container, members, profile, region, reshape_members, solid_paints};
@@ -144,18 +144,17 @@ impl Resolver<'_> {
}
/// Does the plain image `c` lie wholly outside what the clips around it show together, each
/// clipping path with its own fill rule? Its frame, the pixel rectangle as its transform places
/// it, is cut to each clip in turn until nothing is left. An error when a cut fails or the cuts
/// pass [`MAX_IMAGE_CUTS`]: the image may show, so it can't be left out.
/// clipping path with its own fill rule? Its frame, the quadrilateral of its corners
/// ([`Node::image_corners`]: a distorted image's corners, else the pixel rectangle as its
/// transform places it), is cut to each clip in turn until nothing is left. An error when a
/// cut fails or the cuts pass [`MAX_IMAGE_CUTS`]: the image may show, so it can't be left out.
fn hidden(&mut self, c: &Node) -> Result<bool, String> {
let Some(shown) = &self.shown else { return Ok(false) };
let NodeKind::Image(im) = &c.kind else { return Ok(false) };
let Some(corners) = c.image_corners() else { return Ok(false) };
let Some(b) = c.visual_bounds() else { return Ok(true) };
if b.intersect(shown.bounds).area() <= 0.0 {
return Ok(true);
}
let (w, h) = (f64::from(im.width), f64::from(im.height));
let corners = [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)].map(|(x, y)| im.xf * Point::new(x, y));
if corners.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
return Err(image_refusal(self.label));
}
+2 -1
View File
@@ -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;
+56
View File
@@ -504,6 +504,38 @@ fn warped_images_keep_document_keys_and_hidden_images_apart() {
}
}
/// A distorted image that a later effect leaves with no area after its warp is not cut, and its
/// corners stay finite.
#[test]
fn a_distorted_image_left_with_no_area_after_its_warp_keeps_finite_corners() {
use std::rc::Rc;
use std::sync::Arc;
use vectorcraft_doc::NodeId;
let lift: crate::reshape::WarpMap = Rc::new(|p: Point| Point::new(p.x, p.y - p.x * 0.1));
let mut image = (*warp_test_image(2)).clone();
image.set_image_corners([(10.0, 0.0), (30.0, 0.0), (40.0, 40.0), (0.0, 40.0)].map(|(x, y)| Point::new(x, y))).unwrap();
let mut art = Node::group(NodeId(1), vec![Arc::new(image)]);
let mut warped = crate::reshape::WarpedImages::new();
warped.reserve(&art);
crate::reshape::mark_warped_images(&mut art, &lift, &std::collections::HashSet::new(), false, &mut 0, &mut warped);
// A later effect squeezes the placement flat.
if let Some(c) = art.children_mut()
&& let NodeKind::Image(im) = &mut Arc::make_mut(&mut c[0]).kind
{
im.xf = Affine::scale_non_uniform(1.0, 0.0);
}
crate::reshape::cut_warped_images_within(&mut art, &warped, usize::MAX);
let mut finite = true;
art.walk(&mut |c| {
if let Some(q) = c.extras().image_quad.as_deref() {
finite &= q.iter().all(|p| p.x.is_finite() && p.y.is_finite());
}
});
assert!(finite);
assert_eq!(warp_test_images(&art).0, 1, "not cut");
}
/// An image whose frame keeps its shape because the warp would pass the anchor budget keeps its
/// pixels as they are; within the budget, both bend.
#[test]
@@ -2121,3 +2153,27 @@ fn color_halftones_radius_is_in_raster_pixels_not_a_distance() {
crate::scale_effect(&mut e, 2.0);
assert_eq!((e.params["maxRadius"].as_f64(), e.params["channel1"].as_f64()), (Some(20.0), Some(108.0)));
}
#[test]
fn a_pathfinder_effects_precision_is_a_distance_that_scales_with_the_object() {
for (id, _, _) in PATHFINDER_EFFECTS {
assert!(is_length(id, "precision", false), "{id}");
assert_eq!(length_range(id, "precision"), Some(PATHFINDER_EFFECT_PRECISION), "{id}");
assert!(!is_length(id, "removeRedundantPoints", false) && !is_length(id, "removeUnpainted", false), "{id}");
// Scale Strokes & Effects scales the tolerance with the geometry it is refit to.
let mut e = crate::new_effect(id, &json!({"precision": 0.5, "removeUnpainted": true})).unwrap();
crate::scale_effect(&mut e, 4.0);
assert_eq!(e.params["precision"].as_f64(), Some(2.0), "{id}");
assert_eq!(e.params["removeUnpainted"], json!(true), "{id}");
// An effect saved without the options scales the precision it evaluates with.
let mut e = crate::new_effect(id, &json!({})).unwrap();
crate::scale_effect(&mut e, 3.0);
let scaled = e.params["precision"].as_f64().unwrap_or(f64::NAN);
assert!((scaled - PathfinderEffectOptions::default().precision * 3.0).abs() < 1e-12, "{id}: {scaled}");
// A scale past the range and its inverse restore the precision, as with other distances.
let mut e = crate::new_effect(id, &json!({"precision": 8.0})).unwrap();
crate::scale_effect(&mut e, 2.0);
crate::scale_effect(&mut e, 0.5);
assert_eq!(e.params["precision"].as_f64(), Some(8.0), "{id}");
}
}
+4 -1
View File
@@ -892,6 +892,9 @@ pub use compoundshape::OPEN_PATHS_ADD_NO_AREA;
/// Pathfinder Options (`Prefs::pathfinder`).
pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions};
/// The Pathfinder Options a new Pathfinder effect takes (`effect.apply`).
pub use effectcmd::pathfinder_effect_options;
/// The Attributes panel's state ([`Session::attributes_info`]) and how many recent URLs it keeps.
pub use attributes::RECENT_URLS;
pub use overprint::AttributesInfo;
@@ -909,7 +912,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;
@@ -109,11 +109,11 @@ impl<'a> Reader<'a> {
Ok(union(parts))
}
}
NodeKind::Image(im) => {
let (w, h) = (f64::from(im.width), f64::from(im.height));
let corners = [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)].map(|p| im.xf * p);
self.polygon(&corners)
}
// A distorted image's frame joins its corners.
NodeKind::Image(_) => match n.image_corners() {
Some(corners) => self.polygon(&corners),
None => Ok(None),
},
// An instance of a symbol the document doesn't have draws nothing.
NodeKind::SymbolInstance { .. } => match vectorcraft_render::effects::outline_object(Some(self.doc), n) {
Some(art) => self.node(&art, depth + 1),
@@ -663,6 +663,29 @@ fn an_image_is_measured_by_its_frame_as_turned() {
assert!((end - (300.0 - (y - (300.0 - half)))).abs() < 0.01, "{end} at {y}");
}
#[test]
fn a_distorted_image_is_measured_by_the_frame_through_its_corners() {
let mut s = session();
let im = vectorcraft_doc::ImageObject {
key: "image".into(),
width: 100,
height: 100,
xf: Affine::IDENTITY,
link: None,
placement: Default::default(),
pixels: None,
};
insert(&mut s, |id| {
let mut n = Node::new(id, NodeKind::Image(Box::new(im)));
n.set_image_corners([Point::new(40.0, 0.0), Point::new(60.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)]).unwrap();
n
});
let (b, end) = diamond_weeding(&mut s);
assert!((b.x0 + 10.0).abs() < 1e-3 && (b.y1 - 110.0).abs() < 1e-3, "{b:?}");
// A quarter of the box down (y = 20), the line meets the side from (40, 0) to (0, 100).
assert!((end - 32.0).abs() < 0.01, "{end}");
}
#[test]
fn a_placed_file_is_measured_by_the_art_it_shows() {
let dir = crate::tests_links::Folder::new("weed-placed");
+128 -3
View File
@@ -175,6 +175,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs },
BuiltinBrushLibrary { id: "pressure-sensitive", name: "Pressure Sensitive", make: pressure_sensitive },
BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes },
BuiltinBrushLibrary { id: "paint", name: "Paint", make: paint },
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
BuiltinBrushLibrary { id: "stipple", name: "Stipple", make: stipple },
@@ -182,8 +183,10 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "energy-beams", name: "Energy Beams", make: energy_beams },
BuiltinBrushLibrary { id: "dry-media", name: "Dry Media", make: dry_media },
BuiltinBrushLibrary { id: "tech-circuit", name: "Tech Circuit", make: tech_circuit },
BuiltinBrushLibrary { id: "engraving", name: "Engraving", make: engraving },
BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows },
BuiltinBrushLibrary { id: "image-brush", name: "Image Brush", make: image_brush },
BuiltinBrushLibrary { id: "artistic", name: "Artistic Brushes", make: artistic },
];
/// Built-in library `id`, made once.
@@ -237,6 +240,85 @@ fn art(name: &str, art: Node, colorization: Colorization) -> Brush {
Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) }
}
/// Artistic: four original vector compositions that stretch along a path and take its color.
fn artistic() -> BrushLibrary {
let orbit = group(vec![
black(band(100.0, 1.4, 64, |x| 3.0 * (x * std::f64::consts::TAU / 40.0).sin())),
black(band(100.0, 1.4, 64, |x| -3.0 * (x * std::f64::consts::TAU / 40.0).sin())),
]);
let mut petals = vec![black(band(100.0, 0.8, 4, |_| 0.0))];
for i in 0..6 {
let x = 9.0 + 16.0 * i as f64;
let side = if i % 2 == 0 { 1.0 } else { -1.0 };
petals.push(black(polygon(&[(x - 6.0, 0.0), (x - 2.0, 5.0 * side), (x + 5.0, 7.0 * side), (x + 2.0, 2.0 * side)])));
}
let mut lattice = vec![black(band(100.0, 0.9, 4, |_| 0.0))];
for i in 0..5 {
let x = 20.0 * i as f64;
lattice.push(black(polygon(&[(x, -4.0), (x + 1.0, -4.0), (x + 20.0, 4.0), (x + 19.0, 4.0)])));
lattice.push(black(polygon(&[(x, 4.0), (x + 1.0, 4.0), (x + 20.0, -4.0), (x + 19.0, -4.0)])));
}
let mut facets = Vec::new();
for i in 0..8 {
let x = 12.5 * i as f64;
let high = if i % 2 == 0 { 6.0 } else { 3.5 };
facets.push(black(polygon(&[(x, -high), (x + 11.0, -high / 2.0), (x + 12.5, 0.0), (x + 11.0, high / 2.0), (x, high)])));
}
built(
"Artistic Brushes",
Document::new(100.0, 100.0),
vec![
art("Orbit Lines", orbit, Colorization::Tints),
art("Petal Garland", group(petals), Colorization::Tints),
art("Lattice Braid", group(lattice), Colorization::Tints),
art("Facet Sweep", group(facets), Colorization::Tints),
],
)
}
/// Original fine-line art for an engraving-style brush library.
fn engraving() -> BrushLibrary {
let lines = |count: usize, width: f64, spacing: f64| {
group(
(0..count)
.map(|i| {
let y = (i as f64 - (count - 1) as f64 / 2.0) * spacing;
black(shapes::rectangle(Rect::new(0.0, y - width / 2.0, 100.0, y + width / 2.0)))
})
.collect(),
)
};
let taper = group(
(0..5)
.map(|i| {
let y = (i as f64 - 2.0) * 2.2;
black(polygon(&[(0.0, y - 0.35), (80.0, y - 0.35), (100.0, y), (80.0, y + 0.35), (0.0, y + 0.35)]))
})
.collect(),
);
let broken = group(
(0..5)
.flat_map(|row| {
(0..4).map(move |segment| {
let x = segment as f64 * 25.0 + if row % 2 == 0 { 0.0 } else { 8.0 };
let y = (row as f64 - 2.0) * 2.2;
black(shapes::rectangle(Rect::new(x, y - 0.3, (x + 16.0).min(100.0), y + 0.3)))
})
})
.collect(),
);
built(
"Engraving",
Document::new(100.0, 100.0),
vec![
art("Fine Hatching", lines(5, 0.65, 2.2), Colorization::Tints),
art("Dense Hatching", lines(9, 0.42, 1.2), Colorization::Tints),
art("Tapered Hatching", taper, Colorization::Tints),
art("Broken Hatching", broken, Colorization::Tints),
],
)
}
/// An Arrows brush whose art stretches only between `start` and `end` (fractions of its length).
fn arrow_art(name: &str, art: Node, start: f64, end: f64) -> Brush {
Brush {
@@ -550,6 +632,45 @@ fn spacer(r: Rect) -> Node {
Node::path(NodeId(0), shapes::rectangle(r), Appearance::default())
}
/// Paint: original filled vector art with broad, broken, loaded, and fanned marks. Each is one
/// stroke stretched along the path, with an intentionally different edge and paint distribution.
fn paint() -> BrushLibrary {
let flat_sweep = group(vec![
black(band(100.0, 5.0, 64, |x| 0.8 * (x / 100.0 * std::f64::consts::TAU).sin())),
black(polygon(&[(0.0, -2.5), (7.0, -3.8), (18.0, -2.5)])),
black(polygon(&[(78.0, 2.5), (94.0, 4.0), (100.0, 2.5)])),
]);
let mut dry_drag = vec![];
for (y, shift) in [(-5.0, 0.0), (-3.2, 4.0), (-1.3, 1.0), (0.8, 6.0), (2.8, 3.0), (4.8, 8.0)] {
dry_drag.push(black(shapes::rectangle(Rect::new(2.0 + shift, y, 35.0 + shift, y + 0.8))));
dry_drag.push(black(shapes::rectangle(Rect::new(40.0 + shift, y, 75.0 - shift / 2.0, y + 0.8))));
dry_drag.push(black(shapes::rectangle(Rect::new(80.0 - shift / 2.0, y, 98.0, y + 0.8))));
}
let mut loaded_stroke = vec![black(band(100.0, 6.0, 64, |x| 1.2 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin()))];
for (x, r) in [(12.0, 4.2), (39.0, 3.6), (64.0, 4.8), (88.0, 3.9)] {
loaded_stroke.push(black(shapes::ellipse(Rect::new(x - r, -r - 1.5, x + r, r + 1.5))));
}
let mut fan_sweep = vec![];
for i in -2..=2 {
let offset = i as f64;
fan_sweep.push(black(band(100.0, 1.2, 48, |x| offset * (1.4 + x * 0.045) + 0.3 * (x / 100.0 * std::f64::consts::TAU).sin())));
}
let paint_art = |name: &str, art: Node| Brush {
name: name.into(),
kind: BrushKind::Art(ArtBrush { art, width: 150.0, colorization: Colorization::Tints, ..Default::default() }),
};
built(
"Paint",
Document::new(100.0, 100.0),
vec![
paint_art("Flat Sweep", flat_sweep),
paint_art("Dry Drag", group(dry_drag)),
paint_art("Loaded Stroke", group(loaded_stroke)),
paint_art("Fan Sweep", group(fan_sweep)),
],
)
}
/// Pattern Borders: pattern brushes of tiles drawn here; Beads has corner tiles.
fn pattern_borders() -> BrushLibrary {
let zigzag = black(polygon(&[(0.0, 1.4), (5.0, -2.6), (10.0, 1.4), (10.0, 2.6), (5.0, -1.4), (0.0, 2.6)]));
@@ -992,10 +1113,14 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<BrushLibrary>
return Some(found);
}
if let Some(b) = BUILTIN.iter().find(|b| b.id == key) {
return Some((builtin_info(b), builtin_library(key)?));
return Some((builtin_info(b), builtin_library(b.id)?));
}
let id = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key))?.id;
library(s, &id)
if let Some(id) = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key)).map(|l| l.id) {
return library(s, &id);
}
// Keep the short built-in alias, but let a user or loaded library own its display name.
let b = key.eq_ignore_ascii_case("Artistic").then(|| BUILTIN.iter().find(|b| b.id == "artistic")).flatten()?;
Some((builtin_info(b), builtin_library(b.id)?))
}
fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc<BrushLibrary>)> {
+2 -2
View File
@@ -362,7 +362,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Symbol Sprayer",
[],
None,
"{points: [[x,y]…] (a third number is not used; one that isn't a number is an error), name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full; a `style` the document does not have is then an error. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error",
"{points: [[x,y]…] (a third value is a number or null and is not used), name?, radius?: 40, density?: 1..10 (5; a number outside 1..10 is taken as the nearer end), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one with an amount above 0, at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full; a `style` the document does not have is then an error. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error",
has_doc,
symbol_spray
),
@@ -380,7 +380,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Symbolism Tool",
[],
None,
"{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it; average leaves an instance without a size (a scale of 0) as it is. With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. An instance counts only when it changes, and no undo step is added when none does (none under the brush, average with each already at the mean, or each already at the tool's limit). A `method` that is none of the three, or a pressure that isn't a number, is an error",
"{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, shift?: bool (shift, size, stain and style; false), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name (a graphic style's; left out, or naming no style in the document, the first style after the default one)} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way; style without `shift`: from none to the userDefined amount); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it; average leaves an instance without a size as it is. With `proportional` false a drag resizes along its own direction, the width by the drag's horizontal share and the height by its vertical share (a level drag the width, an upright one the height, a 45° drag both alike; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. The style goes on by the brush's strength at each sample, and a stroke's samples add up. With `alt` and without `shift`, userDefined and random style remove all of an instance's appearance items under the brush at once, whatever the brush's strength. `shift` is the tool's Shift form: shift brings the instances within `radius` of any point one place forward among their siblings (with `alt`, one place backward), once for the stroke, and does not move them; size keeps the instances where they are, `affectsDensity` included; stain and style keep each instance's amount and move its paint toward `color` or the style (stain by the tool's amount at its distance from the point, style by the brush's strength there), whatever `method` is, and leave an instance without a stain or style as it is, and `alt` has no effect. An instance counts only when it changes, and no undo step is added when none does (none under the brush, average with each already at the mean, each already at the tool's limit, or shift with nothing to move or change). A `method` that is none of the three, or a pressure that isn't a number, is an error",
has_doc,
symbol_adjust
),
+7 -3
View File
@@ -86,8 +86,9 @@ pub(super) fn spacing(density: f64) -> f64 {
}
/// The document key that holds each symbol set's Symbol Set Density: `{set id: density}`, written
/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it.
const SET_DENSITY_KEY: &str = "symbolSetDensity";
/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it, and copied to a
/// copy of a set by [`Document::reid`].
const SET_DENSITY_KEY: &str = Document::SYMBOL_SET_DENSITY_KEY;
/// The Symbol Set Density symbol set `set` was created at or last given (None when not recorded).
fn set_density_of(d: &Document, set: NodeId) -> Option<f64> {
@@ -261,7 +262,10 @@ pub(super) fn mean(looks: &[&Look], at: Point, with_gap: bool) -> Option<Mean> {
cos += l.angle.cos();
opacity += l.opacity;
middle += l.center.to_vec2();
if let Some((p, o)) = &l.fill {
// A fill at no opacity shows nothing: it is no stain or style, and its paint is not taken.
if let Some((p, o)) = &l.fill
&& *o > 0.0
{
amount += o;
let far = l.center.distance(at);
if paint.is_none_or(|(_, nearest)| far < nearest) {
+174 -32
View File
@@ -118,6 +118,20 @@ fn instances_of(d: &Document, name: Option<&str>) -> Vec<NodeId> {
v
}
/// The symbol instances in `nodes` and inside them, each once, in the order a walk of each node in
/// turn first reaches them.
fn instances_in<'a>(nodes: impl IntoIterator<Item = &'a Node>) -> Vec<NodeId> {
let (mut v, mut seen) = (vec![], std::collections::HashSet::new());
for n in nodes {
n.walk(&mut |c| {
if matches!(c.kind, NodeKind::SymbolInstance { .. }) && seen.insert(c.id) {
v.push(c.id);
}
});
}
v
}
/// The symbols an instance in `n` (its opacity masks included) places, pushed onto `out`.
fn art_symbols(n: &Node, out: &mut Vec<String>) {
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
@@ -917,11 +931,12 @@ fn samples(p: &Value, cmd: &str) -> Result<Vec<(Point, f64)>> {
let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing points [[x,y]…]"))?;
let mut v = Vec::with_capacity(a.len());
for q in a {
let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue };
// The pressure is checked first: a point skipped for its coordinates still has a bad one refused.
let pressure = match q.get(2) {
None | Some(Value::Null) => 1.0,
Some(f) => f.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad(cmd, format!("a point's pressure must be a number, not {f}")))?,
};
let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue };
v.push((Point::new(x, y), pressure.clamp(0.0, 1.0)));
}
if v.is_empty() || v.iter().any(|(q, _)| !q.x.is_finite() || !q.y.is_finite()) {
@@ -930,13 +945,15 @@ fn samples(p: &Value, cmd: &str) -> Result<Vec<(Point, f64)>> {
Ok(v)
}
/// The fill of the graphic style `p` names with `style`, else of the document's first style after
/// the default one.
/// The fill of the graphic style `p` names with `style`, else (no name, or one the document has no
/// style for, such as the Symbol Styler's style from another document) of the document's first
/// style after the default one.
fn style_paint(d: &Document, p: &Value) -> Option<Paint> {
match str_param(p, "style") {
Some(n) => d.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()),
None => d.graphic_styles.get(1).or(d.graphic_styles.first()).map(|g| g.appearance.fill_paint()),
}
str_param(p, "style")
.and_then(|n| d.graphic_styles.iter().find(|g| g.name == n))
.or(d.graphic_styles.get(1))
.or(d.graphic_styles.first())
.map(|g| g.appearance.fill_paint())
}
/// Deterministic per-point jitter in [-1, 1]² (so previews re-applied on the snapshot agree).
@@ -976,7 +993,7 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result<Value> {
}
let style = style_paint(&st.doc, p);
// Style: User Defined uses the style `style` names, so one the document does not have is an error.
if let Some(n) = str_param(p, "style").filter(|_| !modes.style && style.is_none()) {
if let Some(n) = str_param(p, "style").filter(|n| !modes.style && !st.doc.graphic_styles.iter().any(|g| g.name == *n)) {
return Err(bad(C, format!("unknown graphic style `{n}`")));
}
let size = natural_size(&st.doc, &name);
@@ -1129,6 +1146,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
let use_pressure = switch_or(p, "usePressure", false, C)?;
let proportional = switch_or(p, "proportional", true, C)?;
let affects_density = switch_or(p, "affectsDensity", false, C)?;
let shift = switch_or(p, "shift", false, C)?;
// The Symbol Shifter has no Method.
let method = if tool == "shift" { method_param(p, C).map(|_| Method::UserDefined)? } else { method_param(p, C)? };
// Refused while an object of a dynamic instance's art is selected: the instance stays as it is.
@@ -1141,20 +1159,8 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
let style_paint = style_paint(&st.doc, p);
let candidates: Vec<NodeId> = {
let d = &st.doc;
let mut v = vec![];
if st.selection.is_empty() {
v = instances_of(d, None);
} else {
for id in &st.selection.objects {
if let Some(n) = d.node(*id) {
n.walk(&mut |c| {
if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !v.contains(&c.id) {
v.push(c.id);
}
});
}
}
}
let mut v =
if st.selection.is_empty() { instances_of(d, None) } else { instances_in(st.selection.objects.iter().filter_map(|id| d.node(*id))) };
let editable = d.editable();
v.retain(|id| editable(*id));
v
@@ -1172,12 +1178,39 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
// for the whole stroke (and for every preview of it).
let first = pts.first().map_or(Point::ZERO, |(q, _)| *q);
let share = |id: NodeId| if method == Method::Random { jitter(id.0 as usize, first).0 + 1.0 } else { 1.0 };
// Shift with the Symbol Shifter: the instances under the brush come one place forward among
// their siblings (with `alt`, go one place backward), once for the whole stroke.
if tool == "shift" && shift {
let count = crate::cmd::colorcmds::edit_if_changed(s, label, |_, d| {
let under: std::collections::HashSet<NodeId> = candidates
.iter()
.copied()
.filter(|id| {
d.node(*id).and_then(instance_center).is_some_and(|c| {
pts.iter().any(|(q, pressure)| (if use_pressure { *pressure } else { intensity }) > 0.0 && c.distance(*q) < radius)
})
})
.collect();
let moved = restack(d, &under, alt)?;
Ok((moved, moved > 0))
})?;
return Ok(json!({ "count": count }));
}
// Shift with the Symbol Stainer or the Symbol Styler: the paint an instance's stain or style
// moves toward, and the share of the brush's strength it moves by. Shift with the Symbol Sizer
// keeps the instances where they are, Resizing Affects Density included.
let recolor = match tool.as_str() {
"stain" if shift => Some((Paint::solid(color), 0.15)),
"style" if shift => Some((style_paint.clone().unwrap_or(Paint::solid(color)), 1.0)),
_ => None,
};
let spread = affects_density && !shift;
// No undo step when no instance changes (none under the brush, or Average with each at the mean).
let count = crate::cmd::colorcmds::edit_if_changed(s, label, |orig, d| {
let mut touched = std::collections::BTreeSet::new();
let mut sides = Sides::new();
for (j, (q, pressure)) in pts.iter().enumerate() {
let delta = if j > 0 { *q - pts[j - 1].0 } else { Vec2::ZERO };
let delta = j.checked_sub(1).and_then(|i| pts.get(i)).map_or(Vec2::ZERO, |(prev, _)| *q - *prev);
// Use Pressure Pen: the pen's pressure at the point is the intensity there.
let strength = if use_pressure { *pressure } else { intensity };
// Average: the mean of the instances under the brush, as they are at this point.
@@ -1198,6 +1231,14 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
if w <= 0.0 {
continue;
}
// Shift with the Symbol Stainer or the Symbol Styler: the instance keeps the amount
// of its stain or style, and its paint moves toward the color or the style. An
// instance without one, or without a size, is left as it is.
if let Some((to, step)) = &recolor {
let fill = d.node(*id).and_then(|n| look(d, n, &mut sides)).and_then(|l| l.fill);
touched.extend(recolor_keeping_amount(d, *id, fill, to, step * w).then_some(*id));
continue;
}
// Average needs the instance's own values, so it leaves an instance without a size
// as it is; the other methods change it as before.
// The instance's own values are read for Average only.
@@ -1261,8 +1302,9 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
};
n.transform(about(Affine::scale_non_uniform(kx, ky)), false);
// Resizing Affects Density: instances move away from the brush's center as
// they grow and toward it as they shrink.
if affects_density {
// they grow and toward it as they shrink. Shift keeps the instances where
// they are, so the set's density stays as it was.
if spread {
n.transform(Affine::translate((c - *q) * ((kx * ky).sqrt() - 1.0)), false);
}
}
@@ -1280,9 +1322,10 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
"stain" | "style" => {
let paint = if tool == "style" { style_paint.clone().unwrap_or(Paint::solid(color)) } else { Paint::solid(color) };
let (paint, o) = match &avg {
// Toward the mean amount, keeping the stain or style the instance has.
// Toward the mean amount, keeping the stain or style the instance has
// (one at no opacity is none).
Some((t, look)) => {
let (own, cur) = look.fill.clone().map_or((None, 0.0), |(p, o)| (Some(p), o));
let (own, cur) = look.fill.clone().filter(|(_, o)| *o > 0.0).map_or((None, 0.0), |(p, o)| (Some(p), o));
(own.or(t.paint.clone()).unwrap_or(paint), (cur + (t.amount - cur) * w.min(1.0)) as f32)
}
// Alt with the Symbol Styler removes the instance's appearance.
@@ -1292,11 +1335,11 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
}
None => {
let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0);
// The style goes on gradually, by the brush's strength there: in
// full at the center at full intensity or pressure.
let step = match (tool.as_str(), method) {
// Random: the instance's share of the style, scaled by the
// brush strength there.
("style", Method::Random) => (share / 2.0 * w.min(1.0)) as f32,
("style", _) => 1.0,
("style", Method::Random) => (w * share / 2.0) as f32,
("style", _) => w as f32,
_ => (0.15 * w * share) as f32,
};
(paint, if alt { cur - step } else { cur + step })
@@ -1324,9 +1367,108 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
// An instance the stroke moved away and back again is not counted.
// An instance the stroke moved away and back again, or reached but left as it was (at a
// limit already), is not counted.
touched.retain(|id| d.node(*id) != orig.node(*id));
Ok((touched.len(), !touched.is_empty()))
})?;
Ok(json!({ "count": count }))
}
/// Move the paint of instance `id`'s stain or style (`fill`, its topmost fill with the amount)
/// toward `to` by `t`. The fill keeps its amount and everything else it has, and the instance's
/// other appearance items stay as they are. A paint with no form between it and `to` (a solid
/// color and a pattern, say) takes `to` at once, so repeated strokes below half strength still
/// reach it. An instance without a stain or style, or one whose paint does not change, is left as
/// it is. Returns whether it changed.
fn recolor_keeping_amount(d: &mut Document, id: NodeId, fill: Option<(Paint, f64)>, to: &Paint, t: f64) -> bool {
use vectorcraft_doc::blend::lerp_paint;
let Some((own, _)) = fill.filter(|(_, o)| *o > 0.0) else { return false };
let t = t.clamp(0.0, 1.0) as f32;
let mut paint = lerp_paint(&own, to, t);
// `lerp_paint` switches such a pair halfway, so just below half it still gives `own`.
if paint == own && t > 0.0 && lerp_paint(&own, to, 0.49) == own {
paint = to.clone();
}
if paint == own {
return false;
}
let Some(f) = d.node_mut(id).and_then(|n| n.appearance.fill_mut()) else { return false };
f.paint = paint;
true
}
/// Bring each of `ids` one place forward among its siblings past a sibling that is not one of them
/// (`back`: one place backward). Ones already in front of (behind) every other sibling stay, and
/// so do the clipping path of a clip group and the ruler guides above a layer's art. Returns how
/// many moved.
fn restack(d: &mut Document, ids: &std::collections::HashSet<NodeId>, back: bool) -> Result<usize> {
let parents: std::collections::BTreeSet<Option<NodeId>> = ids.iter().map(|id| d.parent_of(*id)).collect();
let mut moved = 0;
for par in parents {
let floor = usize::from(par.and_then(|p| d.node(p)).is_some_and(Node::clips));
let ch = d.children_mut(par)?;
let len = Node::guide_run_start(ch);
if len <= floor + 1 {
continue;
}
let picked = |n: &Arc<Node>| ids.contains(&n.id);
if back {
for i in floor + 1..len {
if picked(&ch[i]) && !picked(&ch[i - 1]) {
ch.swap(i - 1, i);
moved += 1;
}
}
} else {
for i in (floor..len - 1).rev() {
if picked(&ch[i]) && !picked(&ch[i + 1]) {
ch.swap(i, i + 1);
moved += 1;
}
}
}
}
Ok(moved)
}
#[cfg(test)]
mod tests {
use super::*;
fn instance(id: u64) -> Arc<Node> {
Arc::new(Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY }))
}
/// The instances come out in the order a search of the list built so far gives: nested
/// groups, a group listed twice, a member listed after its group and one listed before it.
#[test]
fn instances_in_matches_searching_the_list_so_far() {
let groups: Vec<Node> = (0..40u64)
.map(|g| {
let base = g * 100;
let mut children: Vec<Arc<Node>> = (0..40).map(|i| instance(base + i)).collect();
let inner = (40..50).map(|i| instance(base + i)).collect();
children.insert(20, Arc::new(Node::group(NodeId(base + 90), inner)));
children.push(Arc::new(Node::group(NodeId(base + 91), vec![])));
Node::group(NodeId(base + 99), children)
})
.collect();
let early = Node::new(NodeId(1_245), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY });
let late = Node::new(NodeId(305), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY });
let nodes: Vec<&Node> = std::iter::once(&early).chain(&groups).chain([&groups[0], &late, &groups[7]]).collect();
let mut searched = vec![];
for n in &nodes {
n.walk(&mut |c| {
if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !searched.contains(&c.id) {
searched.push(c.id);
}
});
}
let found = instances_in(nodes.iter().copied());
assert_eq!(found, searched);
assert_eq!(found.len(), 2_000);
assert_eq!(found[0], NodeId(1_245));
assert!(instances_in([]).is_empty());
}
}
+1 -1
View File
@@ -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.
+36 -20
View File
@@ -58,9 +58,10 @@ fn view_param(cmd: &str, p: &Value) -> Result<Option<TraceView>> {
v.as_str().and_then(TraceView::from_id).map(Some).ok_or_else(|| bad(cmd, format!("view must be one of {}", ids())))
}
/// The `split` param (the Split view's divider, 0 to 1), if given.
/// The `split` param (the Split view's divider, 0 to 1), if given. A null divider is an error, as
/// any other value that is not such a number is; only an omitted one keeps the divider.
fn split_param(cmd: &str, p: &Value) -> Result<Option<f64>> {
let Some(v) = p.get("split").filter(|v| !v.is_null()) else { return Ok(None) };
let Some(v) = p.get("split") else { return Ok(None) };
v.as_f64().filter(|f| (0.0..=1.0).contains(f)).map(Some).ok_or_else(|| bad(cmd, "split must be a number from 0 to 1"))
}
@@ -606,6 +607,30 @@ struct Prepared {
library: Vec<([u8; 3], Paint)>,
}
/// The object `imageTrace.make` would trace, without preparing settings or reading image bytes.
pub fn image_trace_target(s: &Session, p: &Value) -> Result<NodeId> {
target_image(s, "imageTrace.make", p).map(|(target, _)| target)
}
fn target_image(s: &Session, c: &str, p: &Value) -> Result<(NodeId, Box<ImageObject>)> {
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<Prepared> {
let mut params = trace_params(s, c, p)?;
@@ -625,25 +650,16 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result<Prepared> {
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)?;
// The traced shapes are placed by the image's transform, which a distortion overrides: the
// command stops before any pixels are read.
let distorted = s.doc()?.doc.node(target).is_some_and(|n| {
n.is_distorted_image() || (is_trace_group(n) && n.children().and_then(|c| c.first()).is_some_and(|i| i.is_distorted_image()))
});
if distorted {
return Err(crate::cmd::xform::distorted_image_error(c, target));
}
if by_color && s.doc()?.doc.node(target).is_some_and(vectorcraft_render::effects::has_pathfinder) {
return Err(bad(c, LIVE_PATHFINDER_BY_COLOR));
}
+4
View File
@@ -109,6 +109,9 @@ pub struct Clipboard {
/// The selected ruler guides copied with (or without) the objects (#3226), as canvas guides on
/// no layer: pasting puts them on the layer new art goes to, moved as the objects are.
pub guides: Vec<vectorcraft_doc::Guide>,
/// The Symbol Set Density recorded at Copy for each copied symbol set, by its id in
/// [`Self::nodes`]: a pasted set packs from it.
pub set_densities: BTreeMap<NodeId, Value>,
/// The RGB and CMYK profiles the objects' colors showed through in the document they were
/// copied from (its assigned profiles, else the working spaces then), by name; none for objects
/// from outside an open document. Paste compares them with the destination's
@@ -484,6 +487,7 @@ impl Clipboard {
})
.collect(),
guides: self.guides.clone(),
set_densities: self.set_densities.clone(),
source_profiles: self.source_profiles.clone(),
colors_converted: self.colors_converted,
}
@@ -1161,6 +1161,7 @@ impl Clipboard {
char_styles: pick(Res::CharStyle, &src.char_styles),
para_styles: pick(Res::ParaStyle, &src.para_styles),
brushes,
set_densities: src.set_densities_of(&nodes),
nodes,
..Default::default()
}
+84 -24
View File
@@ -26,6 +26,8 @@ use vectorcraft_render::proof;
use super::EngineError;
use super::{CommandSpec, Result, Session, always, bad, cmd, color_value, has_doc, switch_or, targets, text_param};
pub mod proof_file;
/// `Document.unknown` key under which files before format v3 kept the assigned profiles (migrated
/// to `Document::color_profiles` on load).
pub const PROFILES_KEY: &str = vectorcraft_doc::profiles::LEGACY_PROFILES_KEY;
@@ -82,7 +84,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Convert Color",
[],
None,
"{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}",
"{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\"|\"oklch\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}; oklch values are [L (0..100 %), C, H (0..360°)] of the color's display sRGB (CSS Color 4 OKLCH: https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), with H 0 for a gray; a color outside sRGB (a Lab color, a CMYK color or an RGB color in a wider working RGB space) is clipped to sRGB first",
always,
convert_color
),
@@ -100,10 +102,46 @@ pub fn specs() -> Vec<CommandSpec> {
"Proof Setup",
["View", "Proof Setup"],
None,
"{target?: \"workingCmyk\"|\"cmyk:<profile>\"|\"legacyMacRgb\"|\"srgb\"|\"monitorRgb\"|\"protanopia\"|\"deuteranopia\"|\"tritanopia\", intent?, simulatePaper?, proof?: bool (also turn Proof Colors on)} → proof state",
"{target?: \"workingCmyk\"|\"cmyk:<profile>\"|\"rgb:<profile>\"|\"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:<profile> or rgb:<profile> → {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<Value> {
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<Value> {
if active.rgb == name || active.cmyk == name {
use_front_profiles(s);
}
// The CMYK profile View → Proof Setup targets: redraw.
// The profile View → Proof Setup targets: redraw.
if proof_targets(&info.name) {
touch_all(s);
}
@@ -311,9 +349,9 @@ fn touch_assigned(s: &mut Session, name: &str) {
}
}
/// Whether View → Proof Setup targets the CMYK profile `name`.
/// Whether View → Proof Setup targets the CMYK or RGB profile `name`.
fn proof_targets(name: &str) -> bool {
matches!(proof::view().setup.target, ProofTarget::Cmyk(t) if t == name)
matches!(proof::view().setup.target, ProofTarget::Cmyk(t) | ProofTarget::Rgb(t) if t == name)
}
#[cfg(target_arch = "wasm32")]
@@ -1003,7 +1041,7 @@ impl PasteProfile {
if o.keys().any(|k| k != "rgb" && k != "cmyk") {
return Err(refuse());
}
let model = |m: &str| o.get(m).map(&one).transpose();
let model = |m: &str| o.get(m).map(one).transpose();
Ok(Some(PasteChoice { rgb: model("rgb")?, cmyk: model("cmyk")? }))
}
Some(v) => {
@@ -1324,10 +1362,15 @@ fn convert_color(_: &mut Session, p: &Value) -> Result<Value> {
let intent = intent_param(p, C)?.unwrap_or(c.settings().intent);
let lab = c.lab(&col);
let (model, vals) = match text_param(p, "to", C)?.unwrap_or("rgb") {
"rgb" => ("rgb", values(&c.convert(&col, Model::Rgb, intent))),
"cmyk" => ("cmyk", values(&c.convert(&col, Model::Cmyk, intent))),
"gray" | "grayscale" => ("gray", values(&c.convert(&col, Model::Gray, intent))),
"lab" => ("lab", vec![lab.l, lab.a, lab.b]),
"rgb" => ("rgb", json!(values(&c.convert(&col, Model::Rgb, intent)))),
"cmyk" => ("cmyk", json!(values(&c.convert(&col, Model::Cmyk, intent)))),
"gray" | "grayscale" => ("gray", json!(values(&c.convert(&col, Model::Gray, intent)))),
"lab" => ("lab", json!([lab.l, lab.a, lab.b])),
"oklch" => {
// RGB numbers past 0..1 ([2, 2, 2]) display clipped, as `hex` reports them.
let [l, ch, h] = vectorcraft_color::oklab::to_oklch(c.display_rgb(&col).map(|v| v.clamp(0.0, 1.0)));
("oklch", json!([l * 100.0, ch, h]))
}
other => return Err(bad(C, format!("unknown model `{other}`"))),
};
let de = c.gamut_error(&col);
@@ -1392,6 +1435,8 @@ fn view_json(v: &proof::ProofView) -> Value {
"target": v.setup.target.id(),
"intent": v.setup.intent.id(),
"simulatePaper": v.setup.simulate_paper,
"preserveNumbers": v.setup.preserve_numbers,
"simulateBlack": v.setup.simulate_black,
"proofColors": v.proof_colors,
"overprintPreview": v.overprint,
"separations": v.separations,
@@ -1401,19 +1446,7 @@ fn view_json(v: &proof::ProofView) -> Value {
fn proof_setup(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "view.proofSetup";
let mut v = proof::view();
if let Some(t) = text_param(p, "target", C)? {
let t = ProofTarget::parse(t).ok_or_else(|| bad(C, format!("unknown proof target `{t}`")))?;
if let ProofTarget::Cmyk(name) = &t
&& !cms::profile(name).is_some_and(|k| k.kind == cms::ProfileKind::Cmyk)
{
return Err(bad(C, format!("unknown CMYK profile `{name}`")));
}
v.setup.target = t;
}
if let Some(i) = intent_param(p, C)? {
v.setup.intent = i;
}
v.setup.simulate_paper = switch_or(p, "simulatePaper", v.setup.simulate_paper, C)?;
setup_params(p, &mut v.setup, C)?;
if let Some(on) = on_param(p, "proof", C)? {
v.proof_colors = on;
}
@@ -1421,6 +1454,33 @@ fn proof_setup(s: &mut Session, p: &Value) -> Result<Value> {
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) {
@@ -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:<profile> or rgb:<profile>", t.id())),
}
}
/// The settings of `setup`, as `view.proofSetup` names them.
fn setup_json(setup: &ProofSetup) -> serde_json::Map<String, Value> {
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<ProofSetup, String> {
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<u8> {
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<Option<Value>> {
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<Option<Value>> {
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
// `<name>.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::<String>::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<Value> = 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})))
}
+53
View File
@@ -105,6 +105,15 @@ pub fn specs() -> Vec<CommandSpec> {
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<Value> {
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<Value> {
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).
+2 -2
View File
@@ -14,7 +14,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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);
+2
View File
@@ -1568,6 +1568,8 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
for xf in placements {
for (k, n) in clip.nodes.iter().enumerate() {
let mut c = d.reid(n);
// A pasted symbol set packs from the density recorded for it at Copy.
d.carry_set_densities(n, &c, &clip.set_densities);
imported.apply(&mut c);
let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() };
if xf != Affine::IDENTITY {
+58
View File
@@ -442,6 +442,17 @@ fn check_revolve_count(n: &Node, cmd: &str) -> Result<()> {
pub(crate) const ONE_3D: &str = "An object takes one 3D effect. Edit the existing effect's options, or remove it first.";
/// The Pathfinder Options that `effect.apply` gives a Pathfinder effect for the keys its `params`
/// leave out: the preferences' Pathfinder Options in force.
pub fn pathfinder_effect_options(s: &Session) -> effects::PathfinderEffectOptions {
let current = super::pathops::current_pf_options(s);
effects::PathfinderEffectOptions {
precision: current.precision,
remove_redundant_points: current.remove_redundant_points,
remove_unpainted: current.remove_unpainted,
}
}
/// `effect.apply`: adds effect `effect` (or `id`) with `params`, its defaults filled in, to the
/// targets' active item as one undo step. A 3D effect must fit each target, which takes only one;
/// a Pathfinder effect on loose objects groups them first. → `{ids, index, item}`.
@@ -465,10 +476,23 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
super::params::check_effect_color(C, id, &params)?;
super::params::check_effect_channel(C, id, &params)?;
super::params::check_effect_center(C, id, &params)?;
super::params::check_effect_pathfinder(C, id, &params)?;
// Crop Marks take their style from the preferences when applied.
if id == effects::CROP_MARKS && params.get("style").is_none() {
params["style"] = json!(s.crop_mark_style().id());
}
// A Pathfinder effect keeps the Pathfinder Options in force when it is applied, those `params`
// give aside. They join the journal entry, so replaying it gives the same effect.
if effects::takes_pathfinder_options(id) {
if let Value::Object(filled) = pathfinder_effect_options(s).to_params() {
for (key, v) in filled {
if params.get(&key).is_none() {
params[key.as_str()] = v;
}
}
}
s.note_journal("params", params.clone());
}
if texture_load_effect(id) {
load_texture(&mut params, C)?;
}
@@ -793,6 +817,7 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
super::params::check_effect_color(C, effect, &params)?;
super::params::check_effect_channel(C, effect, &params)?;
super::params::check_effect_center(C, effect, &params)?;
super::params::check_effect_pathfinder(C, effect, &params)?;
}
if edited.iter().any(|e| texture_load_effect(e)) {
load_texture(&mut params, C)?;
@@ -815,6 +840,15 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result<Value> {
return Ok(json!({ "ids": [] }));
}
}
// Pathfinder effects given the values they already evaluate with, and nothing else to change,
// are no edit and record no undo step.
if kind.is_none() && warp_id.is_none() && visible.is_none() {
let d = &s.doc()?.doc;
let fx: Vec<&Effect> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index)).collect();
if !fx.is_empty() && fx.iter().all(|e| pathfinder_edit_changes_nothing(e, &params)) {
return Ok(json!({ "ids": [] }));
}
}
// An SVG filter is named by its id: another filter renames the effect.
if edited.iter().any(|e| e == effects::SVG_FILTER)
&& let Some(xml) = params.get("xml").and_then(Value::as_str)
@@ -889,6 +923,30 @@ fn bevel_effect(id: &str) -> bool {
id == effects::EXTRUDE || id == effects::CLASSIC_EXTRUDE
}
/// Does merging `params` into Pathfinder effect `e` leave it drawing as it does: the same Pathfinder
/// Options ([`effects::PathfinderEffectOptions`], so an effect saved without them and given their
/// defaults is unchanged), each option given equal to the one it stores (a precision that Scale
/// Strokes & Effects took past its range evaluates at the bound but is still edited), and every
/// other value given equal to the one it has?
fn pathfinder_edit_changes_nothing(e: &Effect, params: &Value) -> bool {
if !effects::takes_pathfinder_options(&e.id) {
return false;
}
let Some(given) = params.as_object().filter(|m| !m.is_empty()) else { return true };
let current = effects::merged_params(&e.id, &e.params);
let mut after = current.clone();
if let Value::Object(m) = &mut after {
m.extend(given.clone());
}
let others_same = given.iter().filter(|(k, _)| !effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str())).all(|(k, v)| current.get(k) == Some(v));
let same_value = |a: &Value, b: &Value| a == b || a.as_f64().is_some_and(|x| b.as_f64() == Some(x));
let stored_same = given
.iter()
.filter(|(k, _)| effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str()))
.all(|(k, v)| e.params.get(k).is_none_or(|stored| same_value(stored, v)));
others_same && stored_same && effects::PathfinderEffectOptions::from_params(&current) == effects::PathfinderEffectOptions::from_params(&after)
}
// ---------- Load Texture ----------
/// Effect › Distort › Glass.
+610 -96
View File
@@ -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<Clip>,
/// 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<bool>,
/// Those records, in the order they were counted.
noted_log: Vec<usize>,
/// The records counted as hidden layers left out.
skipped: Vec<bool>,
/// Those records, in the order they were counted.
skip_log: Vec<usize>,
/// The records counted as knockouts not applied.
unknocked: Vec<bool>,
/// Those records, in the order they were counted.
unknock_log: Vec<usize>,
/// The records counted as layers clipped to a fill that isn't drawn.
clipped_out: Vec<bool>,
/// Those records, in the order they were counted.
clipped_out_log: Vec<usize>,
/// The records counted as clipped layers left unclipped.
unclipped: Vec<bool>,
/// Those records, in the order they were counted.
unclip_log: Vec<usize>,
/// 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<bool>,
/// Bytes of layer and mask pixels decoded, and of canvases the merges made, so far.
spent: Cell<u64>,
/// 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<u64>,
/// `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<u64>,
/// The layers whose pixels were read so far (each time they were).
painted: Cell<usize>,
/// 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<Option<Drawn>>,
/// The pass-through groups that laid nothing onto nothing (see [`Self::laid_nothing`]).
laid_blank: Vec<bool>,
/// The groups of both, in the order they were found.
blank_log: Vec<usize>,
/// How many times a merge was counted as not made because it needed more memory than allowed.
squeezed: usize,
}
impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
@@ -786,10 +878,38 @@ impl<F: Fn([f32; 4]) -> [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<F: Fn([f32; 4]) -> [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<F: Fn([f32; 4]) -> [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<F: Fn([f32; 4]) -> [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<F: Fn([f32; 4]) -> [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<F: Fn([f32; 4]) -> [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<F: Fn([f32; 4]) -> [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<F: Fn([f32; 4]) -> [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<F: Fn([f32; 4]) -> [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<bool, String> {
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<F: Fn([f32; 4]) -> [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<Vec<Unit<'i>>, 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<Vec<Unit<'i>>, 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<Unit<'i>> = 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<F: Fn([f32; 4]) -> [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::<Vec<_>>() {
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<F: Fn([f32; 4]) -> [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<F: Fn([f32; 4]) -> [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<Unit<'i>>, 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::<Vec<_>>() {
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<Knocked, String> {
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<Canvas> = 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<bool, String> {
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<Canvas>, 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<Canvas>, u: &Unit<'_>) -> Result<bool, String> {
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<F: Fn([f32; 4]) -> [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<F: Fn([f32; 4]) -> [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<Canvas>, items: &[Item]) -> Result<bool, String> {
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<Canvas>, items: &[Item], level: Level) -> Result<bool, String> {
for c in self.merged(items, false, level)? {
if !self.composite(acc, &c)? {
return Ok(false);
}
@@ -1271,13 +1692,29 @@ impl<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
}
None => return Ok(Drawn::Nothing),
},
Body::Group(items) => {
let mut acc: Option<Canvas> = 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<Canvas> = 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<F: Fn([f32; 4]) -> [f32; 3]> Builder<'_, F> {
Ok(n)
}
/// Layers of the document for `items`, bottom first.
fn list(&mut self, items: &[Item]) -> Result<Vec<Arc<Node>>, String> {
/// Layers of the document for `items`, the layers at `level`, bottom first.
fn list(&mut self, items: &[Item], level: Level) -> Result<Vec<Arc<Node>>, 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<F: Fn([f32; 4]) -> [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<Option<Node>, 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<F: Fn([f32; 4]) -> [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<bool, String> {
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<Canvas>,
knock: &Canvas,
blend: Blend,
fill: f32,
opacity: f32,
record: usize,
max_alloc: u64,
spend: &dyn Fn(u64) -> Result<(), String>,
) -> Result<bool, String> {
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<Canvas>, src: &Canvas, max_alloc: u64, spend: &dyn Fn(u64) -> Result<(), String>) -> Result<bool, String> {
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;
@@ -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<L> {
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<String>, Vec<String>) {
let d = &s.doc().unwrap().doc;
let names = |ls: &[std::sync::Arc<Node>]| ls.iter().map(|l| name(l).to_string()).collect::<Vec<_>>();
(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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>());
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::<Vec<_>>());
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::<Vec<_>>();
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::<Vec<_>>(), ["Inner", "Outer cut"], "{warnings:?}");
assert_eq!(outer[0].children().unwrap().iter().map(|c| name(c)).collect::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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::<Vec<_>>(), ["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]);
+5 -1
View File
@@ -141,7 +141,11 @@ impl Builder {
if fills.is_empty() { Body::Complex } else { Body::Fills { shape: self.shape(path, rule, Kind::Vector)?, fills } }
}
NodeKind::Image(im) => {
let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf);
// A distorted image's frame joins its corners.
let frame = match n.image_frame().filter(|_| n.is_distorted_image()) {
Some(bp) => PathData::from_bezpath(&bp),
None => shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf),
};
self.shape(frame, FillRule::NonZero, Kind::Other)?;
Body::Complex
}
File diff suppressed because one or more lines are too long
+49 -1
View File
@@ -1211,6 +1211,16 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_
install(d, &[id], read, Some(Preserve::Bounds), None)
}
/// Distorted image `im` shows the file read for `link` (`img`) and keeps its corners and its
/// clipping: the new pixels fill them. Its transform is scaled to the new pixel size, so a reader
/// that places it by the transform still gives it its old size.
fn refill_distorted(im: &mut ImageObject, link: &LinkInfo, img: &RasterImage) {
if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 {
im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height));
}
(im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone()));
}
/// Image objects `ids` (in the layers or outside them) show the file read for `link` (`img`), each
/// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say);
/// with `also` (a file's path and the content shown), so do the images outside the layer tree that
@@ -1235,7 +1245,12 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| {
let mut n = n.clone();
let mut clip = ClipTo::Keep;
let distorted = n.is_distorted_image();
if let NodeKind::Image(im) = &mut n.kind {
if distorted {
refill_distorted(im, &link, &img);
return (n, clip);
}
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
let size = |w: u32, h: u32| (w as f64, h as f64);
let (old_pt, old_clip) = match old.get(&im.key) {
@@ -1251,6 +1266,14 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio
Nested { pick: &pick, make: &mut make, next: 0 }.run(d);
}
for id in ids {
if d.node(*id).is_some_and(Node::is_distorted_image) {
if let Some(n) = d.node_mut(*id)
&& let NodeKind::Image(im) = &mut n.kind
{
refill_distorted(im, &link, &img);
}
continue;
}
let Some(NodeKind::Image(im)) = d.node(*id).map(|n| &n.kind) else { continue };
let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement };
let size = |w: u32, h: u32| (w as f64, h as f64);
@@ -2068,6 +2091,9 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
_ => None,
})
};
// Whether the images were found as the missing links (nothing selected, a folder given) rather
// than named or selected.
let mut found_missing = false;
let mut ids: Vec<NodeId> = match (&each, ids_param(p, "ids", C)?) {
(Some(each), _) => each.iter().flat_map(|(ids, _)| ids.iter().copied()).collect(),
(None, Some(ids)) => ids,
@@ -2075,6 +2101,7 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
let selected: Vec<NodeId> = st.selection.objects.iter().copied().filter(|id| image(id).is_some()).collect();
match folder_param {
Some(_) if selected.is_empty() => {
found_missing = true;
groups(&st.doc, None).into_iter().filter(|g| probe(g, LinkBase::of(st)).0 == Status::Missing).flat_map(|g| g.ids).collect()
}
_ => selected,
@@ -2087,6 +2114,11 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
if ids.is_empty() {
return Err(bad(C, "select the images to relink, or pass ids"));
}
// A named or selected distorted image is refused before a folder is searched, whether or not
// its file is found there.
if !found_missing && let Some(id) = ids.iter().find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)) {
return Err(super::xform::distorted_image_error(C, *id));
}
// All Instances: the other stored objects linked to the same files, each once.
if scope == Scope::All {
let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect();
@@ -2131,6 +2163,11 @@ fn relink(s: &mut Session, p: &Value) -> Result<Value> {
}
(None, None, None) => return Err(bad(C, "give path (a file) or folder")),
}
// A new file's placement options place a plain image: a distorted one is left as it is.
let distorted = files.iter().flat_map(|(ids, _)| ids).find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image));
if let Some(id) = distorted {
return Err(super::xform::distorted_image_error(C, *id));
}
// Every file is read and checked before any is copied.
let mut checked = vec![];
for (ids, path) in files {
@@ -2593,6 +2630,9 @@ fn embed(s: &mut Session, p: &Value) -> Result<Value> {
if ids.is_empty() {
return Err(bad(C, "select the linked images or placed documents, or pass ids"));
}
if let Some(id) = ids.iter().find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)) {
return Err(super::xform::distorted_image_error(C, *id));
}
// A DCS file's plates print from its file.
let separated = |id: &NodeId| match kind(id) {
Some(NodeKind::Image(im)) => st.doc.images.get(&im.key).is_some_and(ImageBlob::is_separated),
@@ -2721,6 +2761,9 @@ fn unembed(s: &mut Session, p: &Value) -> Result<Value> {
if im.link.is_some() {
return Err(bad(C, format!("image {} is linked already", id.0)));
}
if n.is_distorted_image() {
return Err(super::xform::distorted_image_error(C, id));
}
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
// As stored (PNG, JPEG, GIF, WebP), unless the path names another format.
let stored = stored_extension(blob);
@@ -2772,6 +2815,9 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option<Vec<NodeId>>) -> Re
skipped.push(id);
continue;
}
if n.is_distorted_image() {
return Err(super::xform::distorted_image_error(C, id));
}
let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?;
embedded.push((id, n.display_name(), blob));
}
@@ -2984,7 +3030,9 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
let (px, py) = file_pt(&st.doc, &im.key);
out["effectivePpi"] = out["ppi"].take();
out["ppi"] = json!([72.0 / px, 72.0 / py]);
(out["scale"], out["rotation"]) = scale_rotation(im.xf, (px, py));
// A distorted image is measured at its middle, as its effective resolution is.
let xf = stored(&doc, id).and_then(vectorcraft_doc::image_quad::nearest_affine).unwrap_or(im.xf);
(out["scale"], out["rotation"]) = scale_rotation(xf, (px, py));
out["format"] = json!(format_label(&st.doc, im));
out["placement"] = placement_json(im.placement);
out["status"] = json!("embedded");
+16
View File
@@ -244,12 +244,22 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
Some(_) => return Err(bad(C, "handle must be in or out")),
};
let independent = switch_or(p, "independent", false, C)?;
let symmetric = switch_or(p, "symmetric", false, C)?;
let link = switch_or(p, "link", false, C)?;
let with = spine_points_param(p, C)?;
// Any `with`, even an empty list, asks to move points, which a handle drag doesn't.
if handle.is_some() && p.get("with").is_some_and(|v| !v.is_null()) {
return Err(bad(C, "`with` moves points, not a handle"));
}
if symmetric && independent {
return Err(bad(C, "`independent` and `symmetric` cannot both be true"));
}
if symmetric && handle.is_none() {
return Err(bad(C, "`symmetric` places a handle: give `handle`"));
}
if link && symmetric {
return Err(bad(C, "`link` and `symmetric` cannot both be true"));
}
if link && independent {
return Err(bad(C, "`link` and `independent` cannot both be true"));
}
@@ -264,6 +274,8 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
}
edit_spine(s, p, C, "Reshape Spine", |sp, anchors, keys| {
let pull_out = handle.is_some_and(|out| sp.has_segment(index, !out));
// At an open end of the spine the handle moves as it would without `symmetric`.
let symmetric = symmetric && pull_out;
let a = sp.anchors.get_mut(index).ok_or_else(|| bad(C, "no such spine point"))?;
if let Some(out) = handle {
if link {
@@ -271,6 +283,10 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
} else {
a.set_handle(out, q, independent);
}
if symmetric {
let opposite = a.p - (q - a.p);
if out { a.h_in = opposite } else { a.h_out = opposite }
}
return Ok(());
}
let delta = q - a.p;
+1 -1
View File
@@ -99,7 +99,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Spine Point",
[],
None,
"{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `link` needs `handle` and cannot go with `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
"{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, symmetric?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `symmetric` mirrors the opposite handle about the anchor without changing its kind, except at an open end of the spine; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `symmetric` and `link` need `handle`, `symmetric` cannot go with `independent`, and `link` cannot go with `independent` or `symmetric`; all default false). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path",
has_doc,
spine_move_anchor
),
+15 -3
View File
@@ -25,14 +25,23 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> {
};
let (rows, cols) = if at.is_some() { (1, 1) } else { (rows, cols) };
let roots = roots_param(s, p)?;
// The distorted images left as they are, each with why.
let mut distorted = vec![];
let (ids, index) = s.edit("Create Gradient Mesh", |d, sel| {
let mut out = vec![];
let mut index = None;
let mut refused = None;
let model = d.color_mode.model();
distorted.clear();
for id in &roots {
let Some(n) = d.node(*id).cloned() else { continue };
let m = if let NodeKind::Image(im) = &n.kind {
if n.is_distorted_image() {
let e = super::super::xform::distorted_image_error(C, *id);
distorted.push(json!({"id": id.0, "reason": e.to_string()}));
refused.get_or_insert(e);
continue;
}
// An embedded image: the points take the picture's colours there.
match image_mesh(d, im, rows, cols) {
Ok(mut m) => {
@@ -40,7 +49,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> {
Some(m)
}
Err(why) => {
refused.get_or_insert(why);
refused.get_or_insert_with(|| bad(C, why));
continue;
}
}
@@ -60,7 +69,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> {
match m.add_lines_at(q, tol) {
Some(i) => index = Some(i),
None => {
refused.get_or_insert("point is outside the object");
refused.get_or_insert_with(|| bad(C, "point is outside the object"));
continue;
}
}
@@ -75,7 +84,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> {
out.push(*id);
}
if out.is_empty() {
return Err(bad(C, refused.unwrap_or("select a path, a compound path or an embedded image")));
return Err(refused.unwrap_or_else(|| bad(C, "select a path, a compound path or an embedded image")));
}
sel.set(out.iter().copied());
Ok((out, index))
@@ -84,6 +93,9 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(i) = index {
r["index"] = json!(i);
}
if !distorted.is_empty() {
r["skipped"] = json!(distorted);
}
Ok(r)
}
+15 -4
View File
@@ -998,6 +998,9 @@ fn mosaic_plan(s: &Session, p: &Value) -> Result<MosaicPlan> {
.ok_or_else(|| bad(C, "select an image"))?;
let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) };
if node.is_distorted_image() {
return Err(super::xform::distorted_image_error(C, id));
}
if !st.doc.images.get(&im.key).is_some_and(|b| !b.bytes.is_empty()) {
return Err(bad(C, "the image has no embedded pixels"));
}
@@ -1285,6 +1288,9 @@ fn crop_image(s: &mut Session, p: &Value) -> Result<Value> {
.ok_or_else(|| bad(C, "select an image"))?;
let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?;
let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) };
if node.is_distorted_image() {
return Err(super::xform::distorted_image_error(C, id));
}
if switch_or(p, "trim", false, C)? {
if p.get("ppi").is_some_and(|v| !v.is_null()) {
return Err(bad(C, "trim keeps the image's pixels as they are: leave out ppi"));
@@ -1495,11 +1501,16 @@ fn mask_image(s: &mut Session, _: &Value) -> Result<Value> {
.selection
.objects
.iter()
.find_map(|id| match st.doc.node(*id).map(|n| &n.kind) {
Some(NodeKind::Image(im)) => {
Some((*id, vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf)))
.find_map(|id| {
let n = st.doc.node(*id)?;
match &n.kind {
// A distorted image's outline joins its corners.
NodeKind::Image(_) if n.is_distorted_image() => Some((*id, PathData::from_bezpath(&n.image_frame()?))),
NodeKind::Image(im) => {
Some((*id, vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf)))
}
_ => None,
}
_ => None,
})
.ok_or_else(|| bad("object.maskImage", "select an image"))?;
let (gid, pid) = s.edit("Mask", |d, sel| {
+1 -1
View File
@@ -305,7 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
"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
),
+31 -4
View File
@@ -202,6 +202,16 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
// 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<f64>, 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<Value> {
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<Value> {
}
*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<Value> {
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()
+31 -5
View File
@@ -516,7 +516,30 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()>
}
check_effect_color(id, effect, params)?;
check_effect_channel(id, effect, params)?;
check_effect_center(id, effect, params)
check_effect_center(id, effect, params)?;
check_effect_pathfinder(id, effect, params)
}
/// The Pathfinder Options in `params` of a Pathfinder effect (`effect`), as command `id` was given
/// them: `precision` a number of points from 0.001 to 10, and `removeRedundantPoints` and
/// `removeUnpainted` true or false. `effect.apply` and `effect.setParams` run this themselves
/// before they edit, as they run [`check_effect_color`].
pub(crate) fn check_effect_pathfinder(id: &str, effect: &str, params: &Value) -> Result<()> {
use vectorcraft_render::effects;
if !effects::takes_pathfinder_options(effect) {
return Ok(());
}
if let Some(v) = params.get("precision")
&& !v.as_f64().is_some_and(|p| effects::PATHFINDER_EFFECT_PRECISION.contains(&p))
{
return Err(bad(id, "precision must be from 0.001 to 10 pt"));
}
for key in ["removeRedundantPoints", "removeUnpainted"] {
if params.get(key).is_some_and(|v| !v.is_boolean()) {
return Err(bad(id, format!("`{key}` must be true or false")));
}
}
Ok(())
}
/// The type of the values in `params` of effect `effect`, as command `id` was given them: a key
@@ -557,10 +580,11 @@ fn check_effect_types(id: &str, effect: &str, params: &Value) -> Result<()> {
/// A value of the type effect `effect` reads for `key`, a parameter its params description names
/// without a dialog default: the earlier 3D Perspective and light (`perspective`, `lightAzimuth`,
/// `lightElevation`) and Scribble `variation` are numbers, an Outline Stroke's `width` is a number
/// and a Gaussian Blur's `linear` is true or false. A Glass, Texturizer or Rough Pastels
/// `textureImage`, an SVG filter's `name` and `xml`, a Warp's `version`, the `style` of Crop Marks
/// and an Extrude & Bevel's custom `bevelName` and `bevelProfile` have checks of their own; they
/// aren't listed.
/// and a Gaussian Blur's `linear` is true or false. A Pathfinder effect's `precision` is a number and
/// its `removeRedundantPoints` and `removeUnpainted` are true or false. A Glass, Texturizer or Rough
/// Pastels `textureImage`, an SVG filter's `name` and `xml`, a Warp's `version`, the `style` of Crop
/// Marks and an Extrude & Bevel's custom `bevelName` and `bevelProfile` have checks of their own;
/// they aren't listed.
pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option<Value> {
use vectorcraft_render::effects;
let number = || Some(Value::from(0.0));
@@ -569,6 +593,8 @@ pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option<Value> {
"variation" if effect == "stylize.scribble" => number(),
"width" if effect == "path.outlineStroke" => number(),
"linear" if effect == "blur.gaussian" => Some(Value::Bool(false)),
"precision" if effects::takes_pathfinder_options(effect) => number(),
"removeRedundantPoints" | "removeUnpainted" if effects::takes_pathfinder_options(effect) => Some(Value::Bool(false)),
_ => None,
}
}
+26 -1
View File
@@ -50,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Direction Handle",
[],
None,
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); link and independent cannot both be true; both default false; with link false, at moves the anchor and both handles before placing the chosen handle",
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle",
has_doc,
set_handle
),
@@ -461,6 +461,13 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
return link_handle(s, p, id, si, ai, out, pos);
}
let independent = switch_or(p, "independent", false, "path.setHandle")?;
let symmetric = switch_or(p, "symmetric", false, "path.setHandle")?;
if symmetric && independent {
return Err(bad("path.setHandle", "`independent` and `symmetric` cannot both be true"));
}
// The other handle is mirrored only where a segment leaves the anchor on its side: at an open
// end the handle moves as it would without `symmetric`.
let symmetric = symmetric && has_segment(s, id, si, ai, !out)?;
let at = match p.get("at").filter(|v| !v.is_null()) {
None => None,
Some(v) => Some(finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad("path.setHandle", "`at` must be [x, y]"))?),
@@ -472,6 +479,7 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
&& at.is_none_or(|to| to == a.p)
&& (if out { a.h_out } else { a.h_in }) == pos
&& !(independent && a.kind != AnchorKind::Corner)
&& (!symmetric || (if out { a.h_in } else { a.h_out }) == a.p - (pos - a.p))
{
return ok();
}
@@ -504,6 +512,10 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
} else {
a.set_handle(out, pos, independent);
}
if symmetric {
let opposite = a.p - (pos - a.p);
if out { a.h_in = opposite } else { a.h_out = opposite }
}
Ok(())
})?;
ok()
@@ -519,6 +531,9 @@ fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out
if switch_or(p, "independent", false, C)? {
return Err(bad(C, "`link` and `independent` cannot both be true"));
}
if switch_or(p, "symmetric", false, C)? {
return Err(bad(C, "`link` and `symmetric` cannot both be true"));
}
if !(pos.x.abs() < 1e9 && pos.y.abs() < 1e9) {
return Err(bad(C, "x and y must be finite"));
}
@@ -655,6 +670,16 @@ fn anchor_of(s: &Session, id: NodeId, si: usize, ai: usize) -> Result<Option<Anc
Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).and_then(|sp| sp.anchors.get(ai)).copied())
}
/// Whether anchor `ai` of subpath `si` of path `id` has a segment on its outgoing (`out`) or
/// incoming side; false when the path, subpath or anchor is not there.
fn has_segment(s: &Session, id: NodeId, si: usize, ai: usize, out: bool) -> Result<bool> {
if s.script_running() {
return Err(EngineError::Busy);
}
let d = &s.doc()?.doc;
Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).is_some_and(|sp| sp.has_segment(ai, out)))
}
fn set_anchors(s: &mut Session, p: &Value) -> Result<Value> {
let id = object_param(p, "id", "path.setAnchors")?.ok_or_else(|| bad("path.setAnchors", "missing id"))?;
let subs = p.get("subpaths").and_then(Value::as_array).ok_or_else(|| bad("path.setAnchors", "missing subpaths"))?;
+10 -3
View File
@@ -685,14 +685,21 @@ fn pf_label(op: PathfinderOp) -> &'static str {
}
}
/// The Pathfinder Options an operation uses: those `p` gives, else the preferences'. They join the
/// command's journal entry, so replaying it gives the same result whatever the preferences are then.
fn pf_options(s: &mut Session, p: &Value, id: &str) -> Result<PathfinderOptions> {
/// The Pathfinder Options in the preferences, as the panel's operations and a new Pathfinder effect
/// take them.
pub(crate) fn current_pf_options(s: &Session) -> PathfinderOptions {
let mut stored = s.prefs.pathfinder;
if !PATHFINDER_PRECISION_RANGE.contains(&stored.precision) {
// A preferences file edited by hand: the default, rather than refitting everything away.
stored.precision = po::DEFAULT_PRECISION;
}
stored
}
/// The Pathfinder Options an operation uses: those `p` gives, else the preferences'. They join the
/// command's journal entry, so replaying it gives the same result whatever the preferences are then.
fn pf_options(s: &mut Session, p: &Value, id: &str) -> Result<PathfinderOptions> {
let stored = current_pf_options(s);
let keys = ["precision", "removeRedundantPoints", "removeUnpainted"];
let given: serde_json::Map<String, Value> =
p.as_object().into_iter().flatten().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
+114 -1
View File
@@ -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<CommandSpec> {
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<NodeId> {
@@ -412,6 +428,103 @@ pub(crate) fn finish_edit(d: &mut Document, sel: &mut Selection) -> Result<Strin
Ok(pe.pattern)
}
/// Give pattern `name` fresh-id copies of the selected art (or of `ids`) as its tile art, as one
/// undo step (`object.pattern.replaceArt`). The pattern keeps its name, swatch, tile and options,
/// and its tile fits the new art when its Size Tile to Art is on; paints refer to a pattern by
/// name, so every fill and stroke of it draws the new tile. The art stays where it is, selected as
/// before. Art that matches the tile art already records nothing.
fn pattern_replace_art(s: &mut Session, p: &Value) -> Result<Value> {
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<Arc<Node>> = 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<Node>]| 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<Arc<Node>> = 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<Node>], 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<Uses> = 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
+31 -14
View File
@@ -630,19 +630,7 @@ fn at_param(p: &Value) -> Result<Option<Point>> {
/// `image_xf`), also for an image alone in a clip group when the new art is an image, clipped by
/// its file's clipping path or not (`new_image`); other objects keep their centre.
fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image: bool) -> Affine {
// An image alone in a clip group (as a PSD or PSB file's clipping path places it,
// [`fileio::file_clipped`]) is measured as the image when the new art is an image; a DCS
// file's plates are not.
let image = match &old.kind {
NodeKind::Group { children, clip: true } if new_image => match &children[..] {
[path, image] if matches!(path.kind, NodeKind::Path { clipping: true, .. }) => match &image.kind {
NodeKind::Image(im) if d.images.get(&im.key).is_none_or(|b| b.separated().is_none()) => image,
_ => old,
},
_ => old,
},
_ => old,
};
let image = replace_measured(d, old, new_image);
if image_xf && let NodeKind::Image(im) = &image.kind {
let (sx, sy) = pt_per_px(d.images.get(&im.key).and_then(|b| fileio::ppi::resolution(&b.bytes)));
let full = Affine::scale_non_uniform(sx, sy);
@@ -655,6 +643,22 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image
Affine::translate(c - natural.center())
}
/// The object [`replace_xf`] measures when Replace swaps `old`: an image alone in a clip group (as
/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is an
/// image (`new_image`), except a DCS file's plates; else `old` itself.
fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Node {
match &old.kind {
NodeKind::Group { children, clip: true } if new_image => match &children[..] {
[path, image] if matches!(path.kind, NodeKind::Path { clipping: true, .. }) => match &image.kind {
NodeKind::Image(im) if d.images.get(&im.key).is_none_or(|b| b.separated().is_none()) => image,
_ => old,
},
_ => old,
},
_ => old,
}
}
/// `rect` fitted with `natural`'s aspect, centred.
fn fit(natural: Rect, r: Rect) -> Affine {
let ratio = |a: f64, b: f64| (b > 1e-9).then(|| a / b);
@@ -814,6 +818,17 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
loaded.natural = Rect::from_origin_size(Point::ORIGIN, size);
}
let natural = loaded.natural;
// Replace keeps the transform of the image it measures (`replace_measured`), which a
// distortion's corners do not follow. Type, and any other object it measures, is placed by the
// bounds of what it replaces, so a distorted image there is not refused.
if let Some(o) = old_node
&& !is_text
{
let image = replace_measured(&st.doc, o, matches!(loaded.art, Art::Image(..)));
if image.is_distorted_image() {
return Err(super::xform::distorted_image_error(PLACE, image.id));
}
}
let m = match (old_node, rect) {
(Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, matches!(loaded.art, Art::Image(..))),
(None, Some(r)) => fit(natural, r),
@@ -1173,6 +1188,8 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
let doc = super::links::with_brush_art(&st.doc);
let n = doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?;
let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) };
// Effective resolution, taken at the middle of a distorted image.
let ppi = effective_ppi(vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf));
let size = n.geometric_bounds().unwrap_or_default();
// A linked file outside the read roots of the caller asking now is left unnamed, as in Link Info.
let doc_path = super::links::LinkBase::of(st).doc;
@@ -1184,7 +1201,7 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result<Value> {
"colorMode": st.doc.images.get(&im.key).map_or("RGB", |b| color_mode(&b.bytes)),
"pixelWidth": im.width,
"pixelHeight": im.height,
"ppi": effective_ppi(im.xf),
"ppi": ppi,
"width": size.width(),
"height": size.height(),
}))
@@ -363,6 +363,7 @@ pub(super) const ALLOWED: &[&str] = &[
"object.pattern.done",
"object.pattern.edit",
"object.pattern.make",
"object.pattern.replaceArt",
"object.puppetWarp",
"object.puppetWarp.pins",
"object.rasterize",
@@ -571,6 +572,7 @@ pub(super) const ALLOWED: &[&str] = &[
"shape.rectangularGrid",
"shape.spiral",
"shape.star",
"shape.threePointArc",
"shapeBuilder.merge",
"shapeBuilder.regions",
"shaper.expand",
+7
View File
@@ -752,6 +752,13 @@ impl Session {
t.set_option("cornerRadius", &r);
}
}
// A press of the tool that is dropped keeps the new radius, also when the tool lent a
// selection tool for the press.
if self.press_taken_by("roundedRectangle")
&& let Some((_, saved)) = self.press_options.as_mut()
{
saved.insert("cornerRadius".into(), r);
}
}
if fonts_folder_changed {
let folder = self.prefs.fonts_folder.trim();
+4
View File
@@ -455,6 +455,10 @@ fn places(map: Affine) -> bool {
/// member).
pub(crate) fn replace_with_image(mut v: Node, image: Node) -> Node {
if !v.is_layer() {
// The new pixels already show a distorted image's distortion.
if let Some(e) = v.extras_if_any() {
e.image_quad = None;
}
return Node { kind: image.kind, appearance: Default::default(), ..v };
}
v.appearance = Default::default();
+24 -10
View File
@@ -130,7 +130,8 @@ type Region = (vectorcraft_geom::BezPath, vectorcraft_geom::FillRule);
#[derive(Clone)]
struct ImageRead<'a> {
blob: &'a vectorcraft_doc::ImageBlob,
xf: vectorcraft_geom::Affine,
/// Pixel space to the page: the image's transform, or a distorted image's projective map.
map: vectorcraft_geom::Homography,
size: (f64, f64),
area: Option<Rect>,
clip: Option<Vec<Region>>,
@@ -261,9 +262,9 @@ impl<'a> Theme<'a> {
let keeps: Vec<Box<dyn Fn(f64, f64) -> bool + '_>> = group
.iter()
.map(|r| {
let (xf, (w, h), area, clip, cost, tested) = (r.xf, r.size, r.area, &r.clip, elements(r), &tested);
let (map, (w, h), area, clip, cost, tested) = (r.map, r.size, r.area, &r.clip, elements(r), &tested);
Box::new(move |u: f64, v: f64| {
let p = xf * Point::new(u * w, v * h);
let Some(p) = map.apply(Point::new(u * w, v * h)) else { return false };
area.is_none_or(|a| a.contains(p))
&& clip.as_ref().is_none_or(|rs| {
tested.set(tested.get().saturating_add(cost));
@@ -278,7 +279,7 @@ impl<'a> Theme<'a> {
.map(|(r, keep)| {
use vectorcraft_geom::kurbo::Shape;
let (w, h) = r.size;
let inv = r.xf.inverse();
let inv = r.map.inverse();
// The box sampled: the marquee, cut to the clipping paths' bounds, so a small
// region a clip shows of a large image is still sampled densely.
let clip_box = r.clip.as_ref().map(|rs| rs.iter().map(|(bp, _)| bp.bounding_box()).reduce(|a, b| a.union(b)).unwrap_or_default());
@@ -286,12 +287,16 @@ impl<'a> Theme<'a> {
(Some(a), Some(c)) => Some(a.intersect(c)),
(a, c) => a.or(c),
};
let box_uv = region.map(|a| {
let uv: Vec<Point> =
[(a.x0, a.y0), (a.x1, a.y0), (a.x0, a.y1), (a.x1, a.y1)].into_iter().map(|(x, y)| inv * Point::new(x, y)).collect();
// A region that crosses a distorted image's horizon has no box: the whole
// image is sampled, and `keep` tests each pixel.
let box_uv = region.zip(inv).and_then(|(a, inv)| {
let uv: Vec<Point> = [(a.x0, a.y0), (a.x1, a.y0), (a.x0, a.y1), (a.x1, a.y1)]
.into_iter()
.map(|(x, y)| inv.apply(Point::new(x, y)))
.collect::<Option<_>>()?;
let low = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::INFINITY, f64::min);
let high = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::NEG_INFINITY, f64::max);
[low(|p| p.x) / w, low(|p| p.y) / h, high(|p| p.x) / w, high(|p| p.y) / h]
Some([low(|p| p.x) / w, low(|p| p.y) / h, high(|p| p.x) / w, high(|p| p.y) / h])
});
(box_uv, if r.clip.is_some() { clipped } else { budget }, keep.as_ref())
})
@@ -401,7 +406,9 @@ impl<'a> Theme<'a> {
None
};
let size = (f64::from(im.width.max(1)), f64::from(im.height.max(1)));
self.queue_image(ImageRead { blob, xf: im.xf, size, area, clip: self.clip.clone(), colorize });
// A distorted image's pixels are where its projective map puts them.
let map = n.image_map().unwrap_or_else(|| vectorcraft_geom::Homography::from_affine(im.xf));
self.queue_image(ImageRead { blob, map, size, area, clip: self.clip.clone(), colorize });
return;
}
NodeKind::SymbolInstance { symbol, xf } => {
@@ -2051,7 +2058,14 @@ mod tests {
bp.line_to((size, size));
bp.line_to((0.0, size));
bp.close_path();
ImageRead { blob, xf: Affine::IDENTITY, size: (size, size), area: None, clip: Some(vec![(bp, FillRule::NonZero)]), colorize: None }
ImageRead {
blob,
map: vectorcraft_geom::Homography::from_affine(Affine::IDENTITY),
size: (size, size),
area: None,
clip: Some(vec![(bp, FillRule::NonZero)]),
colorize: None,
}
}
/// The reads of one image inside clip groups share the work limit: three reads of a 64 px
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke Options",
["Window", "Stroke"],
None,
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path}} (a custom head with its art, as document.inspect reports one; refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}",
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}",
has_doc,
stroke_set
),
+32 -9
View File
@@ -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<CommandSpec> {
"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<Value> {
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<Color> {
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<ColorKey> = 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<Value> {
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<Vec<NodeId>> {
let ids: Vec<NodeId> = 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<ColorKey> = 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<Value> {
}
let linked = if global { link_colors(d, &ids, &links) } else { 0 };
Ok((links.into_iter().map(|(_, n)| n).collect::<Vec<_>>(), linked))
})?;
});
s.doc_mut()?.global_edit = global_edit;
let (added, linked) = edited?;
Ok(json!({"added": added, "linked": linked}))
}
+6 -2
View File
@@ -122,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Type Path Handle",
[],
None,
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change",
"{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner; symmetric: mirror the other handle about the anchor without changing its kind, except at an open end of the path; independent and symmetric cannot both be true; both default false); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change",
has_doc,
set_path_handle
),
@@ -1449,6 +1449,10 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
let out = super::object::choice(p, C, "which", &["in", "out"])? != Some("in");
let pos = vectorcraft_geom::Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?);
let independent = switch_or(p, "independent", false, C)?;
let symmetric = switch_or(p, "symmetric", false, C)?;
if symmetric && independent {
return Err(bad(C, "`independent` and `symmetric` cannot both be true"));
}
let node = s.doc()?.doc.node(id);
let on_path = matches!(node.map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. }));
if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) {
@@ -1461,7 +1465,7 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
let within = |t: &TextObject| {
t.type_path().and_then(|p| p.bounds()).is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= crate::MAX_COORD))
};
if !(t.set_path_handle((si, ai), out, pos, independent) && within(t)) {
if !(t.set_path_handle_with_symmetry((si, ai), out, pos, independent, symmetric) && within(t)) {
t.kind = before;
return Err(bad(C, "no such path anchor, or the path would reach past the canvas"));
}
+124 -1
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Free Distort",
[],
None,
"{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step",
"{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; an image's four corners go exactly where the warp takes them and its pixels are drawn in perspective between them (an error, and nothing changes, when an image's corners would fold over, fall on one line, cross the warp's horizon or lie too close together for a perspective map); a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step",
has_doc,
distort
),
@@ -86,6 +86,15 @@ impl Projective {
Self { m: [a, b, p0.x, d, e, p0.y, g, h], src, pre: bx.to_doc().inverse() }
}
/// Whether `p` maps in front of the warp's horizon, on the side the box's own corners are.
fn in_front(&self, p: Point) -> bool {
let [.., g, h] = self.m;
let p = self.pre * p;
let u = if self.src.width().abs() > 1e-12 { (p.x - self.src.x0) / self.src.width() } else { 0.0 };
let v = if self.src.height().abs() > 1e-12 { (p.y - self.src.y0) / self.src.height() } else { 0.0 };
g * u + h * v + 1.0 > 1e-9
}
pub fn apply(&self, p: Point) -> Point {
let [a, b, c, d, e, f, g, h] = self.m;
let p = self.pre * p;
@@ -138,6 +147,15 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option<Rect> {
// A clip group is bounded by its clip path.
NodeKind::Group { children, clip: true } => warp_children(children, pr, |i| i == 0),
NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => warp_children(children, pr, |i| i >= skip),
// An image's corners follow the warp exactly ([`Node::set_image_corners`]); [`distort`]
// has checked that they stay convex.
NodeKind::Image(_) => {
let b = n.geometric_bounds();
if let Some(q) = n.image_corners() {
let _ = n.set_image_corners(q.map(|p| pr.apply(p)));
}
b
}
_ => {
// No editable points: the affine approximation (which maps the gradients too).
let b = n.geometric_bounds();
@@ -157,6 +175,21 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option<Rect> {
before
}
/// Whether the warp from `src` to `q` ([`Projective::from_box`]) takes the corners of `src` to `q`,
/// within a millionth of `q`'s shortest side plus the rounding error of coordinates as far from `q`'s
/// first corner as the others. The warp is solved and measured with `src` and `q` moved to the
/// origin, so coordinates far from it do not widen the allowance.
fn reaches_corners(src: OrientedBox, q: [Point; 4]) -> bool {
let origin = q[0].to_vec2();
let q = q.map(|p| p - origin);
let src = OrientedBox { rect: src.rect - src.rect.origin().to_vec2(), ..src };
let pr = Projective::from_box(src, q);
let side = (0..4).map(|i| q[i].distance(q[(i + 1) % 4])).fold(f64::INFINITY, f64::min);
let far = q.iter().map(|p| p.x.abs().max(p.y.abs())).fold(0.0, f64::max);
let tol = side * 1e-6 + far * 1e-12;
side.is_finite() && side > 0.0 && src.corners().iter().zip(q).all(|(c, want)| pr.apply(*c).distance(want) <= tol)
}
/// Warps each of `children` and returns the union of the pre-warp bounds of those `counts` picks
/// by index.
fn warp_children(children: &mut [Arc<Node>], pr: &Projective, counts: impl Fn(usize) -> bool) -> Option<Rect> {
@@ -166,6 +199,76 @@ fn warp_children(children: &mut [Arc<Node>], pr: &Projective, counts: impl Fn(us
})
}
/// The first image in `n` (its children and the art of linked opacity masks, as [`warp_node`]
/// reaches them) whose corners `pr` would fold, collapse or carry past the warp's horizon, with
/// why.
fn unwarpable_image(n: &Node, pr: &Projective) -> Option<(vectorcraft_doc::NodeId, Unwarpable)> {
if let (Some(q), NodeKind::Image(im)) = (n.image_corners(), &n.kind) {
if !q.iter().all(|p| pr.in_front(*p)) {
return Some((n.id, Unwarpable::Horizon));
}
if let Err(e) = vectorcraft_doc::image_quad::check_for(im, &q.map(|p| pr.apply(p))) {
return Some((
n.id,
match e {
vectorcraft_doc::image_quad::QuadError::NotFinite | vectorcraft_doc::image_quad::QuadError::NotConvex => Unwarpable::NotConvex,
vectorcraft_doc::image_quad::QuadError::TooNarrow => Unwarpable::TooNarrow,
},
));
}
}
warped_parts(n).into_iter().find_map(|c| unwarpable_image(c, pr))
}
/// The first image in `n` that [`warp_node`] reaches (its children and the art of linked opacity
/// masks).
fn first_image(n: &Node) -> Option<vectorcraft_doc::NodeId> {
if matches!(n.kind, NodeKind::Image(_)) {
return Some(n.id);
}
warped_parts(n).into_iter().find_map(first_image)
}
/// The objects inside `n` that [`warp_node`] warps point by point: the children of layers, groups
/// and compound paths, and the art of a linked opacity mask on those, paths and images. Other
/// objects (blends, envelopes, repeats and the rest) take the warp's affine approximation whole.
fn warped_parts(n: &Node) -> Vec<&Node> {
let inside = matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. });
let mask_too = inside || matches!(n.kind, NodeKind::Path { .. } | NodeKind::Image(_));
let children = n.children().filter(|_| inside).into_iter().flatten().map(|c| &**c);
let mask = n.extras().mask.as_deref().filter(|m| mask_too && m.linked).map(|m| &*m.art);
children.chain(mask).collect()
}
/// The error of `command` on image `id`, which is distorted (Perspective Distort or Free Distort)
/// in a way the command cannot keep.
pub(crate) fn distorted_image_error(command: &str, id: vectorcraft_doc::NodeId) -> EngineError {
bad(command, format!("object {} is an image changed by Perspective Distort or Free Distort, which this command does not work on", id.0))
}
/// Why an image cannot follow the corners of a distort.
#[derive(Clone, Copy)]
enum Unwarpable {
/// Its corners would fold over, meet or fall on one line.
NotConvex,
/// A corner would cross the warp's horizon.
Horizon,
/// Its corners would be too close together for a perspective map to place them.
TooNarrow,
}
/// The error of `object.distort` when image `id` cannot follow its corners.
fn unwarpable_error(id: vectorcraft_doc::NodeId, why: Unwarpable) -> EngineError {
const C: &str = "object.distort";
match why {
Unwarpable::NotConvex => bad(C, format!("image {} cannot be distorted this way: its corners would not make a convex shape", id.0)),
Unwarpable::Horizon => bad(C, format!("image {} cannot be distorted this way: its corners would cross the warp's horizon", id.0)),
Unwarpable::TooNarrow => {
bad(C, format!("image {} cannot be distorted this way: its corners would be too close together for a perspective map", id.0))
}
}
}
fn distort(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.distort";
// All four corners or nothing, each exactly [x, y]: nothing malformed is left out.
@@ -208,6 +311,26 @@ fn distort(s: &mut Session, p: &Value) -> Result<Value> {
return Ok(ids_json);
}
let pr = Projective::from_box(src, [tl, tr, br, bl]);
// An image's corners follow the handles exactly, so they must stay a convex shape: nothing
// changes when one would not.
let doc = &s.doc()?.doc;
// Corners that do not make a convex shape give no perspective map (the warp falls back to an
// affine one), so an image cannot follow them.
if vectorcraft_doc::image_quad::check(&[tl, tr, br, bl]).is_err()
&& let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image)
{
return Err(unwarpable_error(id, Unwarpable::NotConvex));
}
// Corners so close together that the map falls back to an affine one: the box's corners do
// not reach the handles, so an image cannot follow them either.
if !reaches_corners(src, [tl, tr, br, bl])
&& let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image)
{
return Err(unwarpable_error(id, Unwarpable::TooNarrow));
}
if let Some((id, why)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(|n| unwarpable_image(n, &pr)) {
return Err(unwarpable_error(id, why));
}
s.edit("Free Distort", |d, _| {
for id in &ids {
if let Some(n) = d.node_mut(*id) {
+1
View File
@@ -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",
+8
View File
@@ -191,6 +191,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<std::path::PathBuf>,
/// 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<std::path::PathBuf>,
/// 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`]).
@@ -326,6 +331,9 @@ pub struct Session {
/// The id and persistent options of the tool when the press under way began, which a dropped
/// press puts back ([`Session::drop_tool_press`]).
pub(crate) press_options: Option<(String, serde_json::Map<String, serde_json::Value>)>,
/// An option of the active tool was set during the press under way, which stored all of its
/// options, so a dropped press stores the options it puts back.
pub(crate) press_options_stored: bool,
/// The engine saves the selection and active layer before a Type press and restores them if it drops.
pub(crate) press_type_selection: Option<(Selection, Option<NodeId>)>,
/// The freeform gradient point selected once the tool took the press under way, which a
+2
View File
@@ -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",
+3
View File
@@ -100,6 +100,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,
@@ -136,6 +138,7 @@ impl Session {
plane_widget_press: false,
pointer_held: false,
press_options: None,
press_options_stored: false,
press_type_selection: None,
press_point: None,
ruler_guide: None,
+2
View File
@@ -203,12 +203,14 @@ mod symbol_nine_slice;
mod symbolbounds;
mod symboledit;
mod symbolism_options;
mod symbolism_shift;
mod symbollib;
mod tangent_line;
mod targeting;
mod textcombos;
mod textedit;
pub(super) mod textimport;
mod three_point_arc;
mod tileedge;
mod tints;
mod toolsettings;
+121 -1
View File
@@ -112,6 +112,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"calligraphic-nibs",
"pressure-sensitive",
"bristle-brushes",
"paint",
"pattern-borders",
"scatter-shapes",
"stipple",
@@ -119,8 +120,10 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"energy-beams",
"dry-media",
"tech-circuit",
"engraving",
"arrows",
"image-brush"
"image-brush",
"artistic"
]
);
assert!(libs.iter().all(|l| l["category"] == "builtIn"));
@@ -169,6 +172,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
("calligraphic-nibs", "calligraphic"),
("pressure-sensitive", "art"),
("bristle-brushes", "bristle"),
("paint", "art"),
("pattern-borders", "pattern"),
("scatter-shapes", "scatter"),
("stipple", "scatter"),
@@ -177,6 +181,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
("dry-media", "art"),
("arrows", "art"),
("image-brush", "scatter"),
("artistic", "art"),
] {
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
assert!(lib.len() >= 4, "{id}");
@@ -207,6 +212,46 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err());
}
#[test]
fn artistic_library_strokes_are_editable_and_reopen_from_a_saved_library() {
let mut s = session();
let (_, lib) = cmd::brushlib::library(&s, "artistic").unwrap();
let (_, alias) = cmd::brushlib::library(&s, "Artistic").unwrap();
assert_eq!(alias.brushes, lib.brushes);
assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], "artistic");
let names = ["Orbit Lines", "Petal Garland", "Lattice Braid", "Facet Sweep"];
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), names);
let line = run(&mut s, "shape.line", json!({"x1": 10, "y1": 50, "x2": 190, "y2": 50}))["id"].as_u64().unwrap();
let red = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)), 1.0);
for b in &lib.brushes {
let BrushKind::Art(a) = &b.kind else { panic!("{} is not an art brush", b.name) };
assert!(art_paths(&a.art).len() >= 2, "{} has no editable vector art", b.name);
for path in [line_to(180.0), line_to(1.0)] {
assert!(!vectorcraft_brush::stroke_pieces(&lib.doc, b, &path, &black_stroke()).is_empty(), "{} draws nothing", b.name);
}
// The art is black, so with Tints every path takes the stroke color itself.
let mut fills = vec![];
for piece in vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &red) {
piece.walk(&mut |n| {
if n.path_data().is_some() {
fills.push(n.appearance.fill_paint().color().map(|c| c.to_rgb()));
}
});
}
let is_red = |c: &Option<[f32; 3]>| c.is_some_and(|[r, g, b]| (r - 1.0).abs() < 1e-5 && g.abs() < 1e-5 && b.abs() < 1e-5);
assert!(!fills.is_empty() && fills.iter().all(is_red), "{} does not take the stroke color: {fills:?}", b.name);
let before = undo_len(&s);
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "artistic", "name": b.name, "apply": true, "ids": [line]}));
assert_eq!(strs(&added["added"]), [b.name.as_str()]);
assert_eq!(added["applied"], json!([line]));
assert_eq!(undo_len(&s), before + 1);
}
let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let reopened = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
#[test]
fn image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved() {
let mut s = session();
@@ -244,6 +289,26 @@ fn image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved() {
assert_eq!(reopened.images, lib.doc.images);
}
#[test]
fn a_loaded_library_named_artistic_keeps_its_name_ahead_of_the_builtin_alias() {
let mut file = vectorcraft_doc::Document::new(100.0, 100.0);
vectorcraft_brush::store(&mut file, &[vectorcraft_brush::defaults()[0].clone()]);
let b64 = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&file));
let mut s = session();
let loaded = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Artistic.vectorcraft"}));
assert_eq!(loaded["name"], "Artistic");
let id = loaded["library"].as_str().unwrap();
assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], id);
assert_eq!(run(&mut s, "brush.library", json!({"library": "ARTISTIC"}))["id"], id);
assert_eq!(run(&mut s, "brush.library", json!({"library": "artistic"}))["id"], "artistic", "exact built-in id still works");
// A name a built-in library has selects the built-in, as for every built-in; the loaded one keeps its id.
let full = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Artistic Brushes.vectorcraft"}));
assert_eq!(full["name"], "Artistic Brushes");
let full_id = full["library"].as_str().unwrap();
assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic Brushes"}))["id"], "artistic");
assert_eq!(run(&mut s, "brush.library", json!({"library": full_id}))["id"], full_id);
}
/// Every path of brush art `n`: (anchors, opacity).
fn art_paths(n: &vectorcraft_doc::Node) -> Vec<(usize, f32)> {
let mut out = vec![];
@@ -272,6 +337,30 @@ fn black_stroke() -> vectorcraft_doc::StrokeLayer {
vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0)
}
#[test]
fn engraving_library_draws_fine_parallel_strokes_and_survives_save() {
let mut s = session();
let listed = run(&mut s, "brush.libraries", json!({}));
let entry = listed["libraries"].as_array().unwrap().iter().find(|l| l["id"] == "engraving").unwrap();
assert_eq!((entry["name"].as_str(), entry["category"].as_str(), entry["count"].as_u64()), (Some("Engraving"), Some("builtIn"), Some(4)));
let (_, lib) = cmd::brushlib::library(&s, "Engraving").unwrap();
for b in &lib.brushes {
for length in [2.0, 200.0] {
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(length), &black_stroke());
let pts = anchors(&pieces.iter().collect::<Vec<_>>());
assert!(!pts.is_empty() && pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{} at {length} pt", b.name);
}
}
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 20, "x2": 210, "y2": 20}))["id"].as_u64().unwrap();
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "engraving", "name": "Fine Hatching", "apply": true, "ids": [path]}));
assert_eq!(strs(&added["added"]), ["Fine Hatching"]);
assert_eq!(added["applied"], json!([path]));
let saved = run(&mut s, "brush.saveLibrary", json!({"names": ["Fine Hatching"]}));
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let reopened = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(vectorcraft_brush::find(&reopened, "Fine Hatching").unwrap(), lib.brushes[0]);
}
#[test]
fn stipple_library_draws_dot_textures_and_survives_save() {
let mut s = session();
@@ -519,6 +608,37 @@ fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_librar
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
#[test]
fn paint_brushes_draw_distinct_marks_and_survive_a_saved_library() {
let mut s = session();
let (_, lib) = cmd::brushlib::library(&s, "Paint").unwrap();
let names = ["Flat Sweep", "Dry Drag", "Loaded Stroke", "Fan Sweep"];
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), 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::<Vec<_>>());
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]
+66 -1
View File
@@ -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", &params).is_err(), "{params}");
assert_eq!(s.paint.fill, fill, "{params}: the bucket's gradient stays");
}
assert_eq!((node(&s, g), node(&s, rect)), (group, art), "the selection keeps its paint");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step");
// Named objects take it.
s.execute("paint.editGradient", &json!({"stroke": false, "kind": "radial", "aspect": 50, "ids": [rect.0]})).unwrap();
assert_eq!(aspect(&node(&s, rect)), Some(0.5));
// Without the bucket and with nothing selected, the default gradient has no aspect either.
s.select_tool("selection", ViewInfo::default()).unwrap();
s.execute("select.set", &json!({"ids": []})).unwrap();
let fill = s.paint.fill.clone();
assert!(!s.gradient_edit_has_objects(false));
assert!(s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 50})).is_err());
assert_eq!(s.paint.fill, fill, "the default gradient stays");
// An empty group has nothing to paint.
let empty = s
.edit("Group", |d, _| {
let id = d.alloc_id();
d.insert(d.default_layer(), 0, Node::group(id, vec![]))?;
Ok(id)
})
.unwrap();
s.execute("select.set", &json!({"ids": [empty.0]})).unwrap();
assert!(!s.gradient_edit_has_objects(false), "an empty group");
assert!(s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 50})).is_err());
// A fill edit of a Live Paint group with edges and no faces edits no object; a stroke edit edits its edges.
let line = NodeId(s.execute("shape.line", &json!({"x1": 0, "y1": 0, "x2": 100, "y2": 0})).unwrap()["id"].as_u64().unwrap());
let edges_only = NodeId(s.execute("livePaint.make", &json!({"ids": [line.0]})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [edges_only.0]})).unwrap();
let (fill, group, steps) = (s.paint.fill.clone(), node(&s, edges_only), s.doc().unwrap().history.undo.len());
assert!(!s.gradient_edit_has_objects(false), "a Live Paint group without faces");
assert!(s.gradient_edit_has_objects(true), "its edges take a stroke edit");
assert!(s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 50})).is_err());
assert_eq!((&s.paint.fill, node(&s, edges_only)), (&fill, group), "the default and the group stay");
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no undo step");
// A selected object takes it.
s.execute("select.set", &json!({"ids": [rect.0]})).unwrap();
assert!(s.gradient_edit_has_objects(false) && s.gradient_edit_has_objects(true));
s.execute("paint.editGradient", &json!({"stroke": false, "aspect": 25})).unwrap();
assert_eq!(aspect(&node(&s, rect)), Some(0.25));
}
/// With the Live Paint Bucket active, objects named with `ids` still take a stroke, and a brush
/// still goes to the selection.
#[test]
@@ -9429,9 +9491,12 @@ fn image_trace_split_view_keeps_and_validates_its_divider() {
assert_eq!((back.node(g).unwrap().trace_view(), back.node(g).unwrap().trace_split()), (vectorcraft_doc::TraceView::Split, 0.25));
// Bad dividers are refused and change nothing.
let steps = s.doc().unwrap().history.undo.len();
for bad in [json!(-0.1), json!(1.01), json!("0.5"), json!(true), json!([0.5])] {
for bad in [json!(-0.1), json!(1.01), json!("0.5"), json!(true), json!([0.5]), json!(null)] {
assert!(s.execute("imageTrace.setView", &json!({"view": "split", "split": bad})).is_err(), "{bad}");
}
// A null divider with another view is refused too, and the view stays.
assert!(s.execute("imageTrace.setView", &json!({"view": "outlines", "split": null})).is_err());
assert_eq!(node(&s, g).trace_view(), vectorcraft_doc::TraceView::Split);
assert_eq!((s.doc().unwrap().history.undo.len(), node(&s, g).trace_split()), (steps, 0.25));
for edge in [0.0, 1.0] {
s.execute("imageTrace.setView", &json!({"view": "split", "split": edge})).unwrap();
+306
View File
@@ -318,6 +318,45 @@ fn convert_query_and_intents() {
assert!(s.execute("color.convert", &json!({"color": "#808080", "intent": "vivid"})).is_err());
}
/// `to: "oklch"` answers the OKLCH of the color's display sRGB, which converts back to the color;
/// a CMYK color's display color, not its naive separation, sets them.
#[test]
fn convert_to_oklch_answers_lightness_chroma_and_hue() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let mut s = session();
let r = s.execute("color.convert", &json!({"color": "#ff0000", "to": "oklch"})).unwrap();
assert_eq!(r["model"], "oklch");
let v: Vec<f64> = r["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
assert!((v[0] - 62.80).abs() < 0.005 && (v[1] - 0.2577).abs() < 5e-5 && (v[2] - 29.23).abs() < 0.005, "{r}");
let (rgb, lowered) = vectorcraft_color::oklab::from_oklch(v[0] / 100.0, v[1], v[2]);
assert!(!lowered);
assert_eq!(Color::rgb(rgb[0], rgb[1], rgb[2]).to_hex(), "#ff0000");
assert_eq!(r["hex"], "#ff0000");
let gray = s.execute("color.convert", &json!({"color": "#808080", "to": "oklch"})).unwrap();
assert_eq!(gray["values"][2], 0.0, "{gray}");
let ink = json!({"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0});
let cyan = s.execute("color.convert", &json!({"color": ink, "to": "oklch"})).unwrap();
let shown = vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&Color::cmyk(1.0, 0.0, 0.0, 0.0)));
let naive = vectorcraft_color::oklab::to_oklch([0.0, 1.0, 1.0]);
let c: Vec<f64> = cyan["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
let got = [c[0] / 100.0, c[1], c[2]];
assert!((0..3).all(|i| (got[i] - shown[i]).abs() < 1e-9) && shown[1] > 0.05, "{cyan} {shown:?}");
assert!((got[0] - naive[0]).abs() > 0.02, "{cyan} {naive:?}");
// A Lab color outside sRGB answers the OKLCH of its color clipped to sRGB.
let vivid = s.execute("color.convert", &json!({"color": {"l": 50.0, "a": 100.0, "b": 0.0}, "to": "oklch"})).unwrap();
let w: Vec<f64> = vivid["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
let shown = cms::active().display_rgb(&Color::lab(50.0, 100.0, 0.0)).map(|v| v.clamp(0.0, 1.0));
let clipped = vectorcraft_color::oklab::to_oklch(shown);
assert!((w[0] / 100.0 - clipped[0]).abs() < 1e-9 && (w[1] - clipped[1]).abs() < 1e-9, "{vivid} {clipped:?}");
assert!((w[2] - clipped[2]).abs() < 1e-9 && (0.0..360.0).contains(&w[2]), "{vivid} {clipped:?}");
assert!(vectorcraft_color::oklab::in_srgb(vectorcraft_color::oklab::oklch_to_srgb(w[0] / 100.0, w[1], w[2])), "{vivid}");
// RGB numbers past 0..1 answer the OKLCH of the clipped color `hex` reports: white.
let past = s.execute("color.convert", &json!({"color": [2.0, 2.0, 2.0], "to": "oklch"})).unwrap();
assert_eq!(past["hex"], "#ffffff");
let l = past["values"][0].as_f64().unwrap();
assert!((l - 100.0).abs() < 0.01 && past["values"][1].as_f64().unwrap() < 1e-3, "{past}");
}
#[test]
fn assign_profile_is_stored_and_undoable() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
@@ -682,6 +721,273 @@ fn proof_setup_simulates_tritanopia() {
s.execute("view.proofSetup", &json!({"target": "workingCmyk", "proof": false})).unwrap();
}
/// View › Proof Setup › Customize's settings: an RGB profile as the device, Preserve Numbers and
/// Simulate Black Ink, kept in the proof view, read back and drawn; bad values are refused and
/// leave the view as it was.
#[test]
fn proof_setup_takes_the_custom_proof_settings() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let _v = DefaultView::new();
let mut s = session();
rect(&mut s, 0.0, 0.0, 100.0, 100.0, json!("#000000"));
let r = s.execute("view.proofSetup", &json!({})).unwrap();
assert_eq!((r["preserveNumbers"].as_bool(), r["simulateBlack"].as_bool()), (Some(false), Some(false)));
let device = format!("cmyk:{}", cms::GENERIC_CMYK);
let r = s.execute("view.proofSetup", &json!({"target": device, "simulateBlack": true, "proof": true})).unwrap();
assert_eq!((r["target"].as_str(), r["simulateBlack"].as_bool(), r["proofColors"].as_bool()), (Some(device.as_str()), Some(true), Some(true)));
let setup = vectorcraft_render::proof::active_proof().unwrap();
assert!(setup.simulate_black && !setup.preserve_numbers);
let doc = s.doc().unwrap().doc.clone();
let gray = render(&doc, RenderOptions { proof: Some(setup.clone()), ..Default::default() }).pixel(50, 50);
let black = render(&doc, RenderOptions { proof: Some(ProofSetup { simulate_black: false, ..setup }), ..Default::default() }).pixel(50, 50);
assert!(gray[0] > black[0] + 10, "the press black shows as a gray: {gray:?} vs {black:?}");
let rgb = format!("rgb:{}", cms::DISPLAY_P3);
let r = s.execute("view.proofSetup", &json!({"target": rgb, "preserveNumbers": true})).unwrap();
assert_eq!((r["target"].as_str(), r["preserveNumbers"].as_bool()), (Some(rgb.as_str()), Some(true)));
assert_eq!(vectorcraft_render::proof::view().setup.target, ProofTarget::Rgb(cms::DISPLAY_P3.into()));
// Unchanged settings leave the revision alone.
let rev = s.doc().unwrap().revision;
s.execute("view.proofSetup", &json!({"target": rgb, "preserveNumbers": true, "simulateBlack": true})).unwrap();
assert_eq!(s.doc().unwrap().revision, rev);
let view = vectorcraft_render::proof::view();
refused(&mut s, "view.proofSetup", json!({"target": "rgb:Nope"}), "unknown RGB profile `Nope`");
refused(&mut s, "view.proofSetup", json!({"target": format!("rgb:{}", cms::GENERIC_CMYK)}), "unknown RGB profile");
refused(&mut s, "view.proofSetup", json!({"target": "rgb:"}), "unknown RGB profile");
refused(&mut s, "view.proofSetup", json!({"target": "workingCmyk", "preserveNumbers": "yes"}), "`preserveNumbers` must be true or false");
refused(&mut s, "view.proofSetup", json!({"simulateBlack": 1}), "`simulateBlack` must be true or false");
assert_eq!(vectorcraft_render::proof::view(), view, "the proof view is unchanged");
assert_eq!(s.doc().unwrap().revision, rev, "nothing redraws");
}
/// A custom proof setup saved to a file loads back as the same setup with Proof Colors on; saving
/// leaves the proof view as it is, and `view.proofSetup.read` only reads the file.
#[test]
fn a_saved_proof_setup_loads_back() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let _v = DefaultView::new();
let dir = vectorcraft_testkit::TempDir::new("proof-setup-file");
let path = dir.join("press.vcproof").to_string_lossy().to_string();
let mut s = session();
let device = format!("cmyk:{}", cms::GENERIC_CMYK);
let r = s
.execute(
"view.proofSetup.save",
&json!({"path": path, "target": device, "intent": "perceptual", "preserveNumbers": true, "simulateBlack": true}),
)
.unwrap();
assert_eq!((r["path"].as_str(), r["target"].as_str(), r["intent"].as_str()), (Some(path.as_str()), Some(device.as_str()), Some("perceptual")));
assert_eq!(vectorcraft_render::proof::view(), Default::default(), "saving leaves the proof view alone");
let text = std::fs::read_to_string(&path).unwrap();
assert!(text.contains("\"format\": \"vectorcraft-proof-setup\"") && text.contains("\"version\": 1"), "{text}");
let r = s.execute("view.proofSetup.read", &json!({"path": path})).unwrap();
assert_eq!((r["target"].as_str(), r["preserveNumbers"].as_bool(), r["simulateBlack"].as_bool()), (Some(device.as_str()), Some(true), Some(true)));
assert_eq!(vectorcraft_render::proof::view(), Default::default(), "reading changes nothing");
assert!(!crate::waits_for_tool_edit("view.proofSetup.read"), "reading does not finish a tool's edit");
let rev = s.doc().unwrap().revision;
let r = s.execute("view.proofSetup.load", &json!({"path": path})).unwrap();
assert_eq!((r["proofColors"].as_bool(), r["path"].as_str()), (Some(true), Some(path.as_str())));
let v = vectorcraft_render::proof::view();
assert!(v.proof_colors);
let want = ProofSetup {
target: ProofTarget::Cmyk(cms::GENERIC_CMYK.into()),
intent: Intent::Perceptual,
simulate_paper: false,
preserve_numbers: true,
simulate_black: true,
..Default::default()
};
assert_eq!(v.setup, want);
assert!(s.doc().unwrap().revision > rev, "the canvas redraws");
// Saved from the current setup, the file holds that setup: the round trip keeps every field.
let again = dir.join("again.vcproof").to_string_lossy().to_string();
s.execute("view.proofSetup.save", &json!({"path": again, "simulatePaper": true})).unwrap();
s.execute("view.proofSetup", &json!({"target": "workingCmyk"})).unwrap();
s.execute("view.proofSetup.load", &json!({"path": again})).unwrap();
assert_eq!(vectorcraft_render::proof::view().setup, ProofSetup { simulate_paper: true, ..want });
}
/// Saving refuses a target that is not a device, bad params, a bad name and a file larger than
/// loading reads; loading refuses a file
/// that is too large, not a proof setup, newer, or whose device is a profile that is not loaded,
/// and the proof view stays as it was.
#[test]
fn proof_setup_files_refuse_what_they_cannot_use() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let _v = DefaultView::new();
let dir = vectorcraft_testkit::TempDir::new("proof-setup-refused");
let file = |n: &str| dir.join(n).to_string_lossy().to_string();
let mut s = session();
let path = file("a.vcproof");
refused(&mut s, "view.proofSetup.save", json!({"path": path, "target": "protanopia"}), "`protanopia` is not a device to simulate");
refused(&mut s, "view.proofSetup.save", json!({"path": path, "target": "rgb:Nope"}), "unknown RGB profile `Nope`");
refused(&mut s, "view.proofSetup.save", json!({"path": path, "simulateBlack": "yes"}), "`simulateBlack` must be true or false");
refused(&mut s, "view.proofSetup.save", json!({}), "missing `path` or `name`");
refused(&mut s, "view.proofSetup.save", json!({"path": path, "name": "x"}), "not both");
refused(&mut s, "view.proofSetup.save", json!({"path": " "}), "`path` is empty");
refused(&mut s, "view.proofSetup.save", json!({"name": "x"}), "need the preferences folder");
assert!(!std::path::Path::new(&path).exists(), "nothing is written");
s.attach_proof_setups(dir.join("Proof Setups"));
for bad_name in ["", " ", "../up", "a/b", "a\\b", ".hidden", "c:d"] {
refused(&mut s, "view.proofSetup.save", json!({"name": bad_name}), "`name`");
}
refused(&mut s, "view.proofSetup.save", json!({"name": "x".repeat(101)}), "longer than 100 characters");
// A device whose name makes the file larger than load reads is refused, and nothing is written.
let long = "Long Profile Name ".repeat(4000);
cms::register_icc(&cms::icc_bytes(cms::DISPLAY_P3).unwrap(), Some(long.clone())).unwrap();
let refusal = s.execute("view.proofSetup.save", &json!({"path": path, "target": format!("rgb:{long}")}));
cms::unregister_icc(&long);
assert!(refusal.unwrap_err().to_string().contains("larger than 65536 bytes"), "a setup load can't read is refused");
assert!(!std::path::Path::new(&path).exists(), "nothing is written");
let before = vectorcraft_render::proof::view();
let write = |n: &str, text: &str| {
let p = file(n);
std::fs::write(&p, text).unwrap();
p
};
let ok = r#"{"format": "vectorcraft-proof-setup", "version": 1, "target": "workingCmyk", "intent": "relative"}"#;
let cases = [
(write("big.vcproof", &format!("{ok}{}", " ".repeat(64 << 10))), "larger than 65536 bytes"),
(write("junk.vcproof", "not json"), "not a proof setup file"),
(write("other.vcproof", r#"{"format": "other", "version": 1}"#), "not a VectorCraft proof setup file"),
(write("newer.vcproof", &ok.replace("\"version\": 1", "\"version\": 2")), "made by a newer VectorCraft"),
(write("missing.vcproof", &ok.replace("workingCmyk", "cmyk:Not Loaded")), "the CMYK profile `Not Loaded`, which is not loaded"),
(write("blind.vcproof", &ok.replace("workingCmyk", "deuteranopia")), "not a device to simulate"),
(write("intent.vcproof", &ok.replace("relative", "vivid")), "unknown intent `vivid`"),
(write("flag.vcproof", &ok.replace("}", r#", "simulatePaper": 1}"#)), "`simulatePaper` must be true or false"),
];
for (p, msg) in cases {
for cmd in ["view.proofSetup.load", "view.proofSetup.read"] {
refused(&mut s, cmd, json!({"path": p}), msg);
}
}
refused(&mut s, "view.proofSetup.load", json!({"path": file("gone.vcproof")}), "gone.vcproof");
assert_eq!(vectorcraft_render::proof::view(), before, "the proof view is unchanged");
// A file of the limit's size is read.
let padded = format!("{ok}{}", " ".repeat((64 << 10) - ok.len()));
s.execute("view.proofSetup.load", &json!({"path": write("limit.vcproof", &padded)})).unwrap();
}
/// Setups saved by name go in the Proof Setups folder, made on the first save, and are listed by
/// name; other files there are left out, and a run without the folder lists none.
#[test]
fn proof_setups_saved_by_name_are_listed() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let _v = DefaultView::new();
let mut s = session();
assert_eq!(s.execute("view.proofSetup.list", &json!({})).unwrap(), json!({"folder": null, "setups": [], "truncated": false}));
let dir = vectorcraft_testkit::TempDir::new("proof-setup-list");
let folder = dir.join("Proof Setups");
s.attach_proof_setups(folder.clone());
let r = s.execute("view.proofSetup.list", &json!({})).unwrap();
assert_eq!(r["setups"], json!([]), "no folder yet: none saved");
let r = s.execute("view.proofSetup.save", &json!({"name": " Coated Press ", "target": format!("rgb:{}", cms::DISPLAY_P3)})).unwrap();
let saved = folder.join("Coated Press.vcproof");
assert_eq!(r["path"].as_str(), Some(saved.to_string_lossy().as_ref()));
s.execute("view.proofSetup.save", &json!({"name": "Bright"})).unwrap();
std::fs::write(folder.join("notes.txt"), "x").unwrap();
std::fs::create_dir(folder.join("Sub.vcproof")).unwrap();
let r = s.execute("view.proofSetup.list", &json!({})).unwrap();
let names: Vec<&str> = r["setups"].as_array().unwrap().iter().filter_map(|e| e["name"].as_str()).collect();
assert_eq!(names, ["Bright", "Coated Press"]);
assert_eq!(r["truncated"], false);
s.execute("view.proofSetup.load", &json!({"name": "Coated Press"})).unwrap();
assert_eq!(vectorcraft_render::proof::view().setup.target, ProofTarget::Rgb(cms::DISPLAY_P3.into()));
for i in 0..101 {
std::fs::write(folder.join(format!("z{i:03}.vcproof")), "x").unwrap();
}
let r = s.execute("view.proofSetup.list", &json!({})).unwrap();
assert_eq!((r["setups"].as_array().unwrap().len(), r["truncated"].as_bool()), (100, Some(true)));
assert_eq!((r["setups"][0]["name"].as_str(), r["setups"][99]["name"].as_str()), (Some("Bright"), Some("z097")), "the first 100 by name");
}
/// Other files in the Proof Setups folder, however many, do not keep its setups from the listing.
#[test]
fn proof_setups_are_listed_among_many_other_files() {
let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
let _v = DefaultView::new();
let mut s = session();
let dir = vectorcraft_testkit::TempDir::new("proof-setup-list-crowded");
let folder = dir.join("Proof Setups");
std::fs::create_dir_all(&folder).unwrap();
for i in 0..5000 {
std::fs::write(folder.join(format!("a{i:04}.txt")), "").unwrap();
}
s.attach_proof_setups(folder.clone());
s.execute("view.proofSetup.save", &json!({"name": "Press"})).unwrap();
let r = s.execute("view.proofSetup.list", &json!({})).unwrap();
assert_eq!((r["setups"].as_array().unwrap().len(), r["truncated"].as_bool()), (1, Some(false)));
assert_eq!(r["setups"][0]["name"], "Press");
}
/// The listing names only files that `name` loads (`<name>.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::<Vec<_>>();
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::<Vec<_>>())
};
// 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();
+21
View File
@@ -1002,6 +1002,27 @@ fn dcs_transparency_counts_a_transparent_dcs_image_over_another() {
assert!(marked(b), "the opaque image it overlaps");
}
/// Replace measures a DCS file's clipping group by its bounds, not by its plates' image, so a
/// distorted plate image does not stop an image replacing the group.
#[test]
fn replace_is_not_refused_for_a_dcs_group_whose_image_is_distorted() {
let dir = temp_dir("replace-distorted");
let path = write(&dir, "pic.eps", &two_plates());
let mut s = session();
let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap();
let group = r["ids"][0].clone();
let image = image_of(&s, &group).id;
let b = s.doc().unwrap().doc.node(image).unwrap().geometric_bounds().unwrap();
let (x0, y0, x1, y1) = (b.x0, b.y0, b.x1, b.y1);
let corners = json!([[x0 + 4.0, y0], [x1 - 4.0, y0], [x1, y1], [x0, y1]]);
s.execute("object.distort", &json!({ "ids": [image.0], "corners": corners })).unwrap();
assert!(s.doc().unwrap().doc.node(image).unwrap().is_distorted_image());
s.execute("select.set", &json!({ "ids": [group] })).unwrap();
let png = crate::tests_links::png(2, 2, [0, 0, 255]);
let out = s.execute("file.place", &json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&png)}));
assert!(out.is_ok(), "{out:?}");
}
#[test]
fn dcs_transparency_counts_characters_with_a_transparent_gradient() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop};
+75
View File
@@ -588,6 +588,81 @@ fn a_symbols_link_without_a_relative_path_follows_the_moved_file() {
assert_eq!(paths, [moved.clone(), moved], "the layers' link, then the symbol's");
}
/// Update Links gives a distorted image its file's new pixels between the same corners: its
/// Placement Options' fill and clip do not move or clip it. Its transform takes the new pixel size,
/// and Link Info measures its scale at its middle.
#[test]
fn update_links_keeps_a_distorted_images_corners() {
let dir = Folder::new("distorted-update");
let photo = dir.file("photo.png");
write(&photo, &png(20, 10, RED));
let mut s = session();
let id = place(&mut s, &photo);
s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.distort", &json!({"corners": [[240, 300], [260, 300], [300, 400], [200, 400]]})).unwrap();
let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap();
let before = corners(&s);
assert!(s.doc().unwrap().doc.node(id).unwrap().is_distorted_image());
// The far corner of the pixels as the transform alone places them.
let far = |s: &Session| {
let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("an image") };
im.xf * vectorcraft_geom::Point::new(f64::from(im.width), f64::from(im.height))
};
let far_before = far(&s);
// Link Info measures the scale where the effective resolution is measured: at the middle.
let scale_matches_ppi = |s: &mut Session| {
let info = s.execute("links.info", &json!({"id": id.0})).unwrap();
for i in 0..2 {
let (scale, ppi, eff) = (info["scale"][i].as_f64().unwrap(), info["ppi"][i].as_f64().unwrap(), info["effectivePpi"][i].as_f64().unwrap());
assert!((scale - ppi / eff * 100.0).abs() < 1e-6, "{info}");
}
};
scale_matches_ppi(&mut s);
// A copy in a symbol, distorted the same way, shows the same file.
let copy = place(&mut s, &photo);
s.execute("links.placementOptions", &json!({"ids": [copy.0], "preserve": "fill", "clip": true})).unwrap();
s.execute("select.set", &json!({"ids": [copy.0]})).unwrap();
s.execute("object.distort", &json!({"corners": [[240, 300], [260, 300], [300, 400], [200, 400]]})).unwrap();
s.execute("symbol.new", &json!({"name": "Mark", "ids": [copy.0]})).unwrap();
let in_symbol = |s: &Session| {
let mut out = vec![];
s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| {
if let NodeKind::Image(im) = &n.kind {
out.push((n.is_distorted_image(), (im.width, im.height)));
}
});
out
};
let symbol_corners = |s: &Session| {
let mut out = vec![];
s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| out.extend(n.image_corners()));
out
};
assert_eq!(in_symbol(&s), [(true, (20, 10))]);
let symbol_before = symbol_corners(&s);
assert_eq!(symbol_before.len(), 1);
write(&photo, &png(60, 20, BLUE));
let u = s.execute("links.update", &json!({})).unwrap();
assert_eq!(u["updated"].as_array().unwrap().len(), 2, "{u}");
let d = &s.doc().unwrap().doc;
let n = d.node(id).unwrap();
assert!(n.is_distorted_image());
assert_eq!(corners(&s), before);
let NodeKind::Image(im) = &n.kind else { panic!("an image") };
assert_eq!((im.width, im.height), (60, 20));
// The transform takes the new pixel size, so a placement by the transform keeps the old size.
assert!(far(&s).distance(far_before) < 1e-9, "{:?} vs {far_before:?}", far(&s));
let d = &s.doc().unwrap().doc;
assert!(!matches!(d.parent_of(id).and_then(|p| d.node(p)).map(|p| &p.kind), Some(NodeKind::Group { clip: true, .. })), "not clipped");
let mut clipped = false;
d.symbols[0].art.walk(&mut |n| clipped |= matches!(n.kind, NodeKind::Group { clip: true, .. }));
assert!(!clipped, "the symbol's image is not clipped");
assert_eq!(in_symbol(&s), [(true, (60, 20))]);
assert_eq!(symbol_corners(&s), symbol_before, "the symbol's image keeps its corners");
scale_matches_ppi(&mut s);
}
/// Update Links reads a changed file again for the images inside symbols, patterns and opacity
/// masks too: those showing the same content as an image in the layers, and those no object in the
/// layers shows. Each takes the file's place as its own Placement Options say, in one undo step,

Some files were not shown because too many files have changed in this diff Show More