Merge main into in-window menu access keys

This commit is contained in:
yoriswind committed 2026-11-18 22:30:44 -08:00
commit a346c381e4
1266 files changed
+200171 -12852

No files matched your search

+1
View File
@@ -129,6 +129,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-cap-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-center-hide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-center-show.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-circle-points.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a circle with three dots on its edge) | MIT OR Apache-2.0 | |
| `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | |
Generated
+234 -115
View File
@@ -146,13 +146,28 @@ version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
[[package]]
name = "alloc-no-stdlib"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
[[package]]
name = "alloc-stdlib"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
dependencies = [
"alloc-no-stdlib",
"alloc-no-stdlib 2.0.4",
]
[[package]]
name = "alloc-stdlib"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
dependencies = [
"alloc-no-stdlib 3.0.0",
]
[[package]]
@@ -217,7 +232,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"parking_lot",
"percent-encoding",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
"wl-clipboard-rs",
"x11rb",
]
@@ -596,9 +611,9 @@ version = "8.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
"brotli-decompressor",
"alloc-no-stdlib 2.0.4",
"alloc-stdlib 0.2.4",
"brotli-decompressor 5.0.3",
]
[[package]]
@@ -607,8 +622,18 @@ version = "5.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
"alloc-no-stdlib 2.0.4",
"alloc-stdlib 0.2.4",
]
[[package]]
name = "brotli-decompressor"
version = "6.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc031cd87c6529082b0b65c604e86af0ed7744841b17ccfe60b1e31fa606179e"
dependencies = [
"alloc-no-stdlib 3.0.0",
"alloc-stdlib 0.3.0",
]
[[package]]
@@ -976,7 +1001,7 @@ dependencies = [
[[package]]
name = "craft-affinity"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=228f6d0c50f1fdee4c5124603602993fc79d4c9d#228f6d0c50f1fdee4c5124603602993fc79d4c9d"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"crc32fast",
"flate2",
@@ -987,17 +1012,25 @@ dependencies = [
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e#8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"rayon",
]
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
[[package]]
name = "craft-dxf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e#8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"craft-codepage",
"encoding_rs",
@@ -1009,17 +1042,39 @@ dependencies = [
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3#23acc704933a9a5619a5cd1cddc9bb1fb5a9b2d3"
dependencies = [
"harfrust 0.13.3",
"kurbo 0.13.1",
"skrifa 0.47.0",
"thiserror 2.0.21",
"unicode-bidi",
"unicode-segmentation",
"windows-registry",
]
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
[[package]]
name = "craft-gif"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"gif",
]
[[package]]
name = "craft-gzip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b0d84cd15db39f2af9869cfb47b8b72cbeca3f20#b0d84cd15db39f2af9869cfb47b8b72cbeca3f20"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"flate2",
]
@@ -1027,7 +1082,7 @@ dependencies = [
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1050,12 +1105,17 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"craft-dds",
"craft-jpeg",
"craft-metadata",
"craft-tiff",
"crc32fast",
"exr",
"flate2",
"half",
"hayro-jpeg2000",
"image",
"image-webp",
"jpeg-encoder",
@@ -1064,33 +1124,55 @@ dependencies = [
"serde_json",
"thiserror 2.0.21",
"tiff",
"zune-core 0.5.3",
"zune-jpeg 0.5.15",
"zune-core",
"zune-jpeg",
"zune-jpegxl",
]
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-jxl"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"jixel",
"jxl-oxide",
"thiserror 2.0.21",
]
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"egui",
"serde",
"serde_json",
]
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"brotli-decompressor 6.3.2",
"chrono",
"craft-tiff",
"quick-xml 0.41.0",
"serde",
]
[[package]]
name = "craft-metafile"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"encoding_rs",
"image",
@@ -1098,10 +1180,20 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-mime"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"chrono",
"craft-codepage",
"encoding_rs",
]
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"hayro-interpret",
"hayro-syntax",
@@ -1109,10 +1201,18 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-plotter"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57#a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"craft-winprint-gdi",
"log",
@@ -1126,7 +1226,7 @@ dependencies = [
[[package]]
name = "craft-proof"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"log",
"miniz_oxide 0.9.1",
@@ -1134,10 +1234,19 @@ dependencies = [
"unicode-normalization",
]
[[package]]
name = "craft-ps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"flate2",
"kurbo 0.13.1",
]
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"encoding_rs",
"flate2",
@@ -1145,14 +1254,29 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-stream-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"fax",
"hayro-ccitt",
"hayro-jbig2",
"thiserror 2.0.21",
]
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2)",
"craft-image-codecs",
"craft-xml",
"data-url",
"flate2",
"kurbo 0.13.1",
"quick-xml 0.41.0",
"resvg 0.48.1",
"roxmltree 0.21.2",
"thiserror 2.0.21",
"usvg 0.48.1",
@@ -1163,7 +1287,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1172,7 +1296,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6#c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1193,7 +1317,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e98299546f5c5c3c22388d16507f8b5e61a5f280#e98299546f5c5c3c22388d16507f8b5e61a5f280"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"chrono",
"dunce",
@@ -1220,7 +1344,7 @@ dependencies = [
[[package]]
name = "craft-vectorcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b0d84cd15db39f2af9869cfb47b8b72cbeca3f20#b0d84cd15db39f2af9869cfb47b8b72cbeca3f20"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"flate2",
"serde",
@@ -1231,7 +1355,7 @@ dependencies = [
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=fd5e2feff6ea25bed371a99cc732b3968d621505#fd5e2feff6ea25bed371a99cc732b3968d621505"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"js-sys",
"serde_json",
@@ -1242,7 +1366,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"egui",
"objc2 0.6.5",
@@ -1253,7 +1377,7 @@ dependencies = [
[[package]]
name = "craft-winprint-gdi"
version = "0.1.0"
source = "git+https://github.com/storytold/winprint.rs?rev=417ac3c4d14d3da5485a99c7d5ce8f05664ec312#417ac3c4d14d3da5485a99c7d5ce8f05664ec312"
source = "git+https://github.com/storytold/winprint.rs?rev=64e7afd4d1483512385012c340ecaaaf0f3beb7f#64e7afd4d1483512385012c340ecaaaf0f3beb7f"
dependencies = [
"windows-sys 0.61.2",
]
@@ -1261,18 +1385,10 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6d620e971e820b517b11a99cad040ebac670e1e2#6d620e971e820b517b11a99cad040ebac670e1e2"
dependencies = [
"quick-xml 0.41.0",
"thiserror 2.0.21",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=e2dc681a3#e2dc681a3ad8a47038da2f11ddd2c5e1c0454991"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
@@ -1750,7 +1866,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -2143,16 +2259,6 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "gif"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae047235e33e2829703574b54fdec96bfbad892062d97fed2f76022287de61b"
dependencies = [
"color_quant",
"weezl 0.1.12",
]
[[package]]
name = "gif"
version = "0.14.2"
@@ -2386,7 +2492,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"brotli",
"hayro-postscript",
@@ -2395,7 +2501,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -2413,7 +2519,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -2431,12 +2537,12 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -2446,7 +2552,7 @@ dependencies = [
"rustc-hash 2.1.3",
"smallvec",
"stringprep",
"zune-jpeg 0.5.15",
"zune-jpeg",
]
[[package]]
@@ -2831,15 +2937,15 @@ dependencies = [
"bytemuck",
"byteorder-lite",
"color_quant",
"gif 0.14.2",
"gif",
"image-webp",
"moxcms",
"num-traits",
"png 0.18.1",
"qoi",
"tiff",
"zune-core 0.5.3",
"zune-jpeg 0.5.15",
"zune-core",
"zune-jpeg",
]
[[package]]
@@ -2929,6 +3035,12 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "jixel"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "278a75e12caacec34be774d62ad05e45fc0b6a52d1f4e9f7fbc0209ecdf794f3"
[[package]]
name = "jni"
version = "0.22.4"
@@ -3092,7 +3204,7 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e35d032bcec660647828527ff42c6f5776d2fd44b8357f9f6d9ac6dc07218e46"
dependencies = [
"brotli-decompressor",
"brotli-decompressor 5.0.3",
"jxl-bitstream",
"jxl-frame",
"jxl-grid",
@@ -3124,7 +3236,7 @@ version = "0.12.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d36c662923f47586880211f3bc7c0d83fb3a9b410d278c7bde93450748abeef3"
dependencies = [
"brotli-decompressor",
"brotli-decompressor 5.0.3",
"jxl-bitstream",
"jxl-color",
"jxl-frame",
@@ -3230,13 +3342,13 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb#9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"base64 0.22.1",
"bumpalo",
"flate2",
"float-cmp",
"gif 0.14.2",
"gif",
"image-webp",
"imagesize 0.14.0",
"indexmap",
@@ -3251,7 +3363,7 @@ dependencies = [
"tiny-skia-path 0.12.0",
"xmp-writer",
"yoke",
"zune-jpeg 0.5.15",
"zune-jpeg",
]
[[package]]
@@ -3339,7 +3451,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=481f66d287b2a06845f3667a19daf35f0fe958ed#481f66d287b2a06845f3667a19daf35f0fe958ed"
source = "git+https://github.com/storytold/craft-libs?rev=64b181977a0488e4d1e167bc5cc8cfededc2ed4b#64b181977a0488e4d1e167bc5cc8cfededc2ed4b"
dependencies = [
"arrayvec",
"kurbo 0.13.1",
@@ -4044,7 +4156,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -4566,7 +4678,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -4806,15 +4918,12 @@ version = "0.45.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8928798c0a55e03c9ca6c4c6846f76377427d2c1e1f7e6de3c06ae57942df43"
dependencies = [
"gif 0.13.3",
"image-webp",
"log",
"pico-args",
"rgb",
"svgtypes 0.15.3",
"tiny-skia 0.11.4",
"usvg 0.45.1",
"zune-jpeg 0.4.21",
]
[[package]]
@@ -4824,7 +4933,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd"
dependencies = [
"bytemuck",
"gif 0.14.2",
"gif",
"image-webp",
"log",
"pico-args",
@@ -4832,7 +4941,7 @@ dependencies = [
"svgtypes 0.16.1",
"tiny-skia 0.12.0",
"usvg 0.48.1",
"zune-jpeg 0.5.15",
"zune-jpeg",
]
[[package]]
@@ -4944,7 +5053,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5003,7 +5112,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5868,7 +5977,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.6",
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -5940,7 +6049,7 @@ dependencies = [
"half",
"quick-error 2.0.1",
"weezl 0.1.12",
"zune-jpeg 0.5.15",
"zune-jpeg",
]
[[package]]
@@ -6535,6 +6644,7 @@ dependencies = [
"webbrowser",
"windows",
"winit",
"winreg",
"winresource",
"winsafe",
"wl-clipboard-rs",
@@ -6547,8 +6657,8 @@ name = "vectorcraft-affinity"
version = "0.24.1"
dependencies = [
"craft-affinity",
"craft-image-codecs",
"crc32fast",
"image",
"proptest",
]
@@ -6576,6 +6686,8 @@ name = "vectorcraft-cad"
version = "0.24.1"
dependencies = [
"craft-dxf",
"craft-image-codecs",
"craft-plotter",
"image",
"kurbo 0.13.1",
"serde_json",
@@ -6628,7 +6740,9 @@ name = "vectorcraft-doc"
version = "0.24.1"
dependencies = [
"chrono",
"hayro-ccitt",
"craft-image-codecs",
"craft-stream-codecs",
"flate2",
"image",
"jpeg-encoder",
"kurbo 0.13.1",
@@ -6639,16 +6753,17 @@ dependencies = [
"tiff",
"vectorcraft-color",
"vectorcraft-geom 0.24.1",
"zune-jpeg 0.5.15",
"zune-jpeg",
]
[[package]]
name = "vectorcraft-effects"
version = "0.24.1"
dependencies = [
"craft-image-codecs",
"craft-svg",
"image",
"kurbo 0.13.1",
"resvg 0.48.1",
"serde_json",
"svgtypes 0.16.1",
"vectorcraft-color",
@@ -6669,11 +6784,15 @@ dependencies = [
"cfb",
"chrono",
"craft-docpath",
"craft-image-codecs",
"craft-jxl",
"craft-proof",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
"craft-stream-codecs",
"craft-xml",
"crc32fast",
"encoding_rs",
"flate2",
"hayro-jpeg2000",
"hayro-ccitt",
"heic-rs",
"image",
"jxl-color",
@@ -6690,6 +6809,7 @@ dependencies = [
"serde_json",
"skrifa 0.47.0",
"thiserror 2.0.21",
"tiff",
"vectorcraft-affinity",
"vectorcraft-apischema",
"vectorcraft-brush",
@@ -6709,10 +6829,11 @@ dependencies = [
"vectorcraft-svg",
"vectorcraft-testkit",
"vectorcraft-text",
"vectorcraft-three-d",
"vectorcraft-tools",
"vectorcraft-trace",
"wat",
"zune-core 0.5.3",
"zune-core",
"zune-jpegxl",
]
@@ -6721,11 +6842,13 @@ name = "vectorcraft-eps"
version = "0.24.1"
dependencies = [
"craft-eps",
"craft-image-codecs",
"craft-pdf",
"craft-ps",
"craft-stream-codecs",
"encoding_rs",
"fax",
"flate2",
"hayro-ccitt",
"image",
"kurbo 0.13.1",
"memchr",
@@ -6799,6 +6922,7 @@ dependencies = [
name = "vectorcraft-mcp"
version = "0.24.1"
dependencies = [
"craft-image-codecs",
"image",
"log",
"proptest",
@@ -6818,6 +6942,7 @@ dependencies = [
name = "vectorcraft-metafile"
version = "0.24.1"
dependencies = [
"craft-image-codecs",
"craft-metafile",
"image",
"kurbo 0.13.1",
@@ -6858,8 +6983,10 @@ version = "0.24.1"
dependencies = [
"aes",
"chrono",
"craft-image-codecs",
"craft-pdf",
"craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)",
"craft-stream-codecs",
"craft-xml",
"flate2",
"getrandom 0.4.3",
"image",
@@ -6884,15 +7011,14 @@ dependencies = [
"vectorcraft-geom 0.24.1",
"vectorcraft-testkit",
"vectorcraft-text",
"weezl 0.2.1",
]
[[package]]
name = "vectorcraft-plugins"
version = "0.24.1"
dependencies = [
"craft-image-codecs",
"craft-vectorcraft-format",
"image",
"log",
"serde",
"serde_json",
@@ -6910,11 +7036,12 @@ dependencies = [
name = "vectorcraft-render"
version = "0.24.1"
dependencies = [
"craft-gif",
"craft-image-codecs",
"craft-psd",
"craft-stream-codecs",
"craft-tiff",
"flate2",
"gif 0.14.2",
"image",
"jpeg-encoder",
"log",
@@ -6949,13 +7076,14 @@ name = "vectorcraft-svg"
version = "0.24.1"
dependencies = [
"craft-docpath",
"craft-image-codecs",
"craft-mime",
"craft-svg",
"data-url",
"flate2",
"image",
"kurbo 0.13.1",
"proptest",
"resvg 0.45.1",
"serde",
"serde_json",
"simplecss",
@@ -6978,8 +7106,8 @@ dependencies = [
name = "vectorcraft-testkit"
version = "0.24.1"
dependencies = [
"craft-image-codecs",
"fax",
"image",
"kurbo 0.13.1",
"proptest",
"serde_json",
@@ -6996,6 +7124,8 @@ dependencies = [
name = "vectorcraft-text"
version = "0.24.1"
dependencies = [
"craft-font-catalog",
"craft-proof",
"harfrust 0.13.3",
"icu_segmenter",
"kurbo 0.13.1",
@@ -7004,6 +7134,7 @@ dependencies = [
"subsetter",
"unicode-bidi",
"unicode-general-category",
"unicode-normalization",
"unicode-script",
"unicode-segmentation",
"vectorcraft-doc",
@@ -7017,6 +7148,7 @@ dependencies = [
name = "vectorcraft-three-d"
version = "0.24.1"
dependencies = [
"proptest",
"vectorcraft-geom 0.24.1",
"vectorcraft-pathops 0.24.1",
]
@@ -7025,7 +7157,7 @@ dependencies = [
name = "vectorcraft-tools"
version = "0.24.1"
dependencies = [
"image",
"craft-image-codecs",
"kurbo 0.13.1",
"serde",
"serde_json",
@@ -7057,6 +7189,7 @@ version = "0.24.1"
dependencies = [
"bytemuck",
"chrono",
"craft-image-codecs",
"craft-keymap",
"craft-ui",
"craft-update",
@@ -7733,7 +7866,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.52.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -8011,7 +8144,7 @@ dependencies = [
[[package]]
name = "winprint"
version = "0.2.1"
source = "git+https://github.com/storytold/winprint.rs?rev=5f80b9baf6b58937c401656634e42d33f00ddf49#5f80b9baf6b58937c401656634e42d33f00ddf49"
source = "git+https://github.com/storytold/winprint.rs?rev=8ae097ef941b432b0e7671b1ec3a506800e65e57#8ae097ef941b432b0e7671b1ec3a506800e65e57"
dependencies = [
"flate2",
"fmt-derive",
@@ -8026,6 +8159,7 @@ dependencies = [
"windows",
"windows-core",
"windows-implement",
"windows-numerics",
"xml",
]
@@ -8485,12 +8619,6 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zune-core"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a"
[[package]]
name = "zune-core"
version = "0.5.3"
@@ -8506,22 +8634,13 @@ dependencies = [
"simd-adler32",
]
[[package]]
name = "zune-jpeg"
version = "0.4.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713"
dependencies = [
"zune-core 0.4.12",
]
[[package]]
name = "zune-jpeg"
version = "0.5.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
dependencies = [
"zune-core 0.5.3",
"zune-core",
]
[[package]]
@@ -8530,7 +8649,7 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cba11ecd07cc23351500e840ae03841b7e4997923ec8e4832ee3ae199ea0b6b4"
dependencies = [
"zune-core 0.5.3",
"zune-core",
]
[[package]]
+46 -41
View File
@@ -11,35 +11,40 @@ rust-version = "1.95"
repository = "https://github.com/storytold/vectorcraft"
[workspace.dependencies]
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "c4b8405d5fd8f29cf77de528206bd2b38bb0ecb6", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
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" }
# 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 = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", 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 = "b0d84cd15db39f2af9869cfb47b8b72cbeca3f20" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "b0d84cd15db39f2af9869cfb47b8b72cbeca3f20" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
# 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 = "228f6d0c50f1fdee4c5124603602993fc79d4c9d" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2", features = ["tree"] }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8bd1412eaa7c0b58f3f9c401495d35fe12d6d85e" }
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a7fb55eaf9a15c21e8ce0b13cf605dc54fd15f57" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b" }
# WMF, EMF and EMF+ reader (craft-libs#778).
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "6d620e971e820b517b11a99cad040ebac670e1e2" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "e2dc681a3" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e98299546f5c5c3c22388d16507f8b5e61a5f280", features = ["egui"] }
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"] }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -97,10 +102,12 @@ wat = "1.228"
# Without `text` (glyph runs, through glifo and a second skrifa): the renderer draws the outlines
# vectorcraft-text gives it. The other default features stay.
vello_cpu = { version = "0.2", default-features = false, features = ["std", "png", "u8_pipeline", "f32_pipeline"] }
# The image crate still decodes and encodes for the readers not yet moved to craft-image-codecs
# (File › Open's raster path, PDF and SVG images, the renderer's image paint, DIBs). Its format
# features stay until the last of those moves, so no file that opens today stops opening.
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp", "gif", "tiff", "bmp", "tga"] }
# Without `text` and the system fonts (fontdb, harfrust and skrifa, at other versions than ours):
# SVG import reads `<text>` from the XML itself and never gives usvg a font. A test of the SVG
# crate turns `text` on.
# SVG import reads `<text>` from the XML itself and never gives usvg a font.
usvg = { version = "0.48", default-features = false, features = ["svgz"] }
# Without `simple-text` (its text shaping, the only user of rustybuzz and ttf-parser, which are
# unmaintained, #1730): the PDF writer places glyphs itself. A test of the PDF crate turns it on.
@@ -112,18 +119,9 @@ flate2 = { version = "1", default-features = false, features = ["rust_backend"]
rustix = { version = "1.1", default-features = false }
# Zstandard decoder (pure Rust, builds for wasm32 too): the editing copy an EPS carries of its art.
ruzstd = { version = "0.9.1", default-features = false, features = ["std"] }
# CCITT Group 3 and Group 4 decoder (ITU-T T.4 and T.6): EPS images read through
# `CCITTFaxDecode`. The PDF reader's hayro-syntax uses the same version.
hayro-ccitt = "0.3"
# Substring search for the EPS reader's PostScript `search`.
memchr = "2"
# The WHATWG Encoding Standard's legacy encodings: names in legacy .ai files read in the code page
# the user picks (Mac OS Roman, Korean, Japanese, Chinese).
encoding_rs = "0.8.42"
jpeg-encoder = { version = "0.6", default-features = false, features = ["std"] }
gif = { version = "0.14", default-features = false, features = ["std", "raii_no_panic"] }
# CMYK image samples (vectorcraft-doc's cmyk module): the image crate's own TIFF and JPEG
# decoders, read directly (the image crate converts CMYK to RGB).
# vectorcraft-doc's CMYK TIFF reader and writer (src/cmyk.rs) still use `tiff`. `zune-jpeg` and
# `hayro-ccitt` are only the references tests compare craft-image-codecs' CMYK JPEG inks and
# craft-stream-codecs' Group 3 rows with (vectorcraft-doc's and vectorcraft-engine's dev-dependencies).
tiff = "0.11"
zune-jpeg = "0.5"
# JPEG XL decoder (pure Rust, MIT OR Apache-2.0): File › Open and Place read `.jxl` images. It is
@@ -136,6 +134,13 @@ jxl-grid = "0.6.2"
# Tests: a lossless JPEG XL encoder (pure Rust, MIT OR Apache-2.0 OR Zlib) for the `.jxl` test files.
zune-jpegxl = { version = "0.5.2", default-features = false, features = ["std"] }
zune-core = "0.5"
hayro-ccitt = "0.3"
jpeg-encoder = { version = "0.6", default-features = false, features = ["std"] }
# Substring search for the EPS reader's PostScript `search`.
memchr = "2"
# The WHATWG Encoding Standard's legacy encodings: names in legacy .ai files read in the code page
# the user picks (Mac OS Roman, Korean, Japanese, Chinese).
encoding_rs = "0.8.42"
# ui
egui = "0.37"
@@ -179,13 +184,13 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "9be9a63782298ab59cd9b7a42ee9cba4f42a5ccb" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "481f66d287b2a06845f3667a19daf35f0fe958ed" }
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" }
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" }
+122
View File
@@ -146,3 +146,125 @@ Indic hyphenation patterns (crates/text/patterns/):
Copyright (C) 2016 Santhosh Thottingal, used under the MIT license option.
Original copyright and full license notices are preserved in each hyph-*.tex file.
Source: hyphenation/tex-hyphen, commit 5684c0f51c0b81133db2efbe60a408b4155a3ff5.
JPEG encoder dependency notices
jpeg-encoder 0.6.1, https://crates.io/crates/jpeg-encoder/0.6.1
Licensed under (MIT OR Apache-2.0) AND IJG. The MIT option and the IJG and SIMD
notices are reproduced below. Original license texts and provenance hashes are
retained in licenses/jpeg-encoder-0.6.1/.
--- jpeg-encoder 0.6.1: LICENSE-MIT ---
Copyright (c) 2021 Volker Ströbel <volkerstroebel@mysurdity.de>
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
--- jpeg-encoder 0.6.1: IJG-NOTICE.txt ---
/*
* Ported from mozjpeg to rust
*
* This file was part of the Independent JPEG Group's software:
* Copyright (C) 1991-1996, Thomas G. Lane.
* libjpeg-turbo Modifications:
* Copyright (C) 2015, 2020, D. R. Commander.
*
* Conditions of distribution and use:
* In plain English:
*
* 1. We don't promise that this software works. (But if you find any bugs,
* please let us know!)
* 2. You can use this software for whatever you want. You don't have to pay us.
* 3. You may not pretend that you wrote this software. If you use it in a
* program, you must acknowledge somewhere in your documentation that
* you've used the IJG code.
*
* In legalese:
*
* The authors make NO WARRANTY or representation, either express or implied,
* with respect to this software, its quality, accuracy, merchantability, or
* fitness for a particular purpose. This software is provided "AS IS", and you,
* its user, assume the entire risk as to its quality and accuracy.
*
* This software is copyright (C) 1991-2020, Thomas G. Lane, Guido Vollbeding.
* All Rights Reserved except as specified below.
*
* Permission is hereby granted to use, copy, modify, and distribute this
* software (or portions thereof) for any purpose, without fee, subject to these
* conditions:
* (1) If any part of the source code for this software is distributed, then this
* README file must be included, with this copyright and no-warranty notice
* unaltered; and any additions, deletions, or changes to the original files
* must be clearly indicated in accompanying documentation.
* (2) If only executable code is distributed, then the accompanying
* documentation must state that "this software is based in part on the work of
* the Independent JPEG Group".
* (3) Permission for use of this software is granted only if the user accepts
* full responsibility for any undesirable consequences; the authors accept
* NO LIABILITY for damages of any kind.
*
* These conditions apply to any software derived from or based on the IJG code,
* not just to the unmodified library. If you use our work, you ought to
* acknowledge us.
*
* Permission is NOT granted for the use of any IJG author's name or company name
* in advertising or publicity relating to this software or products derived from
* it. This software may be referred to only as "the Independent JPEG Group's
* software".
*
* We specifically permit and encourage the use of this software as the basis of
* commercial products, provided that all warranty or liability claims are
* assumed by the product vendor.
*
* This file contains a slower but more accurate integer implementation of the
* forward DCT (Discrete Cosine Transform).
*
* A 2-D DCT can be done by 1-D DCT on each row followed by 1-D DCT
* on each column. Direct algorithms are also available, but they are
* much more complex and seem not to be any faster when reduced to code.
*
* This implementation is based on an algorithm described in
* C. Loeffler, A. Ligtenberg and G. Moschytz, "Practical Fast 1-D DCT
* Algorithms with 11 Multiplications", Proc. Int'l. Conf. on Acoustics,
* Speech, and Signal Processing 1989 (ICASSP '89), pp. 988-991.
* The primary algorithm described there uses 11 multiplies and 29 adds.
* We use their alternate method with 12 multiplies and 32 adds.
* The advantage of this method is that no data path contains more than one
* multiplication; this allows a very simple and accurate implementation in
* scaled fixed-point arithmetic, with a minimal number of shifts.
*/
--- jpeg-encoder 0.6.1: SIMD-NOTICE.txt ---
/*
* Ported from mozjpeg / jfdctint-avx2.asm to rust
* Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB
* Copyright (C) 2009, 2016, 2018, 2020, D. R. Commander.
*
* Based on the x86 SIMD extension for IJG JPEG library
* Copyright (C) 1999-2006, MIYASAKA Masaru.
*/
+14 -1
View File
@@ -24,7 +24,7 @@ blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
| | Value | Kind |
|---|---|---|
| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 348/375 wired (92.8%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) |
| **Feature breadth** (Illustrator's menu items, tools, effects, formats exist) | **~88%** | measured in part: menu items 717/719 wired (99.7%), tools 89/92, Illustrator effects 46/50, Photoshop effects 57/57, 3D 4/4 (initial types, no materials) |
| **Feature depth** (weighted by use, scored by behaviour) | **~75%** | estimated |
| **To beta** | **~170–270 h** one agent · ~50–80 h with 4–6 agents | estimated |
| **To full parity** | **~360–590 h** one agent · ~95–165 h with 4–6 agents | estimated |
@@ -128,13 +128,20 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 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-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.
- 2026-11-12: Stencil Bridges in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): strips of a set width are cut out of the selected art so that every island of a stencil cut from it (the inside of an O, a hole in a shape) stays attached to the sheet, by the shortest crossings first, vertical, horizontal or the shortest among 12 directions 15° apart, with up to 16 bridges per island; type is measured by its glyph outlines and stays type, and the original goes to a hidden layer or is replaced. One undo step (`addon.cutting.bridges`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-13: Banner Hems and Grommets in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): on the chosen sides of the selected art's bounds, or of each artboard, a hem line at a set depth inside the edge and grommet marks (a circle with a cross) at a set inset, one at each end of a side and the rest spread evenly at most a set spacing apart, stroked in a chosen swatch; a dialog with Preview, one undo step (`addon.cutting.banner`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-14: Nest Shapes in the Cutting Tools add-on (Object › Plug-ins › Cutting Tools): the selected objects move close together onto an artboard, a sheet of a set size or a roll of a set width, packed by their bounding boxes with a margin inside the edges and a spacing between them, optionally turning objects 90° to fit; objects that do not fit go in a column beside the sheet; a dialog with Preview, one undo step (`addon.cutting.nest`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: With Smart Guides and Snap to Tangent on, a circle drawn from its center with the Ellipse tool (Alt and Shift) snaps its radius so that the circle touches a nearby path (a straight segment, a curve, or another circle from outside or inside) when the radius comes within the snapping tolerance of that size, and the touch point shows the "tangent" label. A VectorCraft addition: headline numbers unchanged.
- 2026-11-05: Release Type on a Path joins the Type Tools add-on (Object › Plug-ins › Type Tools): each selected type on a path splits into point type with the same text and attributes, on one straight line starting where its first character sat, and the plain path it was set on, with its exact shape and place in the stacking order and no paint; or keeps only the path or only the text, optionally leaving the original. A dialog with Preview, one undo step (`addon.type.releasePath`, #5532). A VectorCraft addition: headline numbers unchanged.
- 2026-11-14: Unit Converter add-on (Object › Plug-ins › Unit Converter): a panel with one field per unit (pt, picas, in, mm, cm, px, ft & in, m, yd, ft, Q, Ha) where a length typed in any field updates the others as it is typed; From Selection reads the selection's width or height, Apply sets it as one undo step, and each field copies its value with or without the unit (`addon.units.convert`, `addon.units.selectionSize`, #5528). A VectorCraft addition: headline numbers unchanged.
- 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged.
- 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
@@ -142,9 +149,15 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-01: Expand Dashes into Paths joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): each selected path's dashed stroke becomes separate open paths, one per dash, laid out exactly as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off, so the gaps are real gaps for cutters and plotters, as one undo step (`addon.pathtools.expandDashes`, #4922).
- 2026-11-01: Randomize Opacity joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): each selected object gets its own opacity at random between a minimum and a maximum percent, with a seed that repeats the result, as one undo step (`addon.arrange.randomizeOpacity`, #4925).
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged.
- 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `<name>_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged.
- 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). 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-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.
- 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged.
- 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged.
+4 -1
View File
@@ -238,10 +238,13 @@ fn main() -> ExitCode {
/// A headless session that remembers what the user keeps between runs: the PDF presets saved, the
/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders
/// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there
/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there, keeps File Info's
/// metadata templates there and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and
/// `VECTORCRAFT_CONFIG_DIR` apply as they do there.
fn with_stores(mut h: Headless) -> Headless {
prefs_dir::attach_scripts_dir(&mut h.session);
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_profile_store(&mut h.session);
prefs_dir::attach_color_settings(&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 = "fd5e2feff6ea25bed371a99cc732b3968d621505", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "64b181977a0488e4d1e167bc5cc8cfededc2ed4b", version = "0.1.0" }
vectorcraft-format = { workspace = true }
vectorcraft-text = { workspace = true }
egui = { workspace = true }
+1 -1
View File
@@ -142,7 +142,7 @@ fn send(method: &str, params: Value) -> Pin<Box<dyn Future<Output = Value>>> {
})
}
async fn sleep(ms: i32) {
pub(crate) async fn sleep(ms: i32) {
let promise = js_sys::Promise::new(&mut |resolve, _| {
if let Some(window) = web_sys::window() {
let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms);
+139
View File
@@ -0,0 +1,139 @@
//! Which `demand` web faces (`crates/text/web-fonts.txt`) to fetch: each face is fetched at most
//! once at a time and never again once it loaded. A face whose fetch failed is fetched again after
//! a wait that doubles with each failure, and not after [`MAX_TRIES`] failures.
/// The wait after a face's first failed fetch before it is fetched again (ms).
const RETRY_MS: i32 = 30_000;
/// Failed fetches of a face after which it is not fetched again this session.
pub(crate) const MAX_TRIES: u32 = 5;
#[derive(Clone, Copy, Debug, PartialEq)]
enum State {
Idle,
/// Being fetched, after `tries` failed fetches.
Loading {
tries: u32,
},
Loaded,
/// `tries` fetches failed, the last at `failed_at` (ms); the next may start at `retry_at`, or
/// at once when the clock reads earlier than `failed_at`.
Failed {
tries: u32,
failed_at: f64,
retry_at: f64,
},
}
/// The fetch state of each face of a web font list, by index.
#[derive(Debug, Default)]
pub(crate) struct Demand {
states: Vec<State>,
}
impl Demand {
/// Of the faces `wanted` (indexes into the list), the ones to fetch at time `now` (ms): not
/// loaded, not being fetched, and not waiting to be fetched again. They are marked as being
/// fetched.
pub(crate) fn start(&mut self, wanted: &[usize], now: f64) -> Vec<usize> {
let mut out = Vec::new();
for &i in wanted {
if self.states.len() <= i {
self.states.resize(i + 1, State::Idle);
}
let Some(state) = self.states.get_mut(i) else { continue };
let tries = match *state {
State::Idle => Some(0),
State::Loading { .. } | State::Loaded => None,
State::Failed { tries, failed_at, retry_at } => (tries < MAX_TRIES && (now >= retry_at || now < failed_at)).then_some(tries),
};
if let Some(tries) = tries {
*state = State::Loading { tries };
out.push(i);
}
}
out
}
/// The fetch of face `i` started by [`Demand::start`] ended at `now` (ms): loaded when `ok`.
/// Returns the wait (ms) after which a failed face may be fetched again, or `None` when it
/// loaded or has failed [`MAX_TRIES`] times.
pub(crate) fn finished(&mut self, i: usize, ok: bool, now: f64) -> Option<i32> {
let state = self.states.get_mut(i)?;
let State::Loading { tries } = *state else { return None };
if ok {
*state = State::Loaded;
return None;
}
let tries = tries + 1;
let wait = RETRY_MS << (tries - 1).min(4);
*state = State::Failed { tries, failed_at: now, retry_at: now + f64::from(wait) };
(tries < MAX_TRIES).then_some(wait)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_face_is_fetched_once_and_kept() {
let mut d = Demand::default();
assert_eq!(d.start(&[2], 0.0), [2]);
assert!(d.start(&[2], 1.0).is_empty(), "already being fetched");
assert_eq!(d.finished(2, true, 2.0), None, "loaded: no retry");
assert!(d.start(&[2], 1e9).is_empty(), "loaded: never fetched again");
assert_eq!(d.start(&[0, 2, 1], 3.0), [0, 1], "other faces start on their own");
assert_eq!(d.finished(7, false, 4.0), None, "a face never started");
}
#[test]
fn a_failed_face_waits_longer_after_each_failure_and_then_stops() {
let mut d = Demand::default();
let mut now = 0.0;
// The wait after the 1st, 2nd, ... failure: doubling, up to 16 times the first.
for wait in [1, 2, 4, 8].map(|k| k * RETRY_MS) {
assert_eq!(d.start(&[0], now), [0], "at {now}");
assert_eq!(d.finished(0, false, now), Some(wait), "the wait after the failure at {now}");
assert!(d.start(&[0], now + f64::from(wait) - 1.0).is_empty(), "waits {wait} ms after the failure at {now}");
now += f64::from(wait);
}
// The fifth fetch, and after it fails, none.
assert_eq!(d.start(&[0], now), [0]);
assert_eq!(d.finished(0, false, now), None, "no retry after {MAX_TRIES} failures");
assert!(d.start(&[0], now + 1e12).is_empty(), "no fetch after {MAX_TRIES} failures");
// A later success after failures keeps the face.
let mut d = Demand::default();
d.start(&[1], 0.0);
assert_eq!(d.finished(1, false, 0.0), Some(RETRY_MS));
assert_eq!(d.start(&[1], f64::from(RETRY_MS)), [1]);
assert_eq!(d.finished(1, true, f64::from(RETRY_MS)), None);
assert!(d.start(&[1], 1e12).is_empty());
}
/// While a face is fetched again after a failure, neither the interface asking for its script
/// again nor the retry timer starts a second fetch of it.
#[test]
fn a_face_being_fetched_again_is_not_fetched_twice_at_once() {
let mut d = Demand::default();
d.start(&[0], 0.0);
assert_eq!(d.finished(0, false, 0.0), Some(RETRY_MS));
let retry = f64::from(RETRY_MS);
assert_eq!(d.start(&[0, 0], retry), [0], "one fetch for a face wanted twice");
assert!(d.start(&[0], retry + 1.0).is_empty(), "the interface asking again");
assert!(d.start(&[0], retry + 1_000.0).is_empty(), "the retry timer");
assert_eq!(d.finished(0, true, retry + 2_000.0), None);
assert!(d.start(&[0], 1e12).is_empty(), "loaded");
}
/// A clock that reads earlier than the failure (one set back meanwhile) does not hold the
/// retry back: the timer that asks for it has waited already.
#[test]
fn a_clock_set_back_after_a_failure_does_not_stop_the_retry() {
let mut d = Demand::default();
let failed_at = 1e12;
d.start(&[0], failed_at);
assert_eq!(d.finished(0, false, failed_at), Some(RETRY_MS));
assert!(d.start(&[0], failed_at + 1.0).is_empty(), "still waiting");
assert_eq!(d.start(&[0], failed_at - 3_600_000.0), [0], "the clock went back an hour");
}
}
+51 -8
View File
@@ -1,17 +1,22 @@
//! Craft-fonts faces served beside the wasm (`fonts/<sha16>/…`, copied by
//! `cargo xtask web-fonts`) instead of embedded: [`load_startup_fonts`] fetches the `startup`
//! ones before the app starts, [`spawn_background_fonts`] the rest once it runs. The browser checks
//! each file against its SHA-256 (Subresource Integrity). A face that fails is logged and skipped:
//! the app runs without it. With `WEB_FONTS` empty (built without craft-fonts) both do nothing.
//! ones before the app starts, [`spawn_background_fonts`] the `background` ones once it runs, and
//! [`want_chars`] a `demand` face (Korean, Devanagari) when the interface language or the
//! interface's own text needs its script. The browser checks each file against its SHA-256
//! (Subresource Integrity). A face that fails is logged and skipped: the app runs without it. With
//! `WEB_FONTS` empty (built without craft-fonts) these do nothing.
use std::cell::Cell;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use vectorcraft_text::craft_fonts::demand_fonts;
use vectorcraft_text::{FontDb, WEB_FONTS, WebFont};
use wasm_bindgen::JsCast as _;
use wasm_bindgen::closure::Closure;
use wasm_bindgen_futures::JsFuture;
use crate::demand::Demand;
/// Per startup face: the page shows its loading text meanwhile.
const STARTUP_TIMEOUT_MS: i32 = 20_000;
/// Per background face.
@@ -22,12 +27,49 @@ const BACKGROUND_PARALLEL: usize = 4;
thread_local! {
/// The background fetch runs once per page, though a graphics restart creates the app again.
static BACKGROUND_STARTED: Cell<bool> = const { Cell::new(false) };
/// The `demand` faces' fetches.
static DEMAND: RefCell<Demand> = RefCell::new(Demand::default());
/// The running app's context, asked for a frame when a `demand` face arrives (none before the
/// app starts: its first frame looks through the faces loaded by then).
static REPAINT: RefCell<Option<egui::Context>> = const { RefCell::new(None) };
}
/// Fetch, in the background, the `demand` faces for the scripts of `chars` that are not loaded or
/// being fetched. Each one that arrives asks the app for a frame, and the interface draws those
/// characters with it from then on. Set as the interface's missing-glyph handler
/// (`vectorcraft_ui_egui::on_missing_glyphs`), and called with the interface language's name
/// before the app starts.
pub fn want_chars(chars: &[char]) {
let wanted = demand_fonts(WEB_FONTS, chars.iter().copied());
if !wanted.is_empty() {
fetch_demand(&wanted);
}
}
/// Fetch the `demand` faces `wanted` (indexes into `WEB_FONTS`) that [`Demand::start`] lets start.
/// A face whose fetch fails is fetched again after the wait [`Demand::finished`] gives.
fn fetch_demand(wanted: &[usize]) {
for i in DEMAND.with(|d| d.borrow_mut().start(wanted, vectorcraft_ui_egui::now_ms())) {
let Some(f) = WEB_FONTS.get(i) else { continue };
wasm_bindgen_futures::spawn_local(async move {
let ok = load(f, BACKGROUND_TIMEOUT_MS).await;
let retry = DEMAND.with(|d| d.borrow_mut().finished(i, ok, vectorcraft_ui_egui::now_ms()));
if ok && let Some(ctx) = REPAINT.with(|r| r.borrow().clone()) {
ctx.request_repaint();
}
if let Some(wait) = retry {
// A second longer, so a clock the browser coarsens still reads the wait as over.
crate::api::sleep(wait.saturating_add(1_000)).await;
fetch_demand(&[i]);
}
});
}
}
/// Fetch and register the `startup` faces (one after the other). Returns how many loaded.
pub async fn load_startup_fonts() -> usize {
let mut loaded = 0;
for f in WEB_FONTS.iter().filter(|f| f.startup) {
for f in WEB_FONTS.iter().filter(|f| f.startup && !f.demand) {
if load(f, STARTUP_TIMEOUT_MS).await {
loaded += 1;
}
@@ -36,13 +78,14 @@ pub async fn load_startup_fonts() -> usize {
}
/// Fetch and register the `background` faces, [`BACKGROUND_PARALLEL`] at a time, asking `ctx` for
/// a frame after each so the font menus and the canvas pick it up. Only the first call does
/// anything.
/// a frame after each so the font menus and the canvas pick it up. Only the first call fetches
/// anything; each call makes `ctx` the context a `demand` face asks for a frame.
pub fn spawn_background_fonts(ctx: egui::Context) {
REPAINT.with(|r| *r.borrow_mut() = Some(ctx.clone()));
if BACKGROUND_STARTED.with(|s| s.replace(true)) {
return;
}
let queue: Rc<Vec<&'static WebFont>> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup).collect());
let queue: Rc<Vec<&'static WebFont>> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup && !f.demand).collect());
let next = Rc::new(Cell::new(0usize));
for _ in 0..BACKGROUND_PARALLEL.min(queue.len()) {
let (queue, next, ctx) = (queue.clone(), next.clone(), ctx.clone());
+2
View File
@@ -21,6 +21,8 @@
#[cfg(target_arch = "wasm32")]
mod api;
#[cfg(any(target_arch = "wasm32", test))]
mod demand;
#[cfg(target_arch = "wasm32")]
mod fonts;
#[cfg(any(target_arch = "wasm32", test))]
+5
View File
@@ -81,6 +81,11 @@ pub fn start() {
return;
};
detect_language();
// The face for a Korean or Hindi browser language (or `?lang=`) starts loading now, beside the
// startup fonts, without holding up the start. Text in those scripts painted later (a saved
// interface language, another one chosen, a layer or file name) has its face fetched then.
vectorcraft_ui_egui::on_missing_glyphs(crate::fonts::want_chars);
crate::fonts::want_chars(&i18n::system_lang().name().chars().collect::<Vec<_>>());
wasm_bindgen_futures::spawn_local(async move {
// Before the first frame, which looks for copies a crash left behind.
let locks = WebLocks::start(RECOVERY_PREFIX).await;
+3
View File
@@ -40,6 +40,9 @@ craft-print = { workspace = true }
[target.'cfg(windows)'.dependencies]
craft-update = { workspace = true }
clipboard-win = { workspace = true }
# Reads a print queue's Standard TCP/IP RAW port for the direct-PDF transport (src/direct_pdf.rs).
# MIT, already in the build through the update client.
winreg = "0.55"
# Which GPU drives which display (EnumDisplayDevices, src/gpu.rs), so the window is drawn on the
# GPU that shows it: drawing on a GPU without a monitor reset the display driver. Safe wrappers over
# Win32 (MIT); the `user` feature is User32.dll only. Only the wgpu renderer chooses an adapter.
+10
View File
@@ -43,6 +43,16 @@ impl eframe::App for App {
/// Restore the borderless caption, apply platform menu and pen input, and hand the frame to the
/// app's raw-input hook while the keyboard user is unconfined.
fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) {
// Without vsync, a main-window frame starts no sooner than the minimum interval after the
// last one. eframe runs this hook once per frame, shown or not, before egui reads the input.
// The frame's time moves on by the wait, and the hang report's frame time starts after it.
if raw.viewport_id == egui::ViewportId::ROOT {
if let Some(wait) = super::presentation::frame_wait(self.min_frame, self.last_frame_began.map(|t| t.elapsed())) {
std::thread::sleep(wait);
raw.time = raw.time.map(|time| time + wait.as_secs_f64());
}
self.last_frame_began = Some(std::time::Instant::now());
}
let _timed = BEACON.enter_timed(Stage::Input);
self.frame_start = Some(std::time::Instant::now());
// winit gives the window its caption back when it changes the window's flags (maximize,
+241 -38
View File
@@ -163,6 +163,10 @@ fn takes_files(mimes: &[&'static str]) -> bool {
/// [`copied_file`] with a file of more than `limit` bytes skipped.
fn copied_file_within(paths: Vec<PathBuf>, mimes: &[&'static str], limit: usize) -> Option<Flavour> {
// A list of more than MAX_URIS files (untrusted data) names none, before any file is looked at.
if paths.len() > MAX_URIS {
return None;
}
paths.into_iter().find_map(|path| {
// text/uri-list lines end in CRLF (RFC 2483), but arboard splits them on LF only.
let path = match path.to_str() {
@@ -203,6 +207,53 @@ fn read_rest(file: impl Read, mut data: Vec<u8>, limit: usize) -> Option<Vec<u8>
(data.len() <= limit).then_some(data)
}
/// The data `copy` takes off the clipboard, called only when `size` (what the clipboard reports
/// before the copy) is known and from 1 to `limit` bytes. `None` without a call otherwise, and
/// when the copy comes to more than `limit` bytes.
#[cfg_attr(not(any(windows, target_os = "macos")), allow(dead_code))]
fn copy_within(size: Option<usize>, limit: usize, copy: impl FnOnce() -> Option<Vec<u8>>) -> Option<Vec<u8>> {
size.filter(|&n| n > 0 && n <= limit)?;
copy().filter(|data| data.len() <= limit)
}
/// The most bytes of UTF-8 that `utf16` bytes of UTF-16 text come to: a code unit (2 bytes) is at
/// most 3 bytes of UTF-8, and a surrogate pair (4 bytes) is 4.
#[cfg_attr(not(windows), allow(dead_code))]
fn utf8_most(utf16: usize) -> usize {
utf16.div_ceil(2).saturating_mul(3)
}
/// Whether a Windows file list (`CF_HDROP`: a `DROPFILES` header, then file names each ended by a
/// NUL and the list by one more, in UTF-16 when the header's `fWide` is set) names at most `limit`
/// files. Counting stops at the first name past `limit`. A block too short for its header, or
/// whose names would start past its end, is not within.
#[cfg_attr(not(windows), allow(dead_code))]
fn drop_files_within(block: &[u8], limit: usize) -> bool {
let field = |at: usize| Some(u32::from_le_bytes(block.get(at..at.checked_add(4)?)?.try_into().ok()?));
let (Some(start), Some(wide)) = (field(0), field(16)) else {
return false;
};
let Some(names) = usize::try_from(start).ok().and_then(|start| block.get(start..)) else {
return false;
};
let (mut count, mut in_name) = (0usize, false);
for unit in names.chunks_exact(if wide != 0 { 2 } else { 1 }) {
if unit.iter().all(|&b| b == 0) {
if !in_name {
break;
}
in_name = false;
} else if !in_name {
in_name = true;
count += 1;
if count > limit {
return false;
}
}
}
true
}
/// The most URIs a copied file list may hold, VectorCraft's own limit: a longer list (untrusted
/// data) names no files.
const MAX_URIS: usize = 1024;
@@ -284,12 +335,13 @@ fn file_uri_path(uri: &str) -> Option<PathBuf> {
#[cfg(windows)]
mod win {
use std::num::NonZeroU32;
use std::num::{NonZeroU32, NonZeroUsize};
use clipboard_win::{formats, options::NoClear, raw};
use super::{
BITMAP, ClipboardRead, Cursor, Flavour, PNG, SVG, SystemClipboard, TEXT, copied_file, decode_png, dib_image, png_flavour, windows_formats,
BITMAP, ClipboardRead, Cursor, Flavour, MAX_BYTES, MAX_URIS, PNG, SVG, SystemClipboard, TEXT, copied_file, copy_within, decode_png,
dib_image, drop_files_within, png_flavour, utf8_most, windows_formats,
};
/// The device-independent bitmaps, the one that carries alpha first. Each is there whenever the
@@ -376,8 +428,11 @@ mod win {
let mut files = vec![];
{
let _open = clipboard_win::Clipboard::new_attempts(10).ok()?;
// None copied when the clipboard holds no file list.
let _ = raw::get_file_list_path(&mut files);
// None copied when the clipboard holds no file list, or one of more than MAX_BYTES
// or MAX_URIS files: the list is counted before its names are copied.
if copy_registered(formats::CF_HDROP, MAX_BYTES).is_some_and(|block| drop_files_within(&block, MAX_URIS)) {
let _ = raw::get_file_list_path(&mut files);
}
}
// The files are read with the clipboard closed again, not keeping other apps waiting.
copied_file(files, mimes).map(ClipboardRead::Now).or_else(|| {
@@ -396,44 +451,64 @@ mod win {
}
}
/// Read the first registered format of `mime` the clipboard holds into `data`.
fn read_registered(mime: &str, data: &mut Vec<u8>) -> bool {
formats_of(mime).filter(|id| raw::is_format_avail(*id)).any(|id| {
data.clear();
raw::get_vec(id, data).is_ok() && !data.is_empty()
/// The size the clipboard reports for format `id`, while it is open.
fn size_of(id: u32) -> Option<usize> {
raw::size(id).map(NonZeroUsize::get)
}
/// The data of format `id`, while the clipboard is open, copied only when its size is at most
/// `limit` bytes ([`copy_within`]).
fn copy_registered(id: u32, limit: usize) -> Option<Vec<u8>> {
copy_within(size_of(id), limit, || {
let mut data = vec![];
raw::get_vec(id, &mut data).ok()?;
Some(data)
})
}
/// The first registered format of `mime` the clipboard holds that is not empty and at most
/// [`MAX_BYTES`]; a larger one is skipped and the next tried.
fn read_registered(mime: &str) -> Option<Vec<u8>> {
formats_of(mime).filter(|id| raw::is_format_avail(*id)).find_map(|id| copy_registered(id, MAX_BYTES).filter(|data| !data.is_empty()))
}
/// A device-independent bitmap as a PNG flavour.
fn dib_png(dib: &[u8]) -> Option<Flavour> {
png_flavour(&dib_image(dib)?)
}
/// Copy both bitmap formats while the clipboard is open, then decode them in preference order.
pub(super) fn read_dibs(mut get: impl FnMut(u32) -> Option<Vec<u8>>) -> Option<ClipboardRead> {
let dibs: Vec<_> = DIBS.into_iter().filter_map(&mut get).collect();
/// `size` gives each format's size before `get` copies it, and a format of more than
/// [`MAX_BYTES`] is not copied ([`copy_within`]) and the next one is tried.
pub(super) fn read_dibs(mut size: impl FnMut(u32) -> Option<usize>, mut get: impl FnMut(u32) -> Option<Vec<u8>>) -> Option<ClipboardRead> {
let dibs: Vec<_> = DIBS.into_iter().filter_map(|id| copy_within(size(id), MAX_BYTES, || get(id))).collect();
(!dibs.is_empty()).then_some(ClipboardRead::Later(Box::new(move || dibs.iter().find_map(|dib| dib_png(dib)))))
}
/// One flavour, while the clipboard is open. A device-independent bitmap is copied here, and
/// the work that comes back decodes each captured format in preference order.
/// the work that comes back decodes each captured format in preference order. Text whose
/// UTF-16 block could come to more than [`MAX_BYTES`] as UTF-8 ([`utf8_most`]) is not read.
fn read_one(mime: &'static str) -> Option<ClipboardRead> {
let mut data = vec![];
let mime = match mime {
BITMAP if read_registered(PNG, &mut data) => PNG,
BITMAP => {
return read_dibs(|id| {
let mut dib = vec![];
raw::get_vec(id, &mut dib).ok()?;
Some(dib)
});
}
let (mime, mut data) = match mime {
BITMAP => match read_registered(PNG) {
Some(png) => (PNG, png),
None => {
return read_dibs(size_of, |id| {
let mut dib = vec![];
raw::get_vec(id, &mut dib).ok()?;
Some(dib)
});
}
},
TEXT => {
raw::get_string(&mut data).ok()?;
TEXT
let text = copy_within(size_of(formats::CF_UNICODETEXT).map(utf8_most), MAX_BYTES, || {
let mut text = vec![];
raw::get_string(&mut text).ok()?;
Some(text)
})?;
(TEXT, text)
}
m if read_registered(m, &mut data) => m,
_ => return None,
m => (m, read_registered(m)?),
};
// Memory blocks can be longer than the data: SVG text ends at its first NUL.
if mime == SVG
@@ -3141,7 +3216,7 @@ mod mac {
use objc2_app_kit::NSPasteboard;
use objc2_foundation::{NSArray, NSString};
use super::{Flavour, pasteboard_types};
use super::{Flavour, MAX_BYTES, copy_within, pasteboard_types};
/// Does the pasteboard hold one of `mimes` ([`pasteboard_types`])? Asks for its types only.
pub fn has(mimes: &[&'static str]) -> bool {
@@ -3152,13 +3227,16 @@ mod mac {
})
}
/// The pasteboard's data for `mime`, the first of its types held ([`pasteboard_types`]).
/// The pasteboard's data for `mime`, the first of its types held ([`pasteboard_types`]) that is
/// not empty and at most [`MAX_BYTES`]: its length is checked before it is copied, and a larger
/// type is skipped and the next tried.
pub fn read(mime: &str) -> Option<Flavour> {
autoreleasepool(|_| {
let pasteboard = NSPasteboard::generalPasteboard();
pasteboard_types(mime).iter().find_map(|&(t, mime)| {
let data = pasteboard.dataForType(&NSString::from_str(t))?.to_vec();
(!data.is_empty()).then_some(Flavour { mime, data })
let held = pasteboard.dataForType(&NSString::from_str(t))?;
let data = copy_within(Some(held.len()), MAX_BYTES, || Some(held.to_vec()))?;
Some(Flavour { mime, data })
})
})
}
@@ -3345,6 +3423,102 @@ mod tests {
assert!(uri_list_paths(list(MAX_URIS + 1).as_bytes()).is_empty());
}
/// A copied file list of more than 1,024 files pastes none, before any file is looked at,
/// wherever the list came from; 1,024 files paste the first that is art.
#[test]
fn a_copied_file_list_longer_than_the_limit_pastes_no_file() {
let d = dir("many");
let art = d.path().join("art.svg");
std::fs::write(&art, "<svg xmlns=\"http://www.w3.org/2000/svg\"/>").unwrap();
let missing = |n: usize| (0..n).map(|i| d.path().join(format!("gone{i}.png"))).collect::<Vec<_>>();
let last = [missing(MAX_URIS - 1), vec![art.clone()]].concat();
assert_eq!(copied_file(last, &PASTE_ORDER).map(|f| f.mime), Some(SVG));
// The art first: no file is opened past the count.
let first = [vec![art.clone()], missing(MAX_URIS)].concat();
assert!(copied_file(first, &PASTE_ORDER).is_none());
assert!(copied_file([missing(MAX_URIS), vec![art]].concat(), &PASTE_ORDER).is_none());
}
/// Clipboard data is copied only when the size the clipboard gives is from 1 byte to the limit,
/// and the copy is not asked for otherwise.
#[test]
fn clipboard_data_is_copied_only_when_its_size_fits() {
let copy = |size: Option<usize>, got: usize| {
let mut asked = false;
let data = copy_within(size, 8, || {
asked = true;
Some(vec![1; got])
});
(data.map(|d| d.len()), asked)
};
assert_eq!(copy(Some(8), 8), (Some(8), true));
assert_eq!(copy(Some(1), 1), (Some(1), true));
for size in [None, Some(0), Some(9), Some(usize::MAX)] {
assert_eq!(copy(size, 1), (None, false), "{size:?}");
}
// Data that comes to more than the limit after all is refused.
assert_eq!(copy(Some(8), 9), (None, true));
assert_eq!(MAX_BYTES, 64 << 20);
}
/// The UTF-8 that UTF-16 text comes to is bounded from the UTF-16 block's size alone, before
/// the text is converted: a block that could pass the limit as UTF-8 is not read.
#[test]
fn text_is_bounded_by_what_its_utf8_could_come_to() {
for text in ["", "a", "\u{20ac}\u{20ac}\u{20ac}", "\u{1f600}", "a\u{20ac}\u{1f600}\u{ffff}"] {
let utf16 = text.encode_utf16().count() * 2;
assert!(utf8_most(utf16) >= text.len(), "{text:?}");
}
// Every code unit at 3 bytes of UTF-8: the bound is exact.
assert_eq!(utf8_most("\u{20ac}\u{20ac}".encode_utf16().count() * 2), "\u{20ac}\u{20ac}".len());
let copied = |utf16: usize| copy_within(Some(utf8_most(utf16)), MAX_BYTES, || Some(vec![])).is_some();
assert!(copied(MAX_BYTES / 3 * 2));
assert!(!copied(MAX_BYTES / 3 * 2 + 2));
assert!(!copied(MAX_BYTES));
assert_eq!(utf8_most(usize::MAX), usize::MAX);
}
/// A Windows file list (CF_HDROP) of `names`: a DROPFILES header, the names in UTF-16 or one
/// byte a character, each ended by a NUL, and one more NUL.
fn drop_files(names: &[&str], wide: bool) -> Vec<u8> {
let mut block = vec![];
block.extend(20u32.to_le_bytes());
block.extend([0u8; 12]);
block.extend(u32::from(wide).to_le_bytes());
for name in names.iter().copied().chain([""]) {
for unit in name.encode_utf16().chain([0]) {
if wide {
block.extend(unit.to_le_bytes());
} else {
block.push(unit as u8);
}
}
}
block
}
#[test]
fn a_windows_file_list_is_counted_before_its_names_are_read() {
let names = |n: usize| (0..n).map(|i| format!("C:\\art\\{i}.svg")).collect::<Vec<_>>();
for wide in [true, false] {
let list = |n: usize| drop_files(&names(n).iter().map(String::as_str).collect::<Vec<_>>(), wide);
assert!(drop_files_within(&list(MAX_URIS), MAX_URIS), "{wide}");
assert!(!drop_files_within(&list(MAX_URIS + 1), MAX_URIS), "{wide}");
assert!(drop_files_within(&list(0), MAX_URIS), "{wide}");
// Names past the list's closing NUL are not counted.
let mut ended = list(2);
ended.extend(list(MAX_URIS + 1).get(20..).unwrap());
assert!(drop_files_within(&ended, 2), "{wide}");
// A list cut short counts the names it holds.
assert!(!drop_files_within(&list(3)[..list(3).len() - 4], 2), "{wide}");
}
// A header cut short, or names that would start past the block's end.
assert!(!drop_files_within(&drop_files(&["a"], true)[..19], MAX_URIS));
let mut past = drop_files(&["a"], true);
past[0..4].copy_from_slice(&u32::MAX.to_le_bytes());
assert!(!drop_files_within(&past, MAX_URIS));
}
#[test]
fn gnome_files_list_names_its_files_after_copy_or_cut() {
let paths = |list: &[u8]| gnome_copied_paths(list).into_iter().map(|p| p.to_string_lossy().into_owned()).collect::<Vec<_>>();
@@ -3398,19 +3572,48 @@ mod tests {
let valid = dib(40, 1, 1, 32, 0, &[], &bgra(&[RED]));
let mut captured = Vec::new();
let read = win::read_dibs(|id| {
captured.push(id);
match id {
CF_DIBV5 => Some(vec![40, 0, 0]),
CF_DIB => Some(valid.clone()),
_ => None,
}
})
let get = |id: u32| match id {
CF_DIBV5 => Some(vec![40, 0, 0]),
CF_DIB => Some(valid.clone()),
_ => None,
};
let read = win::read_dibs(
|id| get(id).map(|d| d.len()),
|id| {
captured.push(id);
get(id)
},
)
.unwrap();
assert_eq!(captured, [CF_DIBV5, CF_DIB]);
let flavour = read.flavour().unwrap();
assert_eq!(flavour.mime, PNG);
assert_eq!(pixels(&decode_png(&flavour.data).unwrap()), [RED]);
// A bitmap larger than the limit is not copied, and the other one still pastes.
captured.clear();
let read = win::read_dibs(
|id| if id == CF_DIBV5 { Some(MAX_BYTES + 1) } else { get(id).map(|d| d.len()) },
|id| {
captured.push(id);
get(id)
},
)
.unwrap();
assert_eq!(captured, [CF_DIB]);
assert_eq!(read.flavour().map(|f| f.mime), Some(PNG));
// Each format has the limit to itself: a first one at the limit that doesn't decode
// leaves the second to paste.
captured.clear();
let read = win::read_dibs(
|id| if id == CF_DIBV5 { Some(MAX_BYTES) } else { get(id).map(|d| d.len()) },
|id| {
captured.push(id);
get(id)
},
)
.unwrap();
assert_eq!(captured, [CF_DIBV5, CF_DIB]);
assert_eq!(read.flavour().map(|f| f.mime), Some(PNG));
}
#[test]
+88 -10
View File
@@ -10,7 +10,7 @@
//! - macOS: the window's layer is tagged sRGB and macOS converts it (`mac_color_space`).
//!
//! While the preference is on, a background thread reads the display every [`EVERY`] seconds,
//! and at once when the window moves to another display.
//! and at once when the window moves to another display or Edit › Refresh Monitor Profile asks.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
@@ -31,6 +31,8 @@ pub(crate) struct Reader {
looked: Option<f64>,
/// A reading is running.
busy: Arc<AtomicBool>,
/// [`DisplayProfile::attach_reader`] was called.
attached: bool,
}
/// Clears [`Reader::busy`] when the reading thread ends, also by a panic.
@@ -45,22 +47,22 @@ impl Drop for Done {
impl Reader {
/// Starts a reading when one is due and none is running. `now` is the frame's time in seconds.
pub(crate) fn tick(&mut self, window: &winit::window::Window, now: f64, enabled: bool, profile: &DisplayProfile, ctx: &egui::Context) {
if !enabled || self.busy.load(Ordering::Acquire) || self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) {
return;
if !self.attached {
profile.attach_reader();
self.attached = true;
}
self.looked = Some(now);
let display = window.current_monitor().and_then(|m| m.name());
if !due(self.last.as_ref(), now, display.as_deref()) {
let Some(display) = self.start(now, enabled, profile, || window.current_monitor().and_then(|m| m.name())) else {
return;
}
self.last = Some((now, display.clone()));
};
profile.pending();
self.busy.store(true, Ordering::Release);
let done = Done(self.busy.clone());
let (profile, ctx) = (profile.clone(), ctx.clone());
let spawned = std::thread::Builder::new().name("display profile".into()).spawn(move || {
let _done = done;
if profile.report(read(display)) {
let changed = profile.report(read(display));
drop(done);
// A request made while this reading ran starts on the next frame.
if changed || profile.read_requested() {
ctx.request_repaint();
}
});
@@ -68,6 +70,32 @@ impl Reader {
log::warn!("couldn't start reading the display profile: {e}");
}
}
/// The display to read at `now` when a reading is to start, looked up with `display`. A
/// request from Refresh Monitor Profile ([`DisplayProfile::request_read`]) starts one at once,
/// past [`EVERY`] and [`LOOK_EVERY`]; while a reading runs it waits, and a frame that finds the
/// preference off drops it. A request made with the preference on is kept when the preference
/// goes off and on again between two frames.
fn start(&mut self, now: f64, enabled: bool, profile: &DisplayProfile, display: impl FnOnce() -> Option<String>) -> Option<Option<String>> {
if !enabled {
profile.take_request();
return None;
}
if self.busy.load(Ordering::Acquire) {
return None;
}
let asked = profile.take_request();
if !asked && self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) {
return None;
}
self.looked = Some(now);
let display = display();
if !asked && !due(self.last.as_ref(), now, display.as_deref()) {
return None;
}
self.last = Some((now, display.clone()));
Some(display)
}
}
/// Whether a reading of `display` is due at `now`, after the last one (`last`): none yet, another
@@ -570,6 +598,56 @@ mod tests {
assert!(due(Some(&last), 50.0, Some("DP-1")));
}
fn attached() -> DisplayProfile {
let profile = DisplayProfile::default();
profile.attach_reader();
profile
}
#[test]
fn a_requested_reading_starts_on_the_next_frame_past_both_intervals() {
let (mut r, profile) = (Reader::default(), attached());
let dp1 = || Some("DP-1".to_string());
assert_eq!(r.start(100.0, true, &profile, dp1), Some(Some("DP-1".into())));
// Inside the display lookup interval and the reading interval: nothing starts.
assert_eq!(r.start(100.5, true, &profile, || panic!("not looked up")), None);
assert_eq!(r.start(102.0, true, &profile, dp1), None);
profile.request_read(true).unwrap();
assert_eq!(r.start(102.1, true, &profile, dp1), Some(Some("DP-1".into())));
assert!(!profile.read_requested(), "the request is taken");
// The intervals run again from the requested reading.
assert_eq!(r.start(102.2, true, &profile, dp1), None);
assert_eq!(r.start(111.0, true, &profile, dp1), None);
assert_eq!(r.start(113.0, true, &profile, dp1), Some(Some("DP-1".into())));
}
#[test]
fn a_request_made_while_a_reading_runs_waits_for_it_to_end() {
let (mut r, profile) = (Reader::default(), attached());
let dp1 = || Some("DP-1".to_string());
assert!(r.start(0.0, true, &profile, dp1).is_some());
r.busy.store(true, Ordering::Release);
profile.request_read(true).unwrap();
assert_eq!(r.start(0.1, true, &profile, dp1), None);
assert_eq!(r.start(5.0, true, &profile, dp1), None);
assert!(profile.read_requested(), "kept while the reading runs");
r.busy.store(false, Ordering::Release);
assert_eq!(r.start(5.1, true, &profile, dp1), Some(Some("DP-1".into())));
assert!(!profile.read_requested());
}
#[test]
fn a_request_is_dropped_when_the_preference_goes_off() {
let (mut r, profile) = (Reader::default(), attached());
let dp1 = || Some("DP-1".to_string());
assert!(r.start(0.0, true, &profile, dp1).is_some());
profile.request_read(true).unwrap();
assert_eq!(r.start(0.1, false, &profile, dp1), None);
assert!(!profile.read_requested());
assert_eq!(r.start(0.2, true, &profile, dp1), None, "no reading starts later for it");
assert!(profile.request_read(false).is_err());
}
#[test]
fn wayland_sessions_are_told_apart_from_x11_by_the_environment() {
let env = |pairs: &'static [(&'static str, &'static str)]| {
+87 -11
View File
@@ -1,5 +1,7 @@
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
use super::portal_save;
#[cfg(windows)]
use super::windows_screen_color;
#[cfg(all(windows, not(target_vendor = "win7")))]
use super::windows_stylus;
use super::{ClipboardProbeFactory, FilePick, PickRequest, Services, clipboard, cursor_theme, fileio, printing};
@@ -71,7 +73,7 @@ fn open_extensions(exts: &[impl AsRef<str>], any_case: bool) -> Vec<String> {
/// `d` set up for `request`: its title, file types, folder and suggested name.
fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
let pick = match request {
PickRequest::Open(pick) | PickRequest::Save(pick) => pick,
PickRequest::Open(pick) | PickRequest::Save(pick) | PickRequest::OpenFiles(pick) => pick,
PickRequest::OpenMany => {
return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| {
d.filter(
@@ -81,8 +83,9 @@ fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
});
}
PickRequest::Folder => return d,
PickRequest::FolderAt(folder) => return d.folder(folder),
};
let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_));
let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_) | PickRequest::OpenFiles(_));
let d = pick.filters.iter().fold(d, |d, (name, exts)| {
d.filter(
vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()),
@@ -93,7 +96,55 @@ fn dialog_for<D: DialogSettings>(d: D, request: &PickRequest) -> D {
Some(folder) => d.folder(folder),
None => d,
};
if pick.name.is_empty() { d } else { d.file_name(&pick.name) }
if pick.name.is_empty() {
return d;
}
// Windows' save dialog changes the extension when a different file type is chosen only when
// the suggested name has no explicit extension. rfd supplies the first filter's extension to
// that dialog, so leave the suffix to Windows for saves that offer several formats (#5451).
// A remaining dot in the stem would look like another explicit extension to Windows.
#[cfg(windows)]
if matches!(request, PickRequest::Save(_))
&& pick.filters.len() > 1
&& let Some(ext) = std::path::Path::new(&pick.name).extension().and_then(|e| e.to_str())
&& pick.filters.iter().any(|(_, exts)| exts.iter().any(|e| e.eq_ignore_ascii_case(ext)))
&& let Some(stem) = std::path::Path::new(&pick.name).file_stem().and_then(|s| s.to_str())
&& !stem.contains('.')
{
return d.file_name(stem);
}
d.file_name(&pick.name)
}
#[cfg(test)]
#[test]
fn a_folder_picker_asked_for_a_folder_starts_there() {
/// The settings a dialog was given, by name.
#[derive(Default)]
struct Recorded(Vec<String>);
impl DialogSettings for Recorded {
fn parent(self, _: &winit::window::Window) -> Self {
self
}
fn title(mut self, title: &str) -> Self {
self.0.push(format!("title {title}"));
self
}
fn filter(mut self, name: &str, _: &[impl ToString]) -> Self {
self.0.push(format!("filter {name}"));
self
}
fn folder(mut self, folder: &str) -> Self {
self.0.push(format!("folder {folder}"));
self
}
fn file_name(mut self, name: &str) -> Self {
self.0.push(format!("name {name}"));
self
}
}
assert_eq!(dialog_for(Recorded::default(), &PickRequest::FolderAt("/a/b".into())).0, ["folder /a/b"]);
assert!(dialog_for(Recorded::default(), &PickRequest::Folder).0.is_empty());
}
/// A native file dialog for `request` over `parent` (on Linux the portal then shows it over the
@@ -128,9 +179,9 @@ fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent)
}
let paths = match request {
PickRequest::Open(_) => dialog.pick_file().into_iter().collect(),
PickRequest::OpenMany => dialog.pick_files().unwrap_or_default(),
PickRequest::OpenMany | PickRequest::OpenFiles(_) => dialog.pick_files().unwrap_or_default(),
PickRequest::Save(_) => dialog.save_file().into_iter().collect(),
PickRequest::Folder => dialog.pick_folder().into_iter().collect(),
PickRequest::Folder | PickRequest::FolderAt(_) => dialog.pick_folder().into_iter().collect(),
};
paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect()
}
@@ -313,7 +364,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti
let picked = dialog.pick_file();
Box::pin(async move { picked.await.iter().map(path).collect() })
}
PickRequest::OpenMany => {
PickRequest::OpenMany | PickRequest::OpenFiles(_) => {
let picked = dialog.pick_files();
Box::pin(async move { picked.await.unwrap_or_default().iter().map(path).collect() })
}
@@ -332,7 +383,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti
// on that nil; treat the pick as cancelled instead (#5980).
Err(()) => Box::pin(async move { Vec::new() }),
},
PickRequest::Folder => {
PickRequest::Folder | PickRequest::FolderAt(_) => {
let picked = dialog.pick_folder();
Box::pin(async move { picked.await.iter().map(path).collect() })
}
@@ -353,14 +404,15 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
.and_then(|w| w.window_handle().ok())
.is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)));
let (clip, clip_probe) = (parent.clone(), parent.clone());
let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
#[cfg(any(target_os = "macos", target_os = "linux"))]
let (p1, p2, p3, p4, p5, p6, p7) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent);
#[cfg(any(target_os = "macos", target_os = "linux", windows))]
let sampled_ui = ui.clone();
#[cfg(target_os = "linux")]
let sampled_parent = p1.clone();
Services {
pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())),
pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))),
pick_open_files: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::OpenFiles(pick.clone()), &p6))),
pick_save: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Save(pick.clone()), &p3).into_iter().next())),
// Linux shows dialogs on a thread of their own (#592), macOS as sheets (#867); Windows
// dialogs run the window's events while they are open.
@@ -408,11 +460,14 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services {
// Edit Original of a raster image with Use System Defaults for Edit Original off (#5236).
open_in_photocraft: Some(Box::new(open_in_photocraft)),
pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())),
pick_folder_at: Some(Box::new(move |start: &str| pick_now(PickRequest::FolderAt(start.to_string()), &p7).into_iter().next())),
// Sample Color from Screen: the system's color sampler.
#[cfg(target_os = "macos")]
screen_color: Some(mac_screen_color::sampler(sampled_ui)),
#[cfg(target_os = "linux")]
screen_color: Some(linux_screen_color::sampler(sampled_ui, sampled_parent)),
#[cfg(windows)]
screen_color: Some(windows_screen_color::sampler(sampled_ui)),
// File → Print: the system's printers and print queue.
print: Some(Box::new(printing::SystemPrint)),
..Default::default()
@@ -758,7 +813,7 @@ mod dialog_tests {
/// The file types a dialog was given, by label.
#[derive(Default)]
struct Filters(Vec<(String, Vec<String>)>);
struct Filters(Vec<(String, Vec<String>)>, Option<String>);
impl DialogSettings for Filters {
fn parent(self, _window: &winit::window::Window) -> Self {
@@ -774,7 +829,8 @@ mod dialog_tests {
fn folder(self, _folder: &str) -> Self {
self
}
fn file_name(self, _name: &str) -> Self {
fn file_name(mut self, name: &str) -> Self {
self.1 = Some(name.to_string());
self
}
}
@@ -831,4 +887,24 @@ mod dialog_tests {
let first = fileio::place_filters().next().map(|(_, exts)| open_extensions(exts, CASE_SENSITIVE_FILTERS));
assert_eq!(placed.first().map(|(_, exts)| exts.clone()), first);
}
/// A format selected after the Windows Save As dialog opens can replace the suffix of the
/// suggested name. Single-format saves and open dialogs keep the supplied name verbatim.
#[cfg(windows)]
#[test]
fn save_dialog_with_several_formats_leaves_the_extension_to_windows() {
let filters = vec![FilePick::filter("VectorCraft", &["vectorcraft"]), FilePick::filter("PDF-compatible .ai", &["ai"])];
let pick = FilePick { name: "Poster.vectorcraft".into(), filters: filters.clone(), ..Default::default() };
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick.clone())).1.as_deref(), Some("Poster"));
assert_eq!(dialog_for(Filters::default(), &PickRequest::Open(pick)).1.as_deref(), Some("Poster.vectorcraft"));
let pick = FilePick { name: "Poster.AI".into(), filters: filters.clone(), ..Default::default() };
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster"));
let pick = FilePick { name: "Poster.design".into(), filters: filters.clone(), ..Default::default() };
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.design"));
let pick = FilePick { name: "draft.v1.vectorcraft".into(), filters: filters.clone(), ..Default::default() };
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("draft.v1.vectorcraft"));
let pick = FilePick { name: "Poster.vectorcraft".into(), filters: vec![filters[0].clone()], ..Default::default() };
assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.vectorcraft"));
}
}
+32 -10
View File
@@ -77,6 +77,7 @@ mod window_frame;
mod windows_alt_codes;
#[cfg(windows)]
mod windows_cores;
mod windows_screen_color;
mod windows_stylus;
mod xwayland;
@@ -141,6 +142,11 @@ struct App {
display_profile: display_profile::Reader,
/// When this frame's input hook started, for the hang report's frame times (`hang_watch`).
frame_start: Option<std::time::Instant>,
/// The shortest time between the starts of two frames, while the window presents without vsync
/// ([`presentation::min_frame_interval`]).
min_frame: Option<std::time::Duration>,
/// When the last frame started, after its wait for [`Self::min_frame`].
last_frame_began: Option<std::time::Instant>,
}
/// `vectorcraft --help`. Headless work (convert, run, MCP) is `vectorcraft-cli`'s.
@@ -364,6 +370,10 @@ fn main() -> std::process::ExitCode {
let saved_window = saved.as_ref().and_then(|ui| ui.window);
#[cfg(feature = "wgpu")]
let gpu_pref = saved.as_ref().and_then(|ui| ui.engine_prefs.get("gpuPreference")).and_then(serde_json::Value::as_str);
// Preferences › Performance › Low-Latency Drawing; anything but `true` in the file is off.
#[cfg(feature = "wgpu")]
let low_latency_drawing =
saved.as_ref().and_then(|ui| ui.engine_prefs.get("lowLatencyDrawing")).and_then(serde_json::Value::as_bool).unwrap_or(false);
#[cfg(feature = "wgpu")]
let power_env = eframe::wgpu::PowerPreference::from_env();
#[cfg(feature = "wgpu")]
@@ -457,10 +467,11 @@ fn main() -> std::process::ExitCode {
let mut options = options;
// One frame queued, not two: the canvas is rasterized on the CPU and the GPU only
// composites it, so the window answers the pointer a frame sooner (#444).
// `--present-mode` and `--frame-latency` change it for a launch (`presentation`).
options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY);
// `--present-mode` and `--frame-latency` change it for a launch, and Low-Latency Drawing
// asks for no vsync when neither sets the mode (`presentation`).
options.wgpu_options.surface = presentation.apply(eframe::egui_wgpu::SurfaceConfig::LOW_LATENCY, low_latency_drawing);
// What the app asks for: the driver picks novsync's mode and may clamp the latency.
log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation));
log::info!("requested window surface: {}", presentation::describe(&options.wgpu_options.surface, &presentation, low_latency_drawing));
// Only adapters that can show the window, in the order `gpu` gives (#306, #502).
if let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup {
create.native_adapter_selector = Some(gpu::selector(power, displays, compositor, left_out.adapters.clone(), startup.clone()));
@@ -507,6 +518,11 @@ fn main() -> std::process::ExitCode {
// For the hang report (`hang_watch`).
#[cfg(feature = "wgpu")]
let requested_surface = options.wgpu_options.surface;
// Without vsync, frames start at most 240 times a second (`presentation`).
#[cfg(feature = "wgpu")]
let min_frame = presentation::min_frame_interval(&requested_surface);
#[cfg(not(feature = "wgpu"))]
let min_frame = None;
// A panic that ends the window (egui-wgpu's own, #502) is caught here: never a crash.
let run = |options: eframe::NativeOptions, app_creator: eframe::AppCreator<'_>| {
#[cfg(target_os = "linux")]
@@ -535,7 +551,10 @@ fn main() -> std::process::ExitCode {
prefs_dir::attach_plugin_store(&mut session);
// File › Scripts lists the scripts of the Scripts folder next to the preferences.
prefs_dir::attach_scripts_dir(&mut session);
// 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_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);
load_prefs(&mut app, saved);
@@ -588,14 +607,15 @@ fn main() -> std::process::ExitCode {
created.created(&cc.egui_ctx);
if !gpu::skipped().is_empty() {
// A processor chosen in Settings can be the one that can't show the window.
let hint = if chosen_gpu {
" (Settings › Performance › Graphics Processor › Automatic uses the one that drives your display)"
if chosen_gpu {
app.status(format!(
"The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary} (Settings › Performance › Graphics Processor › Automatic uses the one that drives your display)"
));
} else {
""
};
app.status(format!(
"The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary}{hint}"
));
app.status(format!(
"The graphics processor tried first couldn't show the window, so VectorCraft started again on {summary}"
));
}
} else if let Some(crash) = &crash {
app.status(match crash {
gpu::Crash::Adapter { name, .. } => format!(
@@ -690,6 +710,8 @@ fn main() -> std::process::ExitCode {
monitors_listed: None,
display_profile: Default::default(),
frame_start: None,
min_frame,
last_frame_began: None,
}))
}),
)
+17
View File
@@ -65,6 +65,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) {
}
}
/// Keep File Info's metadata templates in the `Metadata Templates` folder, which a saved template
/// makes.
pub fn attach_metadata_templates_dir(session: &mut vectorcraft_engine::Session) {
if let Some(dir) = store_dir("Metadata Templates") {
session.attach_metadata_templates_dir(dir);
}
}
/// Have File › New start each category's documents from its profile in the `New Document
/// Profiles` folder, which `file.newProfiles.edit` makes.
pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) {
@@ -73,6 +81,15 @@ pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) {
}
}
/// 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.
pub fn attach_script_data(session: &mut vectorcraft_engine::Session) {
if let Some(dir) = store_dir("Script Data") {
session.attach_script_data(dir);
}
}
/// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from
/// now on there. After the preferences were restored: the folder is the one place the presets live.
pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) {
+123 -15
View File
@@ -6,9 +6,17 @@
//! frames the swap chain may queue, 1 to 3. Unset, the app keeps its own surface settings. A flag
//! overrides its variable; a value that isn't one of these stops the app with a message, as
//! `--control` does. A launch that sets either one runs as its own app, as with `--new-instance`.
//! The surface the app asks for is logged at start-up.
//! Preferences › Performance › Low-Latency Drawing (`lowLatencyDrawing`, off by default, read at
//! start-up) asks for `novsync` when neither the flag nor the variable sets the mode. Whenever the
//! surface presents without vsync, frames start at most 240 times a second. The surface the app
//! asks for is logged at start-up, with where its present mode came from.
use std::ffi::OsString;
use std::time::Duration;
/// The most frames a second the window draws while it presents without vsync.
#[cfg(feature = "wgpu")]
pub const UNSYNCED_FRAME_CAP: u32 = 240;
/// A present mode the command line or the environment can ask for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -54,6 +62,7 @@ fn flag_value(flag: &str, arg: &str, args: &mut impl Iterator<Item = String>) ->
impl Overrides {
/// Whether a flag or a variable set the present mode or the frame latency.
#[cfg_attr(target_os = "macos", allow(dead_code))] // its one caller, in `main`, is not built on macOS
pub fn is_set(&self) -> bool {
*self != Self::default()
}
@@ -95,25 +104,44 @@ impl Overrides {
Ok(Self { mode, latency })
}
/// `surface` with the overrides applied.
/// `surface` with the overrides applied. With Low-Latency Drawing on (`low_latency_drawing`) and
/// no present mode override, the mode is `novsync`.
#[cfg(feature = "wgpu")]
pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig) -> eframe::egui_wgpu::SurfaceConfig {
pub fn apply(&self, surface: eframe::egui_wgpu::SurfaceConfig, low_latency_drawing: bool) -> eframe::egui_wgpu::SurfaceConfig {
use eframe::wgpu::PresentMode;
let present_mode = match self.mode {
Some(Mode::Fifo) => PresentMode::Fifo,
Some(Mode::AutoVsync) => PresentMode::AutoVsync,
Some(Mode::NoVsync) => PresentMode::AutoNoVsync,
None if low_latency_drawing => PresentMode::AutoNoVsync,
None => surface.present_mode,
};
eframe::egui_wgpu::SurfaceConfig { present_mode, desired_maximum_frame_latency: self.latency.or(surface.desired_maximum_frame_latency) }
}
}
/// The present mode and frame latency `surface` asks for, for the start-up log:
/// "autovsync, frame latency 1", with "(override)"
/// after a value a flag or variable set.
/// The shortest time between the starts of two frames on `surface`: `None` with vsync, where the
/// display paces the frames, and 1/[`UNSYNCED_FRAME_CAP`] of a second without it.
#[cfg(feature = "wgpu")]
pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides) -> String {
pub fn min_frame_interval(surface: &eframe::egui_wgpu::SurfaceConfig) -> Option<Duration> {
use eframe::wgpu::PresentMode;
match surface.present_mode {
PresentMode::AutoNoVsync | PresentMode::Immediate | PresentMode::Mailbox => Some(Duration::from_secs(1) / UNSYNCED_FRAME_CAP),
PresentMode::AutoVsync | PresentMode::Fifo | PresentMode::FifoRelaxed => None,
}
}
/// How long a frame waits before it starts, `since_last` after the previous frame started, so that
/// frames start at least `min` apart. `None`: no wait (no cap, the first frame, or `min` has passed).
pub fn frame_wait(min: Option<Duration>, since_last: Option<Duration>) -> Option<Duration> {
min?.checked_sub(since_last?).filter(|wait| !wait.is_zero())
}
/// The present mode and frame latency `surface` asks for, for the start-up log:
/// "autovsync, frame latency 1", with "(override)" after a value a flag or variable set, and
/// "(preference)" after a present mode Low-Latency Drawing set.
#[cfg(feature = "wgpu")]
pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Overrides, low_latency_drawing: bool) -> String {
use eframe::wgpu::PresentMode;
let mode = match surface.present_mode {
PresentMode::AutoVsync => "autovsync",
@@ -125,7 +153,8 @@ pub fn describe(surface: &eframe::egui_wgpu::SurfaceConfig, overrides: &Override
};
let latency = surface.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string());
let tag = |set: bool| if set { " (override)" } else { "" };
format!("{mode}{}, frame latency {latency}{}", tag(overrides.mode.is_some()), tag(overrides.latency.is_some()))
let mode_tag = if overrides.mode.is_none() && low_latency_drawing { " (preference)" } else { tag(overrides.mode.is_some()) };
format!("{mode}{mode_tag}, frame latency {latency}{}", tag(overrides.latency.is_some()))
}
#[cfg(test)]
@@ -223,20 +252,99 @@ mod tests {
use eframe::wgpu::PresentMode;
let app = SurfaceConfig::LOW_LATENCY;
// No override: the surface the app asks for is unchanged.
assert_eq!(Overrides::default().apply(app), app);
assert_eq!(Overrides::default().apply(app, false), app);
let latency = Overrides { mode: None, latency: Some(2) };
let s = latency.apply(app);
let s = latency.apply(app, false);
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoVsync, Some(2)));
assert_eq!(describe(&s, &latency), "autovsync, frame latency 2 (override)");
assert_eq!(describe(&s, &latency, false), "autovsync, frame latency 2 (override)");
let fifo = Overrides { mode: Some(Mode::Fifo), latency: None };
let s = fifo.apply(app);
let s = fifo.apply(app, false);
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::Fifo, app.desired_maximum_frame_latency));
// Never a mode the driver may lack: no vsync lets wgpu fall back by support.
let novsync = Overrides { mode: Some(Mode::NoVsync), latency: Some(3) };
let s = novsync.apply(app);
let s = novsync.apply(app, false);
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(3)));
assert_eq!(describe(&s, &novsync), "novsync (override), frame latency 3 (override)");
assert_eq!(describe(&s, &novsync, false), "novsync (override), frame latency 3 (override)");
let unset = SurfaceConfig { present_mode: PresentMode::Fifo, desired_maximum_frame_latency: None };
assert_eq!(describe(&unset, &Overrides::default()), "fifo, frame latency default");
assert_eq!(describe(&unset, &Overrides::default(), false), "fifo, frame latency default");
}
/// Low-Latency Drawing alone asks for no vsync, through wgpu's fallback by support and never an
/// explicit Immediate or Mailbox; off, the app's surface is exactly its own.
#[cfg(feature = "wgpu")]
#[test]
fn low_latency_drawing_alone_presents_without_vsync_and_off_keeps_the_app_surface() {
use eframe::egui_wgpu::SurfaceConfig;
use eframe::wgpu::PresentMode;
let app = SurfaceConfig::LOW_LATENCY;
let none = Overrides::default();
assert_eq!(none.apply(app, false), app);
let s = none.apply(app, true);
assert_eq!(s.present_mode, PresentMode::AutoNoVsync);
assert_eq!(s.desired_maximum_frame_latency, app.desired_maximum_frame_latency);
let frames = app.desired_maximum_frame_latency.map_or("default".to_string(), |n| n.to_string());
assert_eq!(describe(&s, &none, true), format!("novsync (preference), frame latency {frames}"));
// A latency override still applies with the preference's mode.
let latency = Overrides { mode: None, latency: Some(2) };
let s = latency.apply(app, true);
assert_eq!((s.present_mode, s.desired_maximum_frame_latency), (PresentMode::AutoNoVsync, Some(2)));
assert_eq!(describe(&s, &latency, true), "novsync (preference), frame latency 2 (override)");
}
/// The flag and the variable each set the present mode over Low-Latency Drawing.
#[cfg(feature = "wgpu")]
#[test]
fn the_flag_and_the_variable_win_over_low_latency_drawing() {
use eframe::egui_wgpu::SurfaceConfig;
use eframe::wgpu::PresentMode;
let app = SurfaceConfig::LOW_LATENCY;
let flag = parse(&["--present-mode", "fifo"]).unwrap();
let s = flag.apply(app, true);
assert_eq!(s.present_mode, PresentMode::Fifo);
assert!(describe(&s, &flag, true).starts_with("fifo (override),"), "{}", describe(&s, &flag, true));
let var = Overrides::default().with_env(Some("autovsync".into()), None).unwrap();
let s = var.apply(app, true);
assert_eq!(s.present_mode, PresentMode::AutoVsync);
assert!(describe(&s, &var, true).starts_with("autovsync (override),"), "{}", describe(&s, &var, true));
// The flag wins over the variable, and both over the preference.
let both = parse(&["--present-mode=fifo"]).unwrap().with_env(Some("novsync".into()), None).unwrap();
assert_eq!(both.apply(app, true).present_mode, PresentMode::Fifo);
}
/// Frames start at most 240 times a second without vsync, from the preference or an override,
/// and the display paces them with vsync.
#[cfg(feature = "wgpu")]
#[test]
fn the_frame_cap_applies_only_without_vsync_at_240_frames_a_second() {
use eframe::egui_wgpu::SurfaceConfig;
use eframe::wgpu::PresentMode;
let app = SurfaceConfig::LOW_LATENCY;
let cap = Duration::from_secs(1) / 240;
assert_eq!(cap.as_nanos(), 4_166_666);
assert_eq!(min_frame_interval(&Overrides::default().apply(app, true)), Some(cap));
assert_eq!(min_frame_interval(&Overrides { mode: Some(Mode::NoVsync), latency: None }.apply(app, false)), Some(cap));
assert_eq!(min_frame_interval(&Overrides::default().apply(app, false)), None);
assert_eq!(min_frame_interval(&Overrides { mode: Some(Mode::Fifo), latency: None }.apply(app, true)), None);
for (mode, capped) in [
(PresentMode::Immediate, true),
(PresentMode::Mailbox, true),
(PresentMode::AutoNoVsync, true),
(PresentMode::Fifo, false),
(PresentMode::FifoRelaxed, false),
(PresentMode::AutoVsync, false),
] {
let s = SurfaceConfig { present_mode: mode, desired_maximum_frame_latency: Some(1) };
assert_eq!(min_frame_interval(&s).is_some(), capped, "{mode:?}");
}
}
#[test]
fn a_frame_waits_out_the_rest_of_the_minimum_interval() {
let min = Some(Duration::from_millis(4));
assert_eq!(frame_wait(min, Some(Duration::from_millis(1))), Some(Duration::from_millis(3)));
assert_eq!(frame_wait(min, Some(Duration::from_millis(4))), None);
assert_eq!(frame_wait(min, Some(Duration::from_millis(9))), None);
assert_eq!(frame_wait(min, None), None, "the first frame starts at once");
assert_eq!(frame_wait(None, Some(Duration::ZERO)), None, "no cap with vsync");
}
}
+37 -5
View File
@@ -3,15 +3,16 @@
use std::process::Command;
use vectorcraft_ui_egui::print::{PrintJob, PrintService, Printer};
mod direct_pdf;
pub struct SystemPrint;
impl PrintService for SystemPrint {
fn printers(&mut self) -> Vec<Printer> {
system::printers()
}
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
let result = system::print(job);
let to = job.printer.unwrap_or("the default printer");
result.map(|note| format!("Sent “{}” to {to}{note}", job.title))
let note = system::print(job)?;
Ok(sent(job.title, job.printer, &note))
}
fn shared_print(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintFn> {
Some(std::sync::Arc::new(|job| SystemPrint.print(job)))
@@ -29,16 +30,28 @@ impl PrintService for SystemPrint {
}
}
/// The status after the job `title` went to `printer` (the default one without a name), with the
/// spooler's `note` when it gave one. Each message has text between its values, so a catalog can
/// match it and translate it. The note follows as its own sentence: a printer name can end in
/// parentheses ("HP LaserJet (Copy 1)"), and a note in parentheses would match that name.
fn sent(title: &str, printer: Option<&str>, note: &str) -> String {
let to = printer.unwrap_or("the default printer");
if note.is_empty() { format!("Sent “{title}” to {to}") } else { format!("Sent “{title}” to {to}. The spooler replied: {note}") }
}
mod system {
use super::{Command, PrintJob, Printer};
pub fn printers() -> Vec<Printer> {
craft_print::printers().into_iter().map(|p| Printer { name: p.name, default: p.default }).collect()
}
pub fn print(job: &PrintJob) -> Result<String, String> {
if job.direct_pdf {
return super::direct_pdf::print(job);
}
// Copies, layout, marks and colour management are already in the PDF. Preserve its
// physical sheet size and the queue's duplex default without printing copies twice.
let settings = craft_print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() };
craft_print::submit(job.pdf, &settings).map(|note| if note.is_empty() { note } else { format!(" ({note})") }).map_err(|e| e.to_string())
craft_print::submit(job.pdf, &settings).map_err(|e| e.to_string())
}
#[cfg(windows)]
pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command {
@@ -127,9 +140,28 @@ mod tests {
#[cfg(test)]
mod turn_tests {
use super::SystemPrint;
use super::{SystemPrint, sent};
use vectorcraft_ui_egui::print::PrintService;
#[test]
fn the_sent_status_names_the_job_the_printer_and_the_note() {
assert_eq!(sent("Poster", None, ""), "Sent “Poster” to the default printer");
assert_eq!(sent("Poster", Some("Office Laser"), ""), "Sent “Poster” to Office Laser");
assert_eq!(sent("Poster", Some("Office Laser"), "job 12"), "Sent “Poster” to Office Laser. The spooler replied: job 12");
}
#[test]
fn a_printer_name_ending_in_parentheses_stays_whole_in_a_translation() {
use vectorcraft_ui_egui::i18n::{Lang, message};
let Some(de) = Lang::from_code("de") else { panic!("no German catalog") };
let printer = Some("HP LaserJet (Copy 1)");
assert_eq!(message(de, &sent("Poster", printer, "")), "“Poster” an HP LaserJet (Copy 1) gesendet");
assert_eq!(
message(de, &sent("Poster", printer, "job 12")),
"“Poster” an HP LaserJet (Copy 1) gesendet. Antwort der Druckwarteschlange: job 12"
);
}
#[test]
fn only_macos_queues_need_landscape_pages_turned() {
assert_eq!(SystemPrint.turns_landscape(), !cfg!(target_os = "macos"));
+127
View File
@@ -0,0 +1,127 @@
//! Send the print-ready PDF to the printer's own PDF interpreter over its RAW TCP port.
//!
//! This is the opt-in escape hatch for large-format PCL drivers that rewrite a custom page
//! (the HP DesignJet Z5200ps V4 driver emits a square PCL page for a 1067 x 480 mm sheet). The
//! PDF already carries the paper size, so the printer's interpreter prints it as laid out.
#[cfg(windows)]
mod imp {
use std::io::Write;
use std::net::{Shutdown, TcpStream, ToSocketAddrs};
use std::time::Duration;
use vectorcraft_ui_egui::print::PrintJob;
use winreg::RegKey;
use winreg::enums::{HKEY_LOCAL_MACHINE, KEY_READ};
/// Submit one composed PDF to the selected printer's Standard TCP/IP RAW port.
pub fn print(job: &PrintJob) -> Result<String, String> {
let printer = job
.printer
.map(str::to_string)
.or_else(|| craft_print::printers().into_iter().find(|p| p.default).map(|p| p.name))
.ok_or("direct PDF needs a selected printer")?;
let (host, port) = tcp_port(&printer)?;
send(&host, port, &pjl(job.title, job.pdf))?;
Ok(format!(" (direct PDF to {host}:{port})"))
}
/// The `HostName` and port of a printer port registered as a Standard TCP/IP RAW port.
fn tcp_port(printer: &str) -> Result<(String, u16), String> {
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let printer_key = hklm
.open_subkey_with_flags(format!(r"SYSTEM\CurrentControlSet\Control\Print\Printers\{printer}"), KEY_READ)
.map_err(|e| format!("direct PDF: cannot read the printer settings for {printer}: {e}"))?;
let port_name: String = printer_key.get_value("Port").map_err(|e| format!("direct PDF: {printer} has no port: {e}"))?;
let port_key = hklm
.open_subkey_with_flags(format!(r"SYSTEM\CurrentControlSet\Control\Print\Monitors\Standard TCP/IP Port\Ports\{port_name}"), KEY_READ)
.map_err(|e| format!("direct PDF: {printer} does not use a Standard TCP/IP port ({port_name}): {e}"))?;
let protocol: u32 = port_key.get_value("Protocol").unwrap_or(1);
if protocol != 1 {
return Err(format!("direct PDF: {printer}'s port ({port_name}) is not a RAW TCP/IP port"));
}
let host = port_key
.get_value::<String, _>("HostName")
.ok()
.filter(|h| !h.trim().is_empty())
.or_else(|| port_key.get_value::<String, _>("IPAddress").ok().filter(|h| !h.trim().is_empty()))
.ok_or_else(|| format!("direct PDF: {printer}'s port ({port_name}) has no host address"))?;
let number = port_key.get_value::<u32, _>("PortNumber").unwrap_or(9100);
let port = u16::try_from(number).map_err(|_| format!("direct PDF: invalid port number {number}"))?;
Ok((host.trim().to_string(), port))
}
/// Frame the PDF for the printer's PJL interpreter.
fn pjl(title: &str, pdf: &[u8]) -> Vec<u8> {
let mut name: String = title.chars().map(|c| if (c.is_ascii_graphic() || c == ' ') && c != '"' { c } else { '_' }).take(80).collect();
if name.is_empty() {
name.push_str("VectorCraft");
}
let mut out = Vec::with_capacity(pdf.len() + 96);
out.extend_from_slice(b"\x1b%-12345X@PJL JOB NAME=\"");
out.extend_from_slice(name.as_bytes());
out.extend_from_slice(b"\"\r\n@PJL ENTER LANGUAGE=PDF\r\n");
out.extend_from_slice(pdf);
out.extend_from_slice(b"\r\n\x1b%-12345X@PJL EOJ\r\n");
out
}
/// Stream `data` to the first reachable address of `host:port`.
fn send(host: &str, port: u16, data: &[u8]) -> Result<(), String> {
let addrs = (host, port).to_socket_addrs().map_err(|e| format!("direct PDF: cannot resolve {host}: {e}"))?;
let mut last = None;
for addr in addrs {
match TcpStream::connect_timeout(&addr, Duration::from_secs(10)) {
Ok(mut stream) => {
stream.set_write_timeout(Some(Duration::from_secs(120))).map_err(|e| format!("direct PDF: {e}"))?;
stream.write_all(data).map_err(|e| format!("direct PDF: writing to {host}:{port} failed: {e}"))?;
stream.shutdown(Shutdown::Write).map_err(|e| format!("direct PDF: finishing {host}:{port} failed: {e}"))?;
return Ok(());
}
Err(e) => last = Some(e),
}
}
Err(match last {
Some(e) => format!("direct PDF: cannot connect to {host}:{port}: {e}"),
None => format!("direct PDF: {host}:{port} has no addresses"),
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Read;
use std::net::TcpListener;
#[test]
fn the_pjl_frames_the_pdf() {
let out = pjl("witch hat\"", b"%PDF-1.7");
let text = String::from_utf8_lossy(&out);
assert!(text.starts_with("\u{1b}%-12345X@PJL JOB NAME=\"witch hat_\"\r\n@PJL ENTER LANGUAGE=PDF\r\n"));
assert!(text.contains("%PDF-1.7"));
assert!(text.ends_with("\r\n\u{1b}%-12345X@PJL EOJ\r\n"));
}
#[test]
fn the_pdf_reaches_a_listening_port() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let t = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut got = Vec::new();
stream.read_to_end(&mut got).unwrap();
got
});
send("127.0.0.1", port, b"%PDF-1.7 test").unwrap();
assert_eq!(t.join().unwrap(), b"%PDF-1.7 test");
}
}
}
#[cfg(windows)]
pub use imp::print;
#[cfg(not(windows))]
pub fn print(_: &vectorcraft_ui_egui::print::PrintJob) -> Result<String, String> {
Err("direct PDF printing is only available on Windows".into())
}
+4 -4
View File
@@ -78,7 +78,7 @@ impl Monitor {
let scale = self.scale * zoom;
let [x, y] = self.pos;
let [w, h] = self.size;
DockMonitor { name, rect: [x, y, w, h].map(|v| v as f32 / scale), scale }
DockMonitor { name, rect: [x, y, w, h].map(|v| v as f32 / scale), scale, work_area: None }
}
}
@@ -248,13 +248,13 @@ mod tests {
fn floating_panels_get_monitors_in_the_points_a_window_on_them_reports() {
let dock = |m: Monitor, zoom| m.docking(Some("m".into()), zoom);
let plain = dock(monitor(1920, 0, 1920, 1080, 1.0), 1.0);
assert_eq!(plain, DockMonitor { name: Some("m".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0 });
assert_eq!(plain, DockMonitor { name: Some("m".into()), rect: [1920.0, 0.0, 1920.0, 1080.0], scale: 1.0, work_area: None });
// A window at (3000, 200) on this monitor reports (1500, 100).
let scaled = dock(monitor(1920, -200, 3840, 2160, 2.0), 1.0);
assert_eq!(scaled, DockMonitor { name: Some("m".into()), rect: [960.0, -100.0, 1920.0, 1080.0], scale: 2.0 });
assert_eq!(scaled, DockMonitor { name: Some("m".into()), rect: [960.0, -100.0, 1920.0, 1080.0], scale: 2.0, work_area: None });
// The UI zoom divides what egui reports as well.
let zoomed = dock(monitor(-2560, 0, 2560, 1440, 1.0), 1.25);
assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25 });
assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25, work_area: None });
}
#[test]
@@ -0,0 +1,655 @@
//! Windows: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`). Windows has no system
//! color sampler, so a thread of its own copies the virtual screen, the bounding rectangle of all
//! the monitors (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getsystemmetrics>),
//! into a bitmap with `BitBlt` from the screen's device context
//! (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdc>), then covers
//! the virtual screen with a borderless topmost window that shows that copy under a crosshair
//! cursor. The window has its own message loop on that thread, so the UI keeps drawing.
//!
//! A left click answers the copied pixel under the pointer as sRGB; Escape, a click of any other
//! button, closing the window, and the window losing the keyboard focus or the mouse capture answer
//! `None`. Each
//! click is answered when its button is released, so the release does not reach the window
//! underneath. The color comes from the copy taken before the window was shown, so the window
//! never samples itself, and moving content shows the frame it had when the copy was taken.
//!
//! The pixels are 8-bit GDI colors, read as sRGB: GDI content is taken to be sRGB when the display
//! does not use Advanced Color
//! (<https://learn.microsoft.com/en-us/windows/win32/wcs/advanced-color-icc-profiles>). The colors
//! of HDR and wide-gamut displays are not converted.
//!
//! winit makes the process per-monitor DPI aware, so the virtual screen, the pointer and the copy
//! are in physical pixels on every monitor, whatever its scale, and a monitor left of or above the
//! main one has negative coordinates
//! (<https://learn.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows>).
//!
//! The Win32 calls have no safe binding; [`overlay`] allows `unsafe_code`.
#![cfg_attr(not(windows), allow(dead_code))]
/// The status message for every failure; the details go to the log.
const FAILED: &str = "the screen color sampler failed";
/// The largest copy of the virtual screen, in bytes of 32-bit pixels: 1 GiB, eight 7680 × 4320
/// monitors. VectorCraft's own limit.
const MAX_SNAPSHOT_BYTES: u64 = 1 << 30;
/// `CLR_INVALID` (`wingdi.h`): what `GetPixel` answers for a pixel it can't read.
const CLR_INVALID: u32 = 0xFFFF_FFFF;
/// The virtual screen in physical pixels: its top-left corner (negative when a monitor is left of
/// or above the main one) and its size.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct VirtualScreen {
left: i32,
top: i32,
width: i32,
height: i32,
}
impl VirtualScreen {
/// The virtual screen `GetSystemMetrics` reports, checked before any memory is taken for its
/// copy: an error when it is empty, larger than [`MAX_SNAPSHOT_BYTES`], or reaches past the
/// coordinates Windows can address.
fn new(left: i32, top: i32, width: i32, height: i32) -> Result<Self, String> {
if width <= 0 || height <= 0 {
return Err(format!("the virtual screen is {width} × {height} pixels"));
}
let bytes = u64::from(width.unsigned_abs()).saturating_mul(u64::from(height.unsigned_abs())).saturating_mul(4);
if bytes > MAX_SNAPSHOT_BYTES {
return Err(format!("the virtual screen ({width} × {height} pixels) is larger than the {MAX_SNAPSHOT_BYTES}-byte limit"));
}
if left.checked_add(width).is_none() || top.checked_add(height).is_none() {
return Err(format!("the virtual screen at ({left}, {top}) reaches past the coordinate range"));
}
Ok(Self { left, top, width, height })
}
/// The pixel of the copy at the screen point (`x`, `y`), or `None` when the point is outside the
/// virtual screen.
fn pixel(&self, x: i32, y: i32) -> Option<(i32, i32)> {
let (px, py) = (x.checked_sub(self.left)?, y.checked_sub(self.top)?);
((0..self.width).contains(&px) && (0..self.height).contains(&py)).then_some((px, py))
}
}
/// The sRGB components (0 to 1) of a `COLORREF` (`0x00bbggrr`), or `None` for `CLR_INVALID` or any
/// other value with its high byte set.
fn srgb(colorref: u32) -> Option<[f32; 3]> {
if colorref == CLR_INVALID {
return None;
}
let [r, g, b, high] = colorref.to_le_bytes();
(high == 0).then(|| [r, g, b].map(|v| f32::from(v) / 255.0))
}
/// The client point of a mouse message. Its `lParam` holds each coordinate as a signed 16-bit
/// value (`GET_X_LPARAM` and `GET_Y_LPARAM`,
/// <https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-lbuttonup>), so a coordinate past
/// 32,767 pixels in a wide virtual screen loses its high bits. Each coordinate becomes the value
/// with the same low 16 bits nearest to `near`, the message's own pointer position (`MSG.pt`,
/// <https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-msg>) in client
/// coordinates.
fn message_point(lparam: isize, near: (i32, i32)) -> (i32, i32) {
let widen = |low: i16, near: i32| near.saturating_add(i32::from(i32::from(low).wrapping_sub(near) as i16));
(widen(lparam as i16, near.0), widen((lparam >> 16) as i16, near.1))
}
/// A mouse button: the left one picks, and any other one cancels.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Button {
Left,
Right,
/// The middle button or a side button.
Other,
}
/// What the person did in the sampler's window.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Input {
Down(Button),
Up(Button),
Escape,
/// The window became the active window.
Activated,
/// The window stopped being the active window.
Deactivated,
/// Another window took the mouse capture.
CaptureLost,
/// The window was asked to close (Alt+F4).
Closed,
}
/// What the sampler does next.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Step {
Wait,
Pick,
Cancel,
}
/// The mouse button last pressed in the window, and whether the window has been active.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct Press {
down: Option<Button>,
active: bool,
}
impl Press {
/// A release picks or cancels only after its button went down in the window. Losing the focus
/// cancels only after the window had it, so a window that never became active still takes a
/// click.
fn step(&mut self, input: Input) -> Step {
match input {
Input::Down(button) => {
self.down = Some(button);
Step::Wait
}
Input::Up(button) if self.down == Some(button) => {
if button == Button::Left {
Step::Pick
} else {
Step::Cancel
}
}
Input::Up(_) => Step::Wait,
Input::Activated => {
self.active = true;
Step::Wait
}
Input::Deactivated if !self.active => Step::Wait,
Input::Escape | Input::Deactivated | Input::CaptureLost | Input::Closed => Step::Cancel,
}
}
}
/// The screen color sampler; `ui` is woken when it answers.
#[cfg(windows)]
pub fn sampler(ui: egui::Context) -> vectorcraft_ui_egui::screen_color::StartSampler {
Box::new(move || {
let (tx, rx) = std::sync::mpsc::channel();
let ui = ui.clone();
std::thread::Builder::new()
.name("screen-color".into())
.spawn(move || {
let answer = overlay::run().map_err(|detail| {
log::warn!("the screen color sampler gave no color: {detail}");
FAILED.to_string()
});
// The UI may be gone (the app quitting): nothing waits for the color then.
let _ = tx.send(answer);
ui.request_repaint();
})
.map_err(|e| {
log::warn!("could not start the screen color sampler's thread: {e}");
FAILED.to_string()
})?;
Ok(rx)
})
}
/// The copy of the virtual screen and the window that shows it, on the sampler's thread.
#[cfg(windows)]
mod overlay {
#![allow(unsafe_code)]
use std::cell::RefCell;
use std::sync::OnceLock;
use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, WPARAM};
use windows::Win32::Graphics::Gdi::{
BeginPaint, BitBlt, CAPTUREBLT, ClientToScreen, CreateCompatibleBitmap, CreateCompatibleDC, DeleteDC, DeleteObject, EndPaint, GetDC,
GetPixel, HBITMAP, HDC, HGDIOBJ, PAINTSTRUCT, ReleaseDC, SRCCOPY, SelectObject,
};
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::UI::Input::KeyboardAndMouse::{ReleaseCapture, SetCapture, VK_ESCAPE};
use windows::Win32::UI::WindowsAndMessaging::{
CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GetCursorPos, GetMessageW, GetSystemMetrics, HCURSOR, IDC_CROSS,
LoadCursorW, MSG, PostQuitMessage, RegisterClassExW, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SW_SHOW,
SetCursor, SetForegroundWindow, ShowWindow, TranslateMessage, WA_INACTIVE, WM_ACTIVATE, WM_CAPTURECHANGED, WM_CLOSE, WM_DESTROY,
WM_DPICHANGED, WM_ERASEBKGND, WM_KEYDOWN, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEMOVE, WM_PAINT, WM_RBUTTONDOWN,
WM_RBUTTONUP, WM_SETCURSOR, WM_XBUTTONDOWN, WM_XBUTTONUP, WNDCLASSEXW, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,
};
use windows::core::{PCWSTR, w};
use super::{Button, Input, Press, Step, VirtualScreen, message_point, srgb};
/// The window class of the sampler's window.
const CLASS: PCWSTR = w!("VectorCraftScreenColor");
/// The picked color, `None` when canceled, or the details of a failure.
type Picked = Result<Option<[f32; 3]>, String>;
/// A copy of the virtual screen in a memory device context. Dropping it frees the bitmap and
/// the device context.
struct Snapshot {
dc: HDC,
bitmap: HBITMAP,
/// The bitmap the device context held before [`Snapshot::bitmap`] replaced it.
old: HGDIOBJ,
}
impl Snapshot {
/// Copies `screen` from the screen's device context, which is released on this thread, as
/// `ReleaseDC` requires.
fn take(screen: VirtualScreen) -> Result<Self, String> {
// SAFETY: `GetDC(None)` takes no pointers; the device context is released below.
let screen_dc = unsafe { GetDC(None) };
if screen_dc.is_invalid() {
return Err("GetDC(NULL) gave no device context".into());
}
let copied = Self::copy(screen_dc, screen);
// SAFETY: the device context `GetDC(None)` gave on this thread, released once.
unsafe { ReleaseDC(None, screen_dc) };
copied
}
fn copy(screen_dc: HDC, s: VirtualScreen) -> Result<Self, String> {
// SAFETY: `screen_dc` is a live device context; a failure answers a null handle.
let dc = unsafe { CreateCompatibleDC(Some(screen_dc)) };
if dc.is_invalid() {
return Err("CreateCompatibleDC failed".into());
}
// SAFETY: as above; the size was checked by `VirtualScreen::new`.
let bitmap = unsafe { CreateCompatibleBitmap(screen_dc, s.width, s.height) };
if bitmap.is_invalid() {
// SAFETY: the device context made above, deleted once.
unsafe {
let _ = DeleteDC(dc);
}
return Err(format!("CreateCompatibleBitmap gave no {} × {} bitmap", s.width, s.height));
}
// SAFETY: both handles are live and made above.
let old = unsafe { SelectObject(dc, bitmap.into()) };
if old.is_invalid() {
// SAFETY: the handles made above, deleted once.
unsafe {
let _ = DeleteObject(bitmap.into());
let _ = DeleteDC(dc);
}
return Err("SelectObject failed".into());
}
let snapshot = Self { dc, bitmap, old };
// SAFETY: both device contexts are live; the rectangle is the virtual screen.
unsafe { BitBlt(dc, 0, 0, s.width, s.height, Some(screen_dc), s.left, s.top, SRCCOPY | CAPTUREBLT) }
.map_err(|e| format!("BitBlt of the virtual screen failed: {e}"))?;
Ok(snapshot)
}
/// The `COLORREF` of the copy's pixel (`x`, `y`).
fn colorref(&self, x: i32, y: i32) -> u32 {
// SAFETY: the device context is live while `self` is; GetPixel checks the coordinates.
unsafe { GetPixel(self.dc, x, y) }.0
}
}
impl Drop for Snapshot {
fn drop(&mut self) {
// SAFETY: the handles `copy` made, freed once, the bitmap after the device context
// lets go of it.
unsafe {
SelectObject(self.dc, self.old);
let _ = DeleteObject(self.bitmap.into());
let _ = DeleteDC(self.dc);
}
}
}
/// The sampler shown on this thread.
struct Session {
snapshot: Snapshot,
screen: VirtualScreen,
cursor: HCURSOR,
press: Press,
/// The pointer position, in screen coordinates, of the message being dispatched (`MSG.pt`).
message_pt: Option<POINT>,
/// The answer, set once.
answer: Option<Picked>,
/// The window has been destroyed.
destroyed: bool,
}
thread_local! {
static SESSION: RefCell<Option<Session>> = const { RefCell::new(None) };
}
/// Runs `f` on this thread's session, or answers `None` when there is none or it is in use.
/// Win32 calls that send messages to the window (which come back to [`window_proc`]) are made
/// outside it.
fn with<R>(f: impl FnOnce(&mut Session) -> R) -> Option<R> {
SESSION.with(|s| s.try_borrow_mut().ok()?.as_mut().map(f))
}
fn put(session: Option<Session>) -> Option<Session> {
SESSION.with(|s| s.try_borrow_mut().ok().map(|mut s| std::mem::replace(&mut *s, session)))?
}
/// Shows the sampler and waits for the person; answers on this thread.
pub(super) fn run() -> Picked {
// SAFETY: `GetSystemMetrics` takes no pointers.
let (left, top, width, height) = unsafe {
(
GetSystemMetrics(SM_XVIRTUALSCREEN),
GetSystemMetrics(SM_YVIRTUALSCREEN),
GetSystemMetrics(SM_CXVIRTUALSCREEN),
GetSystemMetrics(SM_CYVIRTUALSCREEN),
)
};
let screen = VirtualScreen::new(left, top, width, height)?;
let snapshot = Snapshot::take(screen)?;
register()?;
// SAFETY: a system cursor, loaded by its id.
let cursor = unsafe { LoadCursorW(None, IDC_CROSS) }.map_err(|e| format!("LoadCursorW: {e}"))?;
// Each sampler runs on a thread of its own, so the thread has no session yet.
let _ = put(Some(Session { snapshot, screen, cursor, press: Press::default(), message_pt: None, answer: None, destroyed: false }));
let shown = show(screen, cursor);
if let Ok(hwnd) = shown {
pump();
if with(|s| s.destroyed) == Some(false) {
// SAFETY: the window made by `show` on this thread, not yet destroyed.
let _ = unsafe { DestroyWindow(hwnd) };
}
}
let session = put(None);
shown?;
session.and_then(|s| s.answer).unwrap_or(Ok(None))
}
/// Registers the window class once for the process.
fn register() -> Result<(), String> {
static REGISTERED: OnceLock<Result<(), String>> = OnceLock::new();
REGISTERED
.get_or_init(|| {
// SAFETY: the module handle of this program; it is not freed.
let instance = unsafe { GetModuleHandleW(None) }.map_err(|e| format!("GetModuleHandleW: {e}"))?;
let class = WNDCLASSEXW {
cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
lpfnWndProc: Some(window_proc),
hInstance: instance.into(),
lpszClassName: CLASS,
..Default::default()
};
// SAFETY: `class` is a complete `WNDCLASSEXW` whose strings are static.
if unsafe { RegisterClassExW(&class) } == 0 {
return Err(format!("RegisterClassExW: {}", windows::core::Error::from_thread()));
}
Ok(())
})
.clone()
}
/// Shows the window over the virtual screen in front of every other window and takes the mouse.
fn show(s: VirtualScreen, cursor: HCURSOR) -> Result<HWND, String> {
// SAFETY: the module handle of this program; it is not freed.
let instance = unsafe { GetModuleHandleW(None) }.map_err(|e| format!("GetModuleHandleW: {e}"))?;
// SAFETY: the class was registered by `register`; the strings are static.
let hwnd = unsafe {
CreateWindowExW(
WS_EX_TOPMOST | WS_EX_TOOLWINDOW,
CLASS,
w!("Sample Color from Screen"),
WS_POPUP,
s.left,
s.top,
s.width,
s.height,
None,
None,
Some(instance.into()),
None,
)
}
.map_err(|e| format!("CreateWindowExW: {e}"))?;
// SAFETY: the window made above, on this thread.
unsafe {
let _ = ShowWindow(hwnd, SW_SHOW);
let _ = SetForegroundWindow(hwnd);
SetCapture(hwnd);
SetCursor(Some(cursor));
}
Ok(hwnd)
}
/// The window's message loop, until the window is destroyed.
fn pump() {
let mut msg = MSG::default();
// SAFETY: `msg` is a valid `MSG` for each call. `GetMessageW` answers 0 for `WM_QUIT` and -1
// for an error; both end the loop.
while unsafe { GetMessageW(&mut msg, None, 0, 0) }.0 > 0 {
with(|s| s.message_pt = Some(msg.pt));
// SAFETY: the message `GetMessageW` just filled in.
unsafe {
let _ = TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
}
/// Answers once, then lets go of the mouse and destroys the window.
fn finish(hwnd: HWND, answer: impl FnOnce(&mut Session) -> Picked) {
let first = with(|s| {
let first = s.answer.is_none();
if first {
s.answer = Some(answer(s));
}
first
});
if first == Some(true) {
// SAFETY: the window on this thread; both calls send messages that `window_proc`
// handles outside the session.
unsafe {
let _ = ReleaseCapture();
let _ = DestroyWindow(hwnd);
}
}
}
/// The copy's color at the point where the left button was released: `lparam` of that
/// `WM_LBUTTONUP`, in `hwnd`'s client coordinates, not where the pointer is now. The pointer's
/// current position stands in for `MSG.pt` only when the release was not dispatched by
/// [`pump`].
fn pick(s: &mut Session, hwnd: HWND, lparam: LPARAM) -> Picked {
let mut origin = POINT::default();
// SAFETY: the window on this thread and a valid `POINT`; the call sends no message.
unsafe { ClientToScreen(hwnd, &mut origin) }.ok().map_err(|e| format!("ClientToScreen: {e}"))?;
let pt = match s.message_pt {
Some(pt) => pt,
None => {
let mut now = POINT::default();
// SAFETY: `now` is a valid `POINT`.
unsafe { GetCursorPos(&mut now) }.map_err(|e| format!("GetCursorPos: {e}"))?;
now
}
};
let near = (pt.x.wrapping_sub(origin.x), pt.y.wrapping_sub(origin.y));
let (cx, cy) = message_point(lparam.0, near);
let at = POINT { x: cx.saturating_add(origin.x), y: cy.saturating_add(origin.y) };
let (x, y) = s.screen.pixel(at.x, at.y).ok_or_else(|| format!("the release at ({}, {}) is outside the virtual screen", at.x, at.y))?;
let colorref = s.snapshot.colorref(x, y);
srgb(colorref).map(Some).ok_or_else(|| format!("GetPixel({x}, {y}) answered {colorref:#010x}"))
}
/// Draws the copy where the virtual screen is, wherever the window's client area is.
fn paint(hwnd: HWND) {
let copy = with(|s| (s.snapshot.dc, s.screen));
let mut ps = PAINTSTRUCT::default();
let mut origin = POINT::default();
// SAFETY: the window on this thread, with a `PAINTSTRUCT` for `BeginPaint` and `EndPaint`;
// the copy's device context lives as long as the session.
unsafe {
let _ = ClientToScreen(hwnd, &mut origin);
let target = BeginPaint(hwnd, &mut ps);
if let Some((dc, s)) = copy
&& !target.is_invalid()
{
let _ = BitBlt(target, s.left.saturating_sub(origin.x), s.top.saturating_sub(origin.y), s.width, s.height, Some(dc), 0, 0, SRCCOPY);
}
let _ = EndPaint(hwnd, &ps);
}
}
/// What `msg` means for the sampler.
fn input(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> Option<Input> {
match msg {
WM_LBUTTONDOWN => Some(Input::Down(Button::Left)),
WM_LBUTTONUP => Some(Input::Up(Button::Left)),
WM_RBUTTONDOWN => Some(Input::Down(Button::Right)),
WM_RBUTTONUP => Some(Input::Up(Button::Right)),
WM_MBUTTONDOWN | WM_XBUTTONDOWN => Some(Input::Down(Button::Other)),
WM_MBUTTONUP | WM_XBUTTONUP => Some(Input::Up(Button::Other)),
WM_KEYDOWN if wparam.0 == usize::from(VK_ESCAPE.0) => Some(Input::Escape),
WM_ACTIVATE if wparam.0 & 0xFFFF == WA_INACTIVE as usize => Some(Input::Deactivated),
WM_ACTIVATE => Some(Input::Activated),
// `lParam` is the window that takes the capture.
WM_CAPTURECHANGED if lparam.0 != hwnd.0 as isize => Some(Input::CaptureLost),
WM_CLOSE => Some(Input::Closed),
_ => None,
}
}
unsafe extern "system" fn window_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
// Activation also gives the window the keyboard focus, for Escape.
// SAFETY: the arguments Windows passed in, for the window on this thread.
let result = if msg == WM_ACTIVATE { unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) } } else { LRESULT(0) };
if let Some(input) = input(hwnd, msg, wparam, lparam) {
match with(|s| s.press.step(input)) {
Some(Step::Pick) => finish(hwnd, |s| pick(s, hwnd, lparam)),
Some(Step::Cancel) => finish(hwnd, |_| Ok(None)),
Some(Step::Wait) | None => {}
}
return result;
}
match msg {
WM_SETCURSOR | WM_MOUSEMOVE => {
// The cursor is set by hand: a window with the mouse capture gets no WM_SETCURSOR.
if let Some(cursor) = with(|s| s.cursor) {
// SAFETY: a system cursor loaded by `run`.
unsafe { SetCursor(Some(cursor)) };
}
LRESULT(1)
}
// The copy covers the whole window.
WM_ERASEBKGND => LRESULT(1),
WM_PAINT => {
paint(hwnd);
LRESULT(0)
}
// The window keeps covering the virtual screen when it reaches a monitor of another scale.
WM_DPICHANGED => LRESULT(0),
WM_DESTROY => {
with(|s| s.destroyed = true);
// SAFETY: ends this thread's message loop.
unsafe { PostQuitMessage(0) };
LRESULT(0)
}
// SAFETY: the arguments Windows passed in, for the window on this thread.
_ => unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) },
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// `COLORREF` is `0x00bbggrr`: red in the low byte. `CLR_INVALID` and other values with the high
/// byte set are not colors.
#[test]
fn colorrefs_read_as_srgb() {
assert_eq!(srgb(0x0000_00FF), Some([1.0, 0.0, 0.0]));
assert_eq!(srgb(0x00FF_0000), Some([0.0, 0.0, 1.0]));
assert_eq!(srgb(0x0056_3412), Some([0x12, 0x34, 0x56].map(|v| v as f32 / 255.0)));
assert_eq!(srgb(0), Some([0.0; 3]));
assert_eq!(srgb(0x00FF_FFFF), Some([1.0; 3]));
assert_eq!(srgb(CLR_INVALID), None);
assert_eq!(srgb(0x0100_0000), None);
}
/// The pointer maps to the copy's pixels through the virtual screen's corner, which is negative
/// when a monitor is left of or above the main one. A 1920 × 1080 monitor at 100% left of and
/// lower than a 3840 × 2160 one at 150% gives a 5760 × 2160 virtual screen from (−1920, 0), in
/// physical pixels on both.
#[test]
fn screen_points_map_to_pixels_of_the_copy() {
let s = VirtualScreen::new(-1920, 0, 5760, 2160).unwrap();
assert_eq!(s.pixel(-1920, 0), Some((0, 0)));
assert_eq!(s.pixel(-1, 300), Some((1919, 300)));
assert_eq!(s.pixel(0, 0), Some((1920, 0)));
assert_eq!(s.pixel(3839, 2159), Some((5759, 2159)));
for (x, y) in [(-1921, 0), (3840, 0), (0, -1), (0, 2160), (i32::MIN, 0), (i32::MAX, i32::MAX)] {
assert_eq!(s.pixel(x, y), None, "({x}, {y})");
}
// A monitor above the main one.
let s = VirtualScreen::new(-200, -1440, 2760, 2520).unwrap();
assert_eq!(s.pixel(0, 0), Some((200, 1440)));
assert_eq!(s.pixel(-200, -1440), Some((0, 0)));
// A virtual screen at the far corner of the coordinates maps without overflowing.
let s = VirtualScreen::new(i32::MIN, i32::MIN, 10, 10).unwrap();
assert_eq!(s.pixel(i32::MIN + 9, i32::MIN), Some((9, 0)));
assert_eq!(s.pixel(i32::MAX, 0), None);
}
/// The release's own point picks, with signed coordinates: left of or above the client area
/// they are negative. Past 32,767 pixels they are widened by the message's pointer position.
#[test]
fn the_release_point_comes_from_the_message() {
let lparam = |x: i32, y: i32| ((y as u16 as isize) << 16) | x as u16 as isize;
assert_eq!(message_point(lparam(100, 200), (140, 260)), (100, 200), "the lParam point wins over a nearby position");
assert_eq!(message_point(lparam(65_636, 0), (65_636, 0)), (65_636, 0), "MSG.pt gives the high bits past 65,535 pixels");
assert_eq!(message_point(lparam(100, 0), (100, 0)), (100, 0));
assert_eq!(message_point(lparam(-5, -1), (10, 10)), (-5, -1));
assert_eq!(message_point(lparam(0, 0), (0, 0)), (0, 0));
assert_eq!(message_point(lparam(32_767, -32_768), (32_767, -32_768)), (32_767, -32_768));
assert_eq!(message_point(lparam(40_010, 2_000), (40_000, 2_100)), (40_010, 2_000), "eight 8K monitors in a row");
assert_eq!(message_point(lparam(61_439, 0), (61_000, 0)), (61_439, 0));
assert_eq!(message_point(lparam(32_770, 0), (32_760, 0)), (32_770, 0));
// A negative `lParam` on 64-bit Windows keeps only its low 32 bits as the point.
assert_eq!(message_point(lparam(-3, -4) | !0xFFFF_FFFF, (0, 0)), (-3, -4));
assert_eq!(message_point(lparam(5, 5), (i32::MAX, i32::MIN)), (i32::MAX, i32::MIN + 5), "saturates at the coordinate range");
}
/// The size is checked before the copy is made: an empty, negative, oversized or out-of-range
/// virtual screen is an error.
#[test]
fn the_copy_size_is_checked_first() {
assert!(VirtualScreen::new(0, 0, 7680 * 8, 4320).is_ok(), "eight 8K monitors in a row");
for (left, top, width, height) in [
(0, 0, 0, 1080),
(0, 0, 1920, 0),
(0, 0, -1920, 1080),
(0, 0, 7680 * 8, 4370),
(0, 0, i32::MAX, i32::MAX),
(i32::MAX - 100, 0, 1920, 1080),
(0, i32::MAX - 100, 1920, 1080),
] {
assert!(VirtualScreen::new(left, top, width, height).is_err(), "{left} {top} {width} {height}");
}
}
/// A left click picks when it is released; Escape, a click of any other button, closing the
/// window and losing the mouse cancel; losing the focus cancels once the window had it. A
/// release whose press began elsewhere does nothing.
#[test]
fn clicks_and_keys_pick_or_cancel() {
let run = |inputs: &[Input]| {
let mut press = Press::default();
inputs.iter().map(|&i| press.step(i)).find(|&s| s != Step::Wait).unwrap_or(Step::Wait)
};
use Input::{Activated, CaptureLost, Closed, Deactivated, Escape};
let (left_down, left_up) = (Input::Down(Button::Left), Input::Up(Button::Left));
let (right_down, right_up) = (Input::Down(Button::Right), Input::Up(Button::Right));
let (other_down, other_up) = (Input::Down(Button::Other), Input::Up(Button::Other));
assert_eq!(run(&[Activated, left_down, left_up]), Step::Pick);
assert_eq!(run(&[left_down, left_up]), Step::Pick, "a window that never became active still takes a click");
assert_eq!(run(&[Activated, right_down, right_up]), Step::Cancel);
assert_eq!(run(&[Activated, other_down, other_up]), Step::Cancel, "the middle and side buttons cancel");
assert_eq!(run(&[Activated, other_down, left_up]), Step::Wait);
assert_eq!(run(&[Activated, Escape]), Step::Cancel);
assert_eq!(run(&[Activated, Deactivated]), Step::Cancel);
assert_eq!(run(&[Deactivated]), Step::Wait);
assert_eq!(run(&[CaptureLost]), Step::Cancel);
assert_eq!(run(&[Closed]), Step::Cancel);
assert_eq!(run(&[Activated, left_up, right_up, other_up]), Step::Wait, "releases of presses made before the window showed");
assert_eq!(run(&[left_down, right_down, left_up]), Step::Wait, "the right button replaced the left one");
assert_eq!(run(&[right_down, left_down, left_up]), Step::Pick);
}
}
+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"><circle cx="12" cy="12" r="7.5"/><circle cx="4.5" cy="12" r="1.6" fill="currentColor"/><circle cx="19.5" cy="12" r="1.6" fill="currentColor"/><circle cx="12" cy="4.5" r="1.6" fill="currentColor"/></svg>

After

Width:  |  Height:  |  Size: 386 B

+1 -1
View File
@@ -20,4 +20,4 @@ craft-affinity = { workspace = true }
proptest = { workspace = true }
# The tests build containers and decode previews.
crc32fast = { workspace = true }
image = { workspace = true }
craft-image-codecs = { workspace = true }
+2 -2
View File
@@ -50,8 +50,8 @@ fn source_backed_tiles_retain_the_embedded_jpeg_pixels() {
assert_eq!((image.width, image.height), (400, 300));
assert_eq!(image.transform, Affine::IDENTITY);
let Pixels::Rgba8(pixels) = &image.pixels else { panic!("expected retained level-zero pixels") };
let expected = image::load_from_memory(&source(&bytes)).unwrap().into_rgba8();
assert_eq!(pixels.as_slice(), expected.as_raw());
let expected = craft_image_codecs::decode(&source(&bytes)).unwrap().to_rgba8();
assert_eq!(pixels.as_slice(), expected.as_slice());
assert!(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255));
assert!(pixels.as_chunks::<4>().0.iter().any(|p| p[0] != p[1]));
}
+98 -6
View File
@@ -9,7 +9,6 @@
//! the stroke with what the pen recorded on it (`StrokeLayer::pressure`, `tilt`, `bearing` and
//! `rotation`): the sweep is sampled densely and each sample takes the nib for the pen there.
use vectorcraft_color::Paint;
use vectorcraft_doc::{Node, StrokeLayer};
use vectorcraft_geom::{BezPath, PathData, Point, SubPath, Vec2};
@@ -198,7 +197,70 @@ fn offset_track(t: &Track, d: f64, trim0: f64, trim1: f64) -> Option<BezPath> {
Some(bp)
}
pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, name: &str) -> Vec<Node> {
/// A strand that follows the recorded pen pose. Pressure and tilt change its spread; bearing and
/// barrel rotation turn that spread in the path's local frame. Original path corners are included
/// in the samples so a turn is not rounded away by the pose sampling interval.
fn posed_bristle_track(
t: &Track,
d: f64,
trim0: f64,
trim1: f64,
size: f64,
stroke: &StrokeLayer,
varies: bool,
) -> Option<(BezPath, Vec<(f64, f64)>)> {
let l = t.len();
let (s0, s1) = (trim0.clamp(0.0, l), (l - trim1).clamp(0.0, l));
if s1 - s0 < 1e-6 {
return None;
}
let steps = if varies { ((s1 - s0) / (size * 0.2).max(0.25)).ceil().clamp(1.0, MAX_STEPS) as usize } else { 1 };
let mut positions: Vec<f64> = (0..=steps).map(|i| s0 + (s1 - s0) * i as f64 / steps as f64).collect();
positions.extend(t.cum.iter().copied().filter(|&s| s > s0 && s < s1));
positions.sort_by(f64::total_cmp);
positions.dedup_by(|a, b| (*a - *b).abs() < 1e-6);
let mut path = BezPath::new();
// Distance along the posed strand -> fraction along the original, untrimmed path.
let mut source = Vec::with_capacity(positions.len());
let mut previous: Option<Point> = None;
let mut distance = 0.0;
for (i, s) in positions.into_iter().enumerate() {
let pen = PenAt::of(stroke, s / l);
let pressure = pen.control(Variation::Pressure).unwrap_or(0.5);
let tilt = pen.control(Variation::Tilt).unwrap_or(0.5);
let bearing = pen.control(Variation::Bearing).unwrap_or(0.5);
let rotation = pen.control(Variation::Rotation).unwrap_or(0.5);
let spread = d * (0.5 + pressure) * (1.25 - 0.5 * tilt);
let angle = std::f64::consts::TAU * (bearing + rotation - 1.0);
let p = t.map(s + spread * angle.sin(), spread * angle.cos());
if i == 0 {
path.move_to(p)
} else {
path.line_to(p)
}
if let Some(previous) = previous {
distance += previous.distance(p);
}
source.push((distance, s / l));
previous = Some(p);
}
Some((path, source))
}
fn source_fraction(source: &[(f64, f64)], distance: f64) -> f64 {
let next = source.partition_point(|(d, _)| *d < distance);
if next == 0 {
return source.first().map_or(0.0, |(_, f)| *f);
}
if next >= source.len() {
return source.last().map_or(1.0, |(_, f)| *f);
}
let (d0, f0) = source[next - 1];
let (d1, f1) = source[next];
if d1 - d0 < 1e-9 { f1 } else { f0 + (f1 - f0) * ((distance - d0) / (d1 - d0)) }
}
pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec<Node> {
let mut rng = Rng::new(seed_of(bp, name));
let size = b.size.max(0.1) * weight;
let strands = (3.0 + b.density.clamp(1.0, 100.0) / 100.0 * 13.0).round() as usize;
@@ -210,6 +272,13 @@ pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, nam
let wobble = (100.0 - b.stiffness.clamp(1.0, 100.0)) / 100.0;
let ragged = b.length.clamp(25.0, 300.0) / 100.0;
let opacity = (b.opacity.clamp(1.0, 100.0) / 100.0) as f32;
let posed = stroke.pressure.is_some() || stroke.tilt.is_some() || stroke.bearing.is_some() || stroke.rotation.is_some();
let varies = |points: &[(f64, f64)]| points.first().is_some_and(|(_, first)| points.iter().any(|(_, value)| (value - first).abs() > 1e-6));
let pressure_varies = stroke.pressure.as_ref().is_some_and(|p| varies(&p.points));
let pose_varies = pressure_varies
|| stroke.tilt.as_ref().is_some_and(|p| varies(&p.points))
|| stroke.bearing.as_ref().is_some_and(|p| varies(&p.points))
|| stroke.rotation.as_ref().is_some_and(|p| varies(&p.points));
let mut out = vec![];
for t in tracks(bp, tolerance(size)) {
let l = t.len();
@@ -220,14 +289,37 @@ pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, nam
let edge = 1.0 - lane.abs();
let trim = |r: &mut Rng| r.unit() * ragged * size * (1.2 - edge) * 0.8;
let (t0, t1) = (trim(&mut rng), trim(&mut rng));
let Some(sp) = offset_track(&t, off, t0.min(l * 0.3), t1.min(l * 0.3)) else { continue };
let (t0, t1) = (t0.min(l * 0.3), t1.min(l * 0.3));
let sp = if posed {
posed_bristle_track(&t, off, t0, t1, size, stroke, pose_varies)
} else {
offset_track(&t, off, t0, t1).map(|path| (path, Vec::new()))
};
let Some((sp, source)) = sp else { continue };
let w = thick * (0.6 + 0.4 * edge) * rng.range(0.8, 1.2);
let nib = Nib::new(0.0, 1.0, w);
let subs: Vec<SubPath> = tracks(&sp, tolerance(w)).iter().flat_map(|tt| sweep(tt, &|_| nib, None)).collect();
let subs: Vec<SubPath> = tracks(&sp, tolerance(w))
.iter()
.flat_map(|tt| {
if posed {
sweep(
tt,
&|f| {
let original_fraction = source_fraction(&source, f * tt.len());
let pressure = PenAt::of(stroke, original_fraction).control(Variation::Pressure).unwrap_or(0.5);
Nib::new(0.0, 1.0, w * (0.5 + pressure))
},
pressure_varies.then_some((tt.len() / MAX_STEPS).max(0.25)),
)
} else {
let nib = Nib::new(0.0, 1.0, w);
sweep(tt, &|_| nib, None)
}
})
.collect();
if subs.is_empty() {
continue;
}
let mut n = filled(PathData::new(subs), paint);
let mut n = filled(PathData::new(subs), &stroke.paint);
n.opacity = (opacity * rng.range(0.7, 1.0) as f32).clamp(0.0, 1.0);
out.push(n);
}
+69
View File
@@ -97,6 +97,75 @@ pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) {
walk(n, mode, key);
}
/// Mixed into a stroke's seed for its hue jitter, so the amounts come from a sequence of their own
/// and a copy's size, spacing, scatter and rotation stay as they were without hue jitter.
const HUE_JITTER_SALT: u64 = 0x6875_655f_6a69_7474;
/// Turn the hue of each of `copies` (a scatter brush's copies, in order along the path) by its
/// own amount between −`amount` and `amount` degrees, drawn from `seed` (the stroke's
/// [`crate::track::seed_of`]).
pub(crate) fn jitter_hues(copies: &mut [Node], amount: f64, seed: u64) {
let mut rng = crate::track::Rng::new(seed ^ HUE_JITTER_SALT);
for n in copies {
let turn = rng.range(-amount, amount) as f32;
turn_hues(n, turn);
}
}
/// `c` with its hue turned by `degrees`, worked out on its own components so nothing else about it
/// changes: RGB in HSB of its values, CMYK over C, M and Y with K kept (as
/// [`Color::complement_keep_model`] does), Lab by turning a and b. `None` for a color without a hue:
/// white, black and grays, in their own model (Gray, CMYK with no C, M or Y ink).
fn turned(c: &Color, degrees: f32) -> Option<Color> {
if !degrees.is_finite() || vectorcraft_color::recolor::Neutral::of(c).is_some() {
return None;
}
let turn = |v: [f32; 3]| {
let [h, s, b] = vectorcraft_color::rgb_to_hsb(v);
(s > 0.0).then(|| vectorcraft_color::hsb_to_rgb([(h + degrees).rem_euclid(360.0), s, b]))
};
match *c {
Color::Rgb { r, g, b } => turn([r, g, b]).map(|[r, g, b]| Color::rgb(r, g, b)),
Color::Cmyk { c, m, y, k } => turn([1.0 - c, 1.0 - m, 1.0 - y]).map(|[r, g, b]| Color::cmyk(1.0 - r, 1.0 - g, 1.0 - b, k)),
Color::Gray { .. } => None,
Color::Lab { l, a, b } => {
let (sin, cos) = f64::from(degrees).to_radians().sin_cos();
let (a, b) = (f64::from(a), f64::from(b));
Some(Color::lab(l, (a * cos - b * sin) as f32, (a * sin + b * cos) as f32))
}
}
}
fn turn_paint(p: &mut Paint, degrees: f32) {
if let Paint::Solid { color, .. } = p
&& let Some(c) = turned(color, degrees)
{
*p = Paint::solid(c);
}
}
/// Turn the hue of the solid fills and strokes under `n`, its type's characters included. A
/// mask's colors are its values, so they stay.
fn turn_hues(n: &mut Node, degrees: f32) {
for it in &mut n.appearance.items {
match it {
AppearanceItem::Fill(f) => turn_paint(&mut f.paint, degrees),
AppearanceItem::Stroke(s) => turn_paint(&mut s.paint, degrees),
}
}
if let NodeKind::Text(t) = &mut n.kind {
for r in &mut t.runs {
turn_paint(&mut r.style.fill, degrees);
turn_paint(&mut r.style.stroke, degrees);
}
}
if let Some(ch) = n.children_mut() {
for c in ch.iter_mut() {
turn_hues(Arc::make_mut(c), degrees);
}
}
}
/// Strip the brushes from every stroke under `n`, its masks' art included.
fn strip_brushes(n: &mut Node) {
for it in &mut n.appearance.items {
+2
View File
@@ -172,6 +172,7 @@ pub fn defaults() -> &'static [Brush] {
rotation: (-180.0, 180.0),
rotation_relative_to_path: false,
colorization: Colorization::Tints,
hue_jitter: 0.0,
modes: None,
}),
},
@@ -185,6 +186,7 @@ pub fn defaults() -> &'static [Brush] {
rotation: (-35.0, 35.0),
rotation_relative_to_path: true,
colorization: Colorization::None,
hue_jitter: 0.0,
modes: None,
}),
},
+267 -2
View File
@@ -298,6 +298,12 @@ pub struct Scatter {
/// Rotation relative to the path direction (else to the page).
pub rotation_relative_to_path: bool,
pub colorization: Colorization,
/// Hue jitter in degrees, 0 to 180: each copy turns the hue of the solid colors it draws, after
/// the colorization, by its own amount between −`hue_jitter` and `hue_jitter`. The stroke's
/// path and the brush name fix the amounts, so a stroke draws the same colors every time.
/// 0 (brushes saved before there was hue jitter) leaves the colors as they are.
#[serde(skip_serializing_if = "is_zero")]
pub hue_jitter: f64,
/// How size, spacing, scatter and rotation vary between their two values: Fixed takes the
/// first, Random any value between them, Pressure the first at the lightest pen pressure and
/// the second at the heaviest, Tilt the first with the pen lying flat and the second upright,
@@ -318,6 +324,7 @@ impl Default for Scatter {
rotation: (0.0, 0.0),
rotation_relative_to_path: false,
colorization: Colorization::None,
hue_jitter: 0.0,
modes: None,
}
}
@@ -326,6 +333,8 @@ impl Default for Scatter {
impl Scatter {
/// The ranges of size (%), spacing (%), scatter (%) and rotation (°).
pub const RANGES: [(f64, f64); 4] = [(1.0, 10000.0), (1.0, 10000.0), (-1000.0, 1000.0), (-180.0, 180.0)];
/// The range of [`Scatter::hue_jitter`] (°).
pub const HUE_JITTER_RANGE: (f64, f64) = (0.0, 180.0);
/// Size, spacing, scatter and rotation, each as its (first, second) values.
pub fn values(&self) -> [(f64, f64); 4] {
@@ -624,6 +633,10 @@ fn within_pair((a, b): (f64, f64), range: (f64, f64), fallback: f64) -> (f64, f6
(within(a, range, fallback), within(b, range, fallback))
}
fn is_zero(v: &f64) -> bool {
*v == 0.0
}
fn valid_tile_frame(frame: Rect) -> bool {
[frame.x0, frame.y0, frame.x1, frame.y1].into_iter().all(f64::is_finite)
&& frame.width().is_finite()
@@ -714,6 +727,7 @@ impl Brush {
s.spacing = within_pair(s.spacing, spacing, d.spacing.0);
s.scatter = within_pair(s.scatter, scatter, 0.0);
s.rotation = within_pair(s.rotation, rotation, 0.0);
s.hue_jitter = within(s.hue_jitter, Scatter::HUE_JITTER_RANGE, 0.0);
s.colorization.sanitize();
}
BrushKind::Art(a) => {
@@ -753,6 +767,229 @@ impl Brush {
}
}
// ---------- stroke options ----------
/// The Scatter brush fields a stroke can set for itself ([`BrushKind::stroke_option_keys`]).
#[derive(Serialize, Deserialize)]
struct ScatterOptions {
size: (f64, f64),
spacing: (f64, f64),
scatter: (f64, f64),
rotation: (f64, f64),
modes: Option<[Variation; 4]>,
rotation_relative_to_path: bool,
colorization: Colorization,
}
/// The Art brush fields a stroke can set for itself.
#[derive(Serialize, Deserialize)]
struct ArtOptions {
width: f64,
width_mode: Option<Variation>,
width_max: Option<f64>,
flip_along: bool,
flip_across: bool,
overlap: bool,
colorization: Colorization,
}
/// The Pattern brush fields a stroke can set for itself.
#[derive(Serialize, Deserialize)]
struct PatternOptions {
scale: f64,
spacing: f64,
fit: PatternFit,
flip_along: bool,
flip_across: bool,
colorization: Colorization,
}
impl BrushKind {
/// The definition fields, by their `brush.options` names, that one stroke can set for itself
/// (the Brushes panel's Options of Selected Object, [`StrokeLayer::brush_options`]). A Bristle
/// brush has none.
pub fn stroke_option_keys(&self) -> &'static [&'static str] {
match self {
BrushKind::Calligraphic(_) => &["angle", "roundness", "size", "variation", "modes"],
BrushKind::Scatter(_) => &["size", "spacing", "scatter", "rotation", "modes", "rotation_relative_to_path", "colorization"],
BrushKind::Art(_) => &["width", "width_mode", "width_max", "flip_along", "flip_across", "overlap", "colorization"],
BrushKind::Pattern(_) => &["scale", "spacing", "fit", "flip_along", "flip_across", "colorization"],
BrushKind::Bristle(_) => &[],
}
}
/// The values of [`Self::stroke_option_keys`], as a JSON object. Calligraphic modes left to the
/// values are a `null` `modes`, so a stroke that sets them so keeps that setting.
fn option_values(&self) -> serde_json::Value {
let v = match self {
BrushKind::Calligraphic(c) => serde_json::to_value(c).map(|mut v| {
if let Some(o) = v.as_object_mut() {
o.entry("modes").or_insert(serde_json::Value::Null);
}
v
}),
BrushKind::Scatter(s) => serde_json::to_value(ScatterOptions {
size: s.size,
spacing: s.spacing,
scatter: s.scatter,
rotation: s.rotation,
modes: s.modes,
rotation_relative_to_path: s.rotation_relative_to_path,
colorization: s.colorization,
}),
BrushKind::Art(a) => serde_json::to_value(ArtOptions {
width: a.width,
width_mode: a.width_mode,
width_max: a.width_max,
flip_along: a.flip_along,
flip_across: a.flip_across,
overlap: a.overlap,
colorization: a.colorization,
}),
BrushKind::Pattern(p) => serde_json::to_value(PatternOptions {
scale: p.scale,
spacing: p.spacing,
fit: p.fit,
flip_along: p.flip_along,
flip_across: p.flip_across,
colorization: p.colorization,
}),
BrushKind::Bristle(_) => Ok(serde_json::Value::Object(serde_json::Map::new())),
};
v.unwrap_or_default()
}
/// Set the values of [`Self::stroke_option_keys`] from `v` (as [`Self::option_values`] gives
/// them). An error when a value is of the wrong kind.
fn set_option_values(&mut self, v: serde_json::Value) -> Result<(), serde_json::Error> {
match self {
BrushKind::Calligraphic(c) => *c = serde_json::from_value(v)?,
BrushKind::Scatter(s) => {
let o: ScatterOptions = serde_json::from_value(v)?;
(s.size, s.spacing, s.scatter, s.rotation, s.modes) = (o.size, o.spacing, o.scatter, o.rotation, o.modes);
(s.rotation_relative_to_path, s.colorization) = (o.rotation_relative_to_path, o.colorization);
}
BrushKind::Art(a) => {
let o: ArtOptions = serde_json::from_value(v)?;
(a.width, a.width_mode, a.width_max, a.flip_along, a.flip_across) = (o.width, o.width_mode, o.width_max, o.flip_along, o.flip_across);
(a.overlap, a.colorization) = (o.overlap, o.colorization);
}
BrushKind::Pattern(p) => {
let o: PatternOptions = serde_json::from_value(v)?;
(p.scale, p.spacing, p.fit, p.flip_along, p.flip_across, p.colorization) =
(o.scale, o.spacing, o.fit, o.flip_along, o.flip_across, o.colorization);
}
BrushKind::Bristle(_) => {}
}
Ok(())
}
}
/// Stroke option value `new` with each `null` item of an array taken from the same place in
/// `current`, an array of the same length: a stroke option that changes some items of a range or a
/// list of modes and keeps the others ([`Brush::with_stroke_options`]). Any other `new` is given as
/// it is.
pub fn keep_items(new: &serde_json::Value, current: &serde_json::Value) -> serde_json::Value {
match (new, current) {
(serde_json::Value::Array(n), serde_json::Value::Array(c)) if n.len() == c.len() => {
serde_json::Value::Array(n.iter().zip(c).map(|(n, c)| if n.is_null() { c.clone() } else { n.clone() }).collect())
}
_ => new.clone(),
}
}
impl Brush {
/// The brush as a stroke whose own settings are `options` draws it: each field of
/// [`BrushKind::stroke_option_keys`] in `options` replaces the brush's value (a `colorization`
/// object changes only the fields it gives), and the values are kept within their ranges
/// ([`Brush::sanitize`]). A `null` item of an array keeps the brush's item there
/// ([`keep_items`]). Fields the type does not take are passed over. An error when a value is of
/// the wrong kind.
pub fn with_stroke_options(&self, options: &serde_json::Map<String, serde_json::Value>) -> Result<Brush, String> {
let keys = self.kind.stroke_option_keys();
let mut values = self.kind.option_values();
let Some(o) = values.as_object_mut() else { return Ok(self.clone()) };
for (k, v) in options {
if !keys.contains(&k.as_str()) {
continue;
}
match (o.get_mut(k).and_then(serde_json::Value::as_object_mut), v.as_object()) {
(Some(inner), Some(fields)) if k == "colorization" => {
for (f, fv) in fields {
inner.insert(f.clone(), fv.clone());
}
}
// Set below, once the values the modes may follow are in.
_ if k == "modes" => {}
_ => {
let current = o.get(k).cloned().unwrap_or_default();
o.insert(k.clone(), keep_items(v, &current));
}
}
}
// A Hue Shift without a key takes the art's main color, as `Brush::from_json` gives it.
if let Some(c) = o.get_mut("colorization").and_then(serde_json::Value::as_object_mut)
&& c.get("method").and_then(serde_json::Value::as_str) == Some("hueShift")
&& c.get("key").is_none_or(serde_json::Value::is_null)
{
let key = art_colors(self.art()).first().copied().unwrap_or(vectorcraft_color::Color::BLACK);
c.insert("key".into(), serde_json::to_value(key).map_err(|e| e.to_string())?);
}
let mut b = self.clone();
b.kind.set_option_values(values.clone()).map_err(|e| e.to_string())?;
if let Some(m) = options.get("modes")
&& keys.contains(&"modes")
{
// A null item keeps the mode the brush with the other settings has: modes it leaves to
// its values follow the stroke's values, as they are kept within their ranges. Modes
// equal to those are left as the brush has them, so they keep following the values.
b.sanitize();
let current = match &b.kind {
BrushKind::Calligraphic(c) => serde_json::to_value(c.modes()).unwrap_or_default(),
BrushKind::Scatter(s) => serde_json::to_value(s.modes()).unwrap_or_default(),
_ => serde_json::Value::Null,
};
let modes = keep_items(m, &current);
if modes != current {
if let Some(o) = values.as_object_mut() {
o.insert("modes".into(), modes);
}
b = self.clone();
b.kind.set_option_values(values).map_err(|e| e.to_string())?;
}
}
b.sanitize();
Ok(b)
}
/// The stroke options of `options` that make the brush draw differently: each field of
/// [`BrushKind::stroke_option_keys`] whose value, after [`Self::with_stroke_options`], differs
/// from the brush's own, with that value (kept within its range). An error for a field the
/// type does not take and for a value of the wrong kind.
pub fn stroke_options_that_differ(
&self,
options: &serde_json::Map<String, serde_json::Value>,
) -> Result<serde_json::Map<String, serde_json::Value>, String> {
let keys = self.kind.stroke_option_keys();
if let Some(k) = options.keys().find(|k| !keys.contains(&k.as_str())) {
return Err(if keys.is_empty() {
format!("a {} brush has no options of its own on a stroke", self.kind.label().to_lowercase())
} else {
format!("a {} brush's stroke options do not include `{k}` (they are {})", self.kind.label().to_lowercase(), keys.join(", "))
});
}
let edited = self.with_stroke_options(options)?.kind.option_values();
let own = self.kind.option_values();
Ok(keys
.iter()
.filter_map(|k| {
let v = edited.get(*k)?;
(own.get(*k) != Some(v)).then(|| ((*k).to_string(), v.clone()))
})
.collect())
}
}
// ---------- library ----------
/// The brush library of `doc`: its stored brushes, or the defaults when it has none.
@@ -842,12 +1079,26 @@ fn tolerance(scale: f64) -> f64 {
/// Filled art for one brushed stroke along `bp`, in `doc`. Pieces are in document space with id
/// 0, and never draw a brushed stroke (so they never recurse): their own strokes carry no brush,
/// and what they draw by name that would draw one is left out ([`leave_out_brushed`]).
/// Stroke-level opacity/blend are the caller's job (`StrokeLayer::opacity`).
/// Stroke-level opacity/blend are the caller's job (`StrokeLayer::opacity`). The stroke's own
/// brush settings ([`StrokeLayer::brush_options`]) replace the brush's values
/// ([`Brush::with_stroke_options`]); settings that do not read draw the brush as it is.
pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &StrokeLayer) -> Vec<Node> {
let edited;
let brush = if stroke.brush_options.is_empty() {
brush
} else {
match brush.with_stroke_options(&stroke.brush_options) {
Ok(b) => {
edited = b;
&edited
}
Err(_) => brush,
}
};
let w = if stroke.width > 0.0 { stroke.width } else { 1.0 };
let mut out = match &brush.kind {
BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name),
BrushKind::Bristle(b) => calli::bristle(b, bp, w, &stroke.paint, &brush.name),
BrushKind::Bristle(b) => calli::bristle(b, bp, w, stroke, &brush.name),
BrushKind::Art(a) => warp::art(a, bp, w, stroke),
BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name),
BrushKind::Pattern(p) => warp::pattern(p, bp, w),
@@ -856,6 +1107,12 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok
for n in &mut out {
colorize(n, colorization, &stroke.paint);
}
// One piece per copy, in the order the copies run along the path.
if let BrushKind::Scatter(s) = &brush.kind
&& s.hue_jitter > 0.0
{
colorize::jitter_hues(&mut out, s.hue_jitter, track::seed_of(bp, &brush.name));
}
leave_out_brushed(doc, &mut out, &mut Known::new());
out
}
@@ -1008,6 +1265,14 @@ pub fn has_brush(n: &Node) -> bool {
n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && s.visible))
}
/// Does `stroke` draw with a brush of `lib` (the document's [`library`])? [`stroke_pieces`] sizes
/// brush art from the brush and the stroke weight and does not read the stroke's width profile, so
/// the profile does not change what such a stroke draws. A stroke without a brush, or one that
/// names a brush `lib` lacks, draws a plain stroke, which follows the profile.
pub fn keeps_brush_size(lib: &[Brush], stroke: &StrokeLayer) -> bool {
stroke.brush.as_deref().is_some_and(|name| lib.iter().any(|b| b.name == name))
}
/// How far brush art can paint past the visual box of `n`: `16 × w + 8`, where `w` is the widest
/// stroke of `n` (at least 1), when `n` has a visible brushed stroke with a paint; 0 when it has
/// none, as a brushed stroke without a paint draws no brush art. This is the room the renderer and
+337
View File
@@ -1,3 +1,4 @@
use serde_json::json;
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, StrokeLayer};
use vectorcraft_geom::{Affine, BezPath, Point, Rect, Vec2, shapes};
@@ -826,6 +827,86 @@ fn bristle_makes_translucent_strands() {
assert!(bb.height() <= 6.0 * 1.3 && bb.height() >= 3.0, "{bb:?}");
}
#[test]
fn bristle_pen_pressure_changes_its_footprint() {
let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) };
let render = |pressure| {
let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, pressure), (1.0, pressure)] }), ..stroke(1.0) };
stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s)
};
let light = render(0.0);
let heavy = render(1.0);
assert_eq!(light.len(), heavy.len());
assert!(bounds(&heavy).height() > bounds(&light).height() * 1.8);
}
#[test]
fn bristle_pen_pressure_is_sampled_along_the_stroke() {
let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) };
let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) };
let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s);
let mut points = Vec::new();
for n in &out {
all_points(n, &mut points);
}
let early = points.iter().filter(|p| p.x > 20.0 && p.x < 60.0).map(|p| p.y.abs()).fold(0.0_f64, f64::max);
let late = points.iter().filter(|p| p.x > 140.0 && p.x < 180.0).map(|p| p.y.abs()).fold(0.0_f64, f64::max);
assert!(late > early * 1.4, "spread along stroke: {early} -> {late}");
}
#[test]
fn trimmed_bristle_strands_read_pressure_where_they_begin() {
let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle { size: 20.0, length: 300.0, ..Default::default() }) };
let render = |points| {
let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points }), ..stroke(1.0) };
stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 80.0, 0.0), &s)
};
let ramp = render(vec![(0.0, 0.0), (1.0, 1.0)]);
let neutral = render(vec![(0.0, 0.5), (1.0, 0.5)]);
assert_eq!(ramp.len(), neutral.len());
let start = |n: &Node| {
let anchors = &n.path_data().unwrap().subpaths[0].anchors;
let first = anchors[0].p;
let opposite = anchors[anchors.len() - 16].p;
(first.x, (first.y - opposite.y).abs())
};
let mut checked = false;
for (ramp, neutral) in ramp.iter().zip(&neutral) {
let (x, width) = start(ramp);
if x < 12.0 {
continue;
}
let (_, neutral_width) = start(neutral);
let expected = 0.5 + x / 80.0;
assert!(width / neutral_width > expected - 0.08, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}");
checked = true;
}
assert!(checked, "at least one strand begins past the pressure ramp's first eighth");
}
#[test]
fn bristle_pen_orientation_changes_its_footprint() {
let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) };
let render = |tilt, bearing, rotation| {
let flat = |x| vec![(0.0, x), (1.0, x)];
let s = StrokeLayer {
tilt: Some(vectorcraft_doc::PressureProfile { points: flat(tilt) }),
bearing: Some(vectorcraft_doc::AngleProfile { points: flat(bearing) }),
rotation: Some(vectorcraft_doc::AngleProfile { points: flat(rotation) }),
..stroke(1.0)
};
stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s)
};
let neutral = bounds(&render(0.5, 0.0, 0.0)).height();
let flat = bounds(&render(1.0, 0.0, 0.0)).height();
let upright = bounds(&render(0.0, 0.0, 0.0)).height();
let bearing = bounds(&render(0.5, 90.0, 0.0)).height();
let rotation = bounds(&render(0.5, 0.0, 90.0)).height();
assert!(flat > neutral && neutral > upright, "tilt: {flat} > {neutral} > {upright}");
assert!(bearing < neutral * 0.7, "bearing: {bearing} vs {neutral}");
assert!(rotation < neutral * 0.7, "rotation: {rotation} vs {neutral}");
}
#[test]
fn tints_colorization_uses_stroke_colour() {
let b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
@@ -952,6 +1033,165 @@ fn stain_mixes_type_strokes_too() {
assert_eq!(run_paints(&[art]), [(Paint::solid(blue), Paint::solid(blue))]);
}
/// A scatter brush of rectangles filled `fill`, with `colorization` and `hue_jitter`.
fn jittered(fill: Color, colorization: Colorization, hue_jitter: f64) -> Brush {
let mut art = rect_art(10.0, 4.0);
art.appearance.set_fill(Paint::solid(fill));
Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization, hue_jitter, ..Default::default() }) }
}
/// The fill color of each copy.
fn fill_colors(out: &[Node]) -> Vec<Color> {
out.iter().map(|n| n.appearance.fill_paint().color().unwrap()).collect()
}
/// How far hue `h` is from `from`, in degrees, either way round.
fn hue_gap(h: f32, from: f32) -> f32 {
let d = (h - from).rem_euclid(360.0);
d.min(360.0 - d)
}
#[test]
fn hue_jitter_turns_each_copy_the_same_every_time() {
let doc = Document::new(1.0, 1.0);
let path = line(0.0, 0.0, 200.0, 0.0);
let b = jittered(Color::rgb(1.0, 0.0, 0.0), Colorization::None, 90.0);
let out = stroke_pieces(&doc, &b, &path, &stroke(1.0));
assert_eq!(out.len(), 20);
assert_eq!(stroke_pieces(&doc, &b, &path, &stroke(1.0)), out, "the same stroke draws the same colors");
let colors = fill_colors(&out);
let hues: Vec<f32> = colors.iter().map(|c| c.to_hsb()[0]).collect();
assert!(hues.iter().all(|h| hue_gap(*h, 0.0) <= 90.01), "{hues:?}");
assert!(hues.iter().any(|h| hue_gap(*h, 0.0) > 10.0), "the copies turn: {hues:?}");
let distinct: std::collections::HashSet<String> = colors.iter().map(Color::to_hex).collect();
assert!(distinct.len() > 10, "each copy turns by its own amount: {distinct:?}");
// Saturation and brightness stay; the copies stay where they were, at their size and angle.
assert!(colors.iter().all(|c| near(f64::from(c.to_hsb()[1]), 1.0, 1e-3) && near(f64::from(c.to_hsb()[2]), 1.0, 1e-3)), "{colors:?}");
let plain = stroke_pieces(&doc, &jittered(Color::rgb(1.0, 0.0, 0.0), Colorization::None, 0.0), &path, &stroke(1.0));
let boxes = |o: &[Node]| o.iter().map(|n| n.geometric_bounds().unwrap()).collect::<Vec<_>>();
assert_eq!(boxes(&out), boxes(&plain));
// Another path draws other amounts.
let other = fill_colors(&stroke_pieces(&doc, &b, &line(0.0, 10.0, 200.0, 10.0), &stroke(1.0)));
assert_ne!(other, colors);
}
#[test]
fn hue_jitter_of_zero_changes_nothing() {
let red = Color::rgb(1.0, 0.0, 0.0);
let out = stroke_pieces(&Document::new(1.0, 1.0), &jittered(red, Colorization::None, 0.0), &line(0.0, 0.0, 200.0, 0.0), &stroke(1.0));
assert!(!out.is_empty() && fill_colors(&out).iter().all(|c| *c == red));
// A brush without hue jitter is saved as before, and one saved before reads as 0.
let v = serde_json::to_value(jittered(red, Colorization::None, 0.0)).unwrap();
assert!(v.get("hue_jitter").is_none(), "{v}");
let mut old = serde_json::to_value(jittered(red, Colorization::None, 45.0)).unwrap();
assert_eq!(old.as_object_mut().unwrap().remove("hue_jitter"), Some(serde_json::json!(45.0)));
let BrushKind::Scatter(s) = Brush::from_json(old).unwrap().kind else { panic!("not a scatter brush") };
assert_eq!(s.hue_jitter, 0.0, "a brush saved without the key reads as 0");
let mut with = v.clone();
with["hue_jitter"] = serde_json::json!(45.0);
let BrushKind::Scatter(s) = Brush::from_json(with).unwrap().kind else { panic!("not a scatter brush") };
assert_eq!(s.hue_jitter, 45.0);
// Values outside 0..180 are clamped.
for (given, kept) in [(500.0, 180.0), (-20.0, 0.0)] {
let mut v = v.clone();
v["hue_jitter"] = serde_json::json!(given);
let BrushKind::Scatter(s) = Brush::from_json(v).unwrap().kind else { panic!("not a scatter brush") };
assert_eq!(s.hue_jitter, kept, "{given}");
}
}
#[test]
fn hue_jitter_turns_after_the_colorization() {
let doc = Document::new(1.0, 1.0);
let path = line(0.0, 0.0, 200.0, 0.0);
// Tints: black art takes the blue stroke color, which then turns.
let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0);
let hues: Vec<f32> =
fill_colors(&stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 30.0), &path, &blue)).iter().map(|c| c.to_hsb()[0]).collect();
assert!(!hues.is_empty() && hues.iter().all(|h| hue_gap(*h, 240.0) <= 30.01), "{hues:?}");
assert!(hues.iter().any(|h| hue_gap(*h, 240.0) > 3.0), "{hues:?}");
// A gray stroke color has no hue: its tints stay as they are.
let gray = StrokeLayer::new(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 1.0);
let turned = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 180.0), &path, &gray);
let still = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 0.0), &path, &gray);
assert_eq!(fill_colors(&turned), fill_colors(&still));
// Nor does black ink alone, nor a gray, as a process stroke color.
for key in [Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::cmyk(0.0, 0.0, 0.0, 0.5), Color::gray(0.4)] {
let key = StrokeLayer::new(Paint::solid(key), 1.0);
let turned = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 180.0), &path, &key);
let still = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 0.0), &path, &key);
assert_eq!(fill_colors(&turned), fill_colors(&still), "{key:?}");
}
// A turned process color stays a process color, turned over its C, M and Y with its K kept.
let cmyk = fill_colors(&stroke_pieces(&doc, &jittered(Color::cmyk(0.0, 1.0, 1.0, 0.25), Colorization::None, 60.0), &path, &stroke(1.0)));
assert!(cmyk.iter().any(|c| *c != Color::cmyk(0.0, 1.0, 1.0, 0.25)), "{cmyk:?}");
for c in &cmyk {
let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") };
assert_eq!(k, 0.25);
// Full ink in one channel and none in another, as the color before it.
assert!(near(f64::from(c.max(m).max(y)), 1.0, 1e-4) && near(f64::from(c.min(m).min(y)), 0.0, 1e-4), "{c} {m} {y}");
}
// An RGB color keeps its saturation and brightness in its own values.
let rgb = fill_colors(&stroke_pieces(&doc, &jittered(Color::rgb(0.8, 0.2, 0.4), Colorization::None, 90.0), &path, &stroke(1.0)));
for c in &rgb {
let Color::Rgb { r, g, b } = *c else { panic!("not RGB: {c:?}") };
assert!(near(f64::from(r.max(g).max(b)), 0.8, 1e-4) && near(f64::from(r.min(g).min(b)), 0.2, 1e-4), "{c:?}");
}
// A Lab color keeps its lightness and chroma.
let lab = fill_colors(&stroke_pieces(&doc, &jittered(Color::lab(50.0, 40.0, 30.0), Colorization::None, 90.0), &path, &stroke(1.0)));
assert!(lab.iter().any(|c| *c != Color::lab(50.0, 40.0, 30.0)), "{lab:?}");
for c in &lab {
let Color::Lab { l, a, b } = *c else { panic!("not Lab: {c:?}") };
assert!(l == 50.0 && near(f64::from(a.hypot(b)), 50.0, 1e-3), "{c:?}");
}
}
/// Hue jitter turns type's characters, the colors Tints and Shades and Hue Shift give, and a color
/// linked to a swatch (which loses the link); a pattern paint stays.
#[test]
fn hue_jitter_turns_type_every_colorization_and_linked_colors() {
let doc = Document::new(1.0, 1.0);
let path = line(0.0, 0.0, 200.0, 0.0);
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let typed = |hue_jitter| Brush {
name: "s".into(),
kind: BrushKind::Scatter(Scatter { art: type_art(red.clone(), red.clone()), hue_jitter, ..Default::default() }),
};
let still = run_paints(&stroke_pieces(&doc, &typed(0.0), &path, &stroke(1.0)));
let turned = run_paints(&stroke_pieces(&doc, &typed(90.0), &path, &stroke(1.0)));
assert!(!still.is_empty() && still.iter().all(|p| *p == (red.clone(), red.clone())), "{still:?}");
assert_eq!(turned.len(), still.len());
assert!(turned.iter().any(|p| *p != (red.clone(), red.clone())), "the characters turn: {turned:?}");
assert!(turned.iter().all(|(f, s)| f == s), "a copy's character fill and stroke turn by the same amount: {turned:?}");
// Tints and Shades and Hue Shift: the colors they give turn.
let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0);
for colorization in [Colorization::TintsAndShades, Colorization::HueShift { key: Color::rgb(1.0, 0.0, 0.0) }] {
let art = Color::rgb(1.0, 0.0, 0.0);
let still = fill_colors(&stroke_pieces(&doc, &jittered(art, colorization, 0.0), &path, &blue));
let turned = fill_colors(&stroke_pieces(&doc, &jittered(art, colorization, 45.0), &path, &blue));
assert_eq!(turned.len(), still.len());
assert_ne!(turned, still, "{colorization:?}");
for (t, s) in turned.iter().zip(&still) {
assert!(hue_gap(t.to_hsb()[0], s.to_hsb()[0]) <= 45.01, "{colorization:?}: {t:?} from {s:?}");
}
}
// A color linked to a swatch turns and loses the link; a pattern paint stays.
let linked = Paint::Solid { color: Color::rgb(1.0, 0.0, 0.0), swatch: Some("Red".into()), tint: 1.0 };
let pattern = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY };
let mut art = rect_art(10.0, 4.0);
art.appearance.set_fill(linked.clone());
art.appearance.set_stroke(pattern.clone());
let b = |hue_jitter| Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art: art.clone(), hue_jitter, ..Default::default() }) };
let still = stroke_pieces(&doc, &b(0.0), &path, &stroke(1.0));
let turned = stroke_pieces(&doc, &b(90.0), &path, &stroke(1.0));
assert!(!still.is_empty() && still.iter().all(|n| n.appearance.fill_paint() == linked));
assert_eq!(turned.len(), still.len());
for n in &turned {
assert!(matches!(n.appearance.fill_paint(), Paint::Solid { swatch: None, .. }), "{:?}", n.appearance.fill_paint());
assert_eq!(n.appearance.stroke().map(|s| &s.paint), Some(&pattern));
}
}
/// An instance whose fill has an opacity of 0 does not stain its symbol's art, so the art keeps its
/// swatch links.
#[test]
@@ -2037,3 +2277,100 @@ fn a_straight_run_keeps_the_same_node_kinds_as_a_bend() {
}
}
}
/// `options` as a stroke's own brush settings.
fn with_options(options: serde_json::Value) -> StrokeLayer {
StrokeLayer { brush_options: options.as_object().cloned().unwrap_or_default(), ..stroke(1.0) }
}
#[test]
fn a_strokes_own_options_change_its_art_and_leave_the_brush() {
let doc = Document::new(1.0, 1.0);
let brush = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
let path = line(20.0, 50.0, 220.0, 50.0);
let half = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": 50.0})));
assert!(near(bounds(&half).height(), 2.0, 1e-6), "width 50% halves the art across the stroke: {:?}", bounds(&half));
assert!(near(bounds(&stroke_pieces(&doc, &brush, &path, &stroke(1.0))).height(), 4.0, 1e-6), "a stroke without options draws the brush");
let BrushKind::Art(a) = &brush.kind else { panic!("art brush") };
assert_eq!(a.width, 100.0, "the brush keeps its width");
// A calligraphic stroke's own size and angle.
let nib = stroke_pieces(&doc, &calli(0.0, 20.0, 10.0), &line(0.0, 0.0, 100.0, 0.0), &with_options(json!({"angle": 90.0})));
assert!(near(bounds(&nib).height(), 10.0, 0.05), "{:?}", bounds(&nib));
// A pattern stroke's own scale doubles the tiles across it.
let pattern = pattern_brush(PatternFit::Stretch, false);
let plain = bounds(&stroke_pieces(&doc, &pattern, &path, &stroke(1.0))).height();
let doubled = bounds(&stroke_pieces(&doc, &pattern, &path, &with_options(json!({"scale": 200.0})))).height();
assert!(near(doubled, plain * 2.0, 1e-6), "{plain} → {doubled}");
}
#[test]
fn stroke_options_are_checked_and_kept_within_their_ranges() {
let brush = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch);
let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default();
// Out of range: clamped; equal to the brush's own value: left out.
let got = brush.stroke_options_that_differ(&map(json!({"width": 5000.0, "flip_along": false}))).unwrap();
assert_eq!(serde_json::Value::Object(got), json!({"width": 1000.0}));
// A field the type does not take, and a value of the wrong kind, are errors.
assert!(brush.stroke_options_that_differ(&map(json!({"angle": 10.0}))).unwrap_err().contains("angle"));
assert!(brush.stroke_options_that_differ(&map(json!({"width": "wide"}))).is_err());
let bristle = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) };
assert!(bristle.stroke_options_that_differ(&map(json!({"size": 2.0}))).is_err());
assert!(bristle.stroke_options_that_differ(&map(json!({}))).unwrap().is_empty());
// A colorization object changes only the fields it gives: Hue Shift keeps the key it has.
let key = Color::rgb(0.0, 0.0, 1.0);
let hue = Brush {
name: "h".into(),
kind: BrushKind::Art(ArtBrush { art: rect_art(10.0, 4.0), colorization: Colorization::HueShift { key }, ..Default::default() }),
};
let tints = hue.with_stroke_options(&map(json!({"colorization": {"method": "tints"}}))).unwrap();
assert_eq!(tints.kind.colorization(), Colorization::Tints);
let back = hue.stroke_options_that_differ(&map(json!({"colorization": {"method": "hueShift"}}))).unwrap();
assert!(back.is_empty(), "the brush's own colorization: {back:?}");
// Hue Shift without a key takes the art's main color, as brush.options gives it.
let keyless = tints.stroke_options_that_differ(&map(json!({"colorization": {"method": "hueShift"}}))).unwrap();
let want = art_colors(tints.art()).first().copied().unwrap_or(Color::BLACK);
assert_eq!(keyless["colorization"]["method"], json!("hueShift"));
assert_eq!(keyless["colorization"]["key"], serde_json::to_value(want).unwrap());
// Settings that do not read draw the brush as it is.
let doc = Document::new(1.0, 1.0);
let path = line(20.0, 50.0, 220.0, 50.0);
let odd = stroke_pieces(&doc, &brush, &path, &with_options(json!({"width": [1, 2]})));
assert!(near(bounds(&odd).height(), 4.0, 1e-6));
}
#[test]
fn null_stroke_option_items_keep_the_items_the_stroke_has() {
let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default();
// A scatter brush at fixed sizes, with no modes of its own: they follow its values.
let b = Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { size: (100.0, 100.0), ..Default::default() }) };
let BrushKind::Scatter(s) = b.with_stroke_options(&map(json!({"size": [null, 150]}))).unwrap().kind else { panic!("scatter") };
assert_eq!(s.size, (100.0, 150.0), "the smallest size stays the brush's");
// A stroke whose sizes vary keeps that random size mode when it sets only the spacing mode.
let e = b.with_stroke_options(&map(json!({"size": [50, 80], "modes": [null, "pressure", null, null]}))).unwrap();
let BrushKind::Scatter(s) = e.kind else { panic!("scatter") };
assert_eq!(s.modes(), [Variation::Random, Variation::Pressure, Variation::Fixed, Variation::Fixed]);
// The kept modes follow the values as they are kept within their ranges.
let c = calli(0.0, 100.0, 3.0).with_stroke_options(&map(json!({"variation": [-2, 0, 0], "modes": [null, "pressure", null]}))).unwrap();
let BrushKind::Calligraphic(c) = c.kind else { panic!("calligraphic") };
assert_eq!(c.modes(), [Variation::Fixed, Variation::Pressure, Variation::Fixed]);
// Modes that change nothing are no setting of the stroke's: they keep following its values.
let same = b.stroke_options_that_differ(&map(json!({"modes": [null, null, null, null]}))).unwrap();
assert!(same.is_empty(), "{same:?}");
}
#[test]
fn a_null_calligraphic_modes_setting_stays_when_another_value_changes() {
let map = |v: serde_json::Value| v.as_object().cloned().unwrap_or_default();
// A brush whose modes are its own, and a stroke whose modes follow its values instead.
let mut b = calli(0.0, 100.0, 3.0);
if let BrushKind::Calligraphic(c) = &mut b.kind {
c.modes = Some([Variation::Pressure; 3]);
}
let got = b.stroke_options_that_differ(&map(json!({"modes": null, "angle": 30.0}))).unwrap();
assert_eq!(serde_json::Value::Object(got), json!({"modes": null, "angle": 30.0}));
let BrushKind::Calligraphic(c) = b.with_stroke_options(&map(json!({"modes": null, "angle": 30.0}))).unwrap().kind else { panic!("calligraphic") };
assert_eq!(c.modes(), [Variation::Fixed; 3], "the stroke draws with the modes its values give");
// A brush whose modes follow its values: a null `modes` is the brush's own and is left out.
let plain = calli(0.0, 100.0, 3.0).stroke_options_that_differ(&map(json!({"modes": null}))).unwrap();
assert!(plain.is_empty(), "{plain:?}");
}
+2
View File
@@ -10,6 +10,7 @@ workspace = true
[dependencies]
craft-dxf = { workspace = true }
craft-plotter = { workspace = true }
vectorcraft-geom = { workspace = true }
vectorcraft-color = { workspace = true }
vectorcraft-doc = { workspace = true }
@@ -19,6 +20,7 @@ vectorcraft-pathops = { workspace = true }
vectorcraft-text = { workspace = true }
kurbo = { workspace = true }
image = { workspace = true }
craft-image-codecs = { workspace = true }
[dev-dependencies]
serde_json = { workspace = true }
+2 -428
View File
@@ -1,428 +1,2 @@
//! The bytes of an HP-GL file as instructions: two-letter mnemonics and the parameters that follow
//! them, read one at a time as the plot asks for them. Printer escape sequences (PCL, HP RTL, the
//! HP-GL device-control escapes) and PJL lines around and between the instructions are skipped,
//! with the data their escapes carry.
/// The end-of-text character, the default label terminator.
pub(super) const ETX: u8 = 3;
const ESC: u8 = 0x1b;
/// The most digits of a number that count: longer ones are read as their first digits.
const MAX_DIGITS: usize = 18;
/// What the bytes being read hold.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Mode {
/// HP-GL instructions.
Hpgl,
/// PCL or HP RTL: escape sequences and their data, nothing to draw.
Pcl,
/// After a Universal Exit Language: PJL lines until a language starts.
Pjl,
}
/// One item of a PE (Polyline Encoded) instruction.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum PeItem {
/// Select pen.
Pen(i64),
/// Rectangle mode: the following coordinates come in fours.
Rect,
/// A coordinate pair, after a pen-up flag (`up`) and an absolute flag (`absolute`).
Point { x: f64, y: f64, up: bool, absolute: bool },
}
/// The state of one PE instruction being read.
#[derive(Clone, Copy, Debug, Default)]
pub(super) struct Pe {
seven_bit: bool,
fraction_bits: u32,
up: bool,
absolute: bool,
}
pub(super) struct Lexer<'a> {
b: &'a [u8],
at: usize,
mode: Mode,
/// The file holds HP RTL or PCL raster image data.
pub raster: bool,
}
/// Is `c` a byte that separates numeric parameters (or white space between instructions)?
fn separator(c: u8) -> bool {
matches!(c, b' ' | b',' | b'\t' | b'\r' | b'\n' | 0)
}
impl<'a> Lexer<'a> {
pub fn new(b: &'a [u8]) -> Self {
Self { b, at: 0, mode: Mode::Hpgl, raster: false }
}
fn peek(&self) -> Option<u8> {
self.b.get(self.at).copied()
}
/// Whether everything has been read.
pub fn done(&self) -> bool {
self.at >= self.b.len()
}
/// How many bytes have been read.
pub fn pos(&self) -> usize {
self.at
}
/// The next instruction's mnemonic, in upper case; `strict`: only white space, semicolons and
/// escape sequences may come before it (anything else gives `None`, as the end does).
pub fn op(&mut self, strict: bool) -> Option<[u8; 2]> {
loop {
let c = self.peek()?;
if c == ESC {
self.escape();
continue;
}
match self.mode {
Mode::Pcl => {
self.at += 1;
continue;
}
Mode::Pjl => {
if separator(c) {
self.at += 1;
} else if c == b'@' {
self.pjl_line();
} else {
self.mode = Mode::Hpgl;
}
continue;
}
Mode::Hpgl => {}
}
let next = self.b.get(self.at + 1).copied();
if c.is_ascii_alphabetic()
&& let Some(n) = next.filter(u8::is_ascii_alphabetic)
{
self.at += 2;
return Some([c.to_ascii_uppercase(), n.to_ascii_uppercase()]);
}
if strict && !(separator(c) || c == b';' || c < 0x20) {
return None;
}
self.at += 1;
}
}
/// One `@PJL` line: an `ENTER LANGUAGE` command picks what follows.
fn pjl_line(&mut self) {
let rest = &self.b[self.at..];
let end = rest.iter().position(|&c| c == b'\n').map_or(rest.len(), |n| n + 1);
// A command names its language within its first 256 bytes; longer lines aren't copied.
let line = String::from_utf8_lossy(&rest[..end.min(256)]).to_ascii_uppercase();
if let Some(lang) = line.split_once("LANGUAGE").map(|(_, l)| l.trim_start_matches([' ', '=']).trim()) {
self.mode = if lang.starts_with("HPGL") { Mode::Hpgl } else { Mode::Pcl };
}
self.at += end;
}
/// An escape sequence at the current byte, with the data it carries.
fn escape(&mut self) {
self.at += 1;
let Some(c) = self.peek() else { return };
self.at += 1;
match c {
// Universal Exit Language (`ESC%-12345X`) and the language switches (`ESC%#B` to HP-GL,
// `ESC%#A` to PCL or HP RTL).
b'%' => {
let (_, end) = self.value();
match end {
Some(b'X') => self.mode = Mode::Pjl,
Some(b'B') => self.mode = Mode::Hpgl,
Some(b'A') => self.mode = Mode::Pcl,
_ => {}
}
}
// Reset: PCL follows, until a language switch.
b'E' => self.mode = Mode::Pcl,
// HP-GL device control: `ESC.` and a letter, with parameters up to a colon.
b'.' => {
let Some(kind) = self.peek() else { return };
self.at += 1;
if !b"()YZBEJKLORUX".contains(&kind) {
let rest = &self.b[self.at..self.b.len().min(self.at + 80)];
if let Some(n) = rest.iter().position(|&c| c == b':')
&& rest[..n].iter().all(|c| c.is_ascii_digit() || matches!(c, b';' | b' ' | b','))
{
self.at += n + 1;
}
}
}
// Parameterized PCL: a group character, then values each ending in a letter (upper case
// ends the sequence); `W`, `*b…V` (raster data by plane) and `&p…X` (transparent print
// data) are followed by that many bytes of data. Without a group character (`ESC(8U`,
// `ESC)0N`), one value and the letter ending it.
0x21..=0x2f => {
let Some(group) = self.peek().filter(|g| (0x60..=0x7e).contains(g)) else {
self.value();
return;
};
self.at += 1;
loop {
let (v, end) = self.value();
let Some(end) = end else { return };
let upper = end.to_ascii_uppercase();
if upper == b'W' || (c, group, upper) == (b'*', b'b', b'V') || (c, group, upper) == (b'&', b'p', b'X') {
let n = v.max(0.0).min((self.b.len() - self.at) as f64) as usize;
if (c, group) == (b'*', b'b') && n > 0 {
self.raster = true;
}
self.at += n;
}
if (c, group, end) == (b'*', b'r', b'A') {
self.raster = true;
}
if !end.is_ascii_lowercase() {
return;
}
}
}
// A two-character escape.
_ => {}
}
}
/// A PCL value (`[+-]digits[.digits]`, any part missing) and the character that ends it; `None`
/// when that is not a letter or `@` (which is then left unread).
fn value(&mut self) -> (f64, Option<u8>) {
let v = self.number_here().unwrap_or(0.0);
match self.peek() {
Some(c) if c.is_ascii_alphabetic() || c == b'@' => {
self.at += 1;
(v, Some(c))
}
_ => (v, None),
}
}
/// A number starting at the current byte (`[+-]digits[.digits]`), `None` when it has no digit
/// (its sign and point are read all the same).
fn number_here(&mut self) -> Option<f64> {
let mut neg = false;
if let Some(c @ (b'+' | b'-')) = self.peek() {
neg = c == b'-';
self.at += 1;
}
let (mut v, mut digits, mut scale) = (0.0f64, 0usize, 1.0f64);
let mut point = false;
while let Some(c) = self.peek() {
if c.is_ascii_digit() {
if digits < MAX_DIGITS {
if point {
scale /= 10.0;
v += f64::from(c - b'0') * scale;
} else {
v = v * 10.0 + f64::from(c - b'0');
}
} else if !point {
// Past the digits that count, an integer part keeps its size.
v *= 10.0;
}
digits += 1;
} else if c == b'.' && !point {
point = true;
} else {
break;
}
self.at += 1;
}
let v = v.min(f64::MAX);
(digits > 0).then_some(if neg { -v } else { v })
}
/// The next numeric parameter of the instruction being read, or `None` at its end (a semicolon
/// ending it is read).
pub fn number(&mut self) -> Option<f64> {
loop {
let c = self.peek()?;
if separator(c) {
self.at += 1;
} else if c.is_ascii_digit() || matches!(c, b'+' | b'-' | b'.') {
if let Some(v) = self.number_here() {
return Some(v);
}
} else {
if c == b';' {
self.at += 1;
}
return None;
}
}
}
/// Up to `out.len()` numeric parameters into `out` (the rest are read and dropped) → how many.
pub fn numbers(&mut self, out: &mut [f64]) -> usize {
let mut n = 0;
while let Some(v) = self.number() {
if let Some(slot) = out.get_mut(n) {
*slot = v;
}
n += 1;
}
n.min(out.len())
}
/// Read and drop the parameters of the instruction being read: numbers and quoted strings.
pub fn params(&mut self) {
loop {
while self.number().is_some() {}
if self.peek() != Some(b'"') {
return;
}
self.quoted();
}
}
/// Read and drop numeric parameters → whether a semicolon ended them (an instruction the reader
/// doesn't know, written out in full).
pub fn closed_params(&mut self) -> bool {
while self.number().is_some() {}
self.at > 0 && self.b.get(self.at - 1) == Some(&b';')
}
/// A comment (CO): its quoted string or nothing, then the terminator or the end → whether it
/// is one.
pub fn comment(&mut self) -> bool {
while self.peek().is_some_and(separator) {
self.at += 1;
}
match self.peek() {
Some(b'"') => self.quoted(),
Some(b';') => {
self.at += 1;
true
}
None => true,
Some(_) => false,
}
}
/// The text of a label, up to and including `terminator` (or the end).
pub fn label(&mut self, terminator: u8) {
let rest = &self.b[self.at..];
self.at += rest.iter().position(|&c| c == terminator).map_or(rest.len(), |n| n + 1);
}
/// A quoted string (CO): the parameters up to its closing quote, then the terminator → whether
/// there was one.
pub fn quoted(&mut self) -> bool {
while self.peek().is_some_and(separator) {
self.at += 1;
}
let found = self.peek() == Some(b'"');
if found {
self.at += 1;
let rest = &self.b[self.at..];
self.at += rest.iter().position(|&c| c == b'"').map_or(rest.len(), |n| n + 1);
}
if self.peek() == Some(b';') {
self.at += 1;
}
found
}
/// The character right after the mnemonic (DT, SM), `None` when it is a semicolon or the end
/// (the semicolon is read).
pub fn char(&mut self) -> Option<u8> {
let c = self.peek()?;
self.at += 1;
(c != b';').then_some(c)
}
/// The next item of a PE instruction, `None` at its end (its semicolon is read).
pub fn pe(&mut self, st: &mut Pe) -> Option<PeItem> {
loop {
let raw = self.peek()?;
let c = raw & 0x7f;
// Spaces, deletes, control characters and bytes 128 to 160 and 255 are ignored.
if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 {
self.at += 1;
continue;
}
match c {
b';' => {
self.at += 1;
return None;
}
// Flags keep their meaning with the eighth bit set; digits are 63 and up (191 and up).
b':' | b'<' | b'>' | b'=' | b'7' | b'9' if raw < 63 || (0xb7..191).contains(&raw) => {
self.at += 1;
match c {
b':' => return self.pe_value(st).map(PeItem::Pen).or_else(|| self.end_pe()),
b'<' => st.up = true,
b'>' => match self.pe_value(st) {
Some(n) => st.fraction_bits = n.clamp(0, 52) as u32,
None => return self.end_pe(),
},
b'=' => st.absolute = true,
b'7' => st.seven_bit = true,
_ => return Some(PeItem::Rect),
}
}
_ => {
let scale = 0.5f64.powi(st.fraction_bits as i32);
let (Some(x), Some(y)) = (self.pe_value(st), self.pe_value(st)) else { return self.end_pe() };
let item = PeItem::Point { x: x as f64 * scale, y: y as f64 * scale, up: st.up, absolute: st.absolute };
(st.up, st.absolute) = (false, false);
return Some(item);
}
}
}
}
/// The rest of a PE instruction that can't be decoded: see [`Lexer::skip_pe`].
fn end_pe(&mut self) -> Option<PeItem> {
self.skip_pe();
None
}
/// The data of a PE instruction, up to and including its semicolon, unread: its data is never
/// read as instructions.
pub fn skip_pe(&mut self) {
let rest = &self.b[self.at..];
self.at += rest.iter().position(|&c| c == b';').map_or(rest.len(), |n| n + 1);
}
/// One encoded PE number, `None` when the instruction ends inside it (or a byte that is no
/// digit comes first, which is read).
fn pe_value(&mut self, st: &Pe) -> Option<i64> {
let (base, low, high): (u64, std::ops::RangeInclusive<u8>, std::ops::RangeInclusive<u8>) =
if st.seven_bit { (32, 63..=94, 95..=126) } else { (64, 63..=126, 191..=254) };
let (mut v, mut place) = (0u64, 1u64);
loop {
let raw = self.peek()?;
let c = if st.seven_bit { raw & 0x7f } else { raw };
if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 {
self.at += 1;
continue;
}
if c == b';' {
return None;
}
self.at += 1;
let (digit, last) = if low.contains(&c) {
(u64::from(c - 63), false)
} else if high.contains(&c) {
(u64::from(c - high.start()), true)
} else {
return None;
};
v = v.saturating_add(digit.saturating_mul(place));
place = place.saturating_mul(base);
if last {
// The low bit is the sign.
let n = i64::try_from(v >> 1).unwrap_or(i64::MAX);
return Some(if v & 1 == 1 { -n } else { n });
}
}
}
}
//! Shared HP-GL byte lexer; drawing interpretation remains local.
pub(super) use craft_plotter::hpgl::lex::{ETX, Lexer, Pe, PeItem};
+33 -6
View File
@@ -7,6 +7,8 @@
//! hatches, type text entities or glyph outlines, and placed images image entities linked to PNG
//! or JPEG files the caller writes next to the drawing. Coordinates are y-up, in drawing units: `scale` units per
//! `unit` of the art, with the origin at the bottom-left corner of [`DxfOptions::region`].
//! [`export_drawings`] writes one such drawing for each of several regions, applying the live
//! effects once for all of them.
//!
//! What DXF can't hold (blending modes, opacity masks, raster effects, gradients, patterns,
//! clipping) is approximated or left out, and each such loss comes back as a warning.
@@ -436,18 +438,43 @@ pub const SCALE_RANGE: std::ops::RangeInclusive<f64> = 1e-6..=1e6;
/// Write `doc` as a DXF drawing with `opts`. Live geometry effects are applied first; template
/// layers, guides and hidden objects are left out.
pub fn export(doc: &Document, opts: &DxfOptions) -> Result<DxfOutput, String> {
Ok(export_drawings(doc, opts, &[(opts.region, opts.crop)])?.pop().unwrap_or_default())
}
/// Write `doc` as one DXF drawing for each `(region, crop)` of `drawings`, in order, each as
/// [`export`] writes it with `opts` and that region and crop. Live geometry effects are applied
/// once for all the drawings.
pub fn export_drawings(doc: &Document, opts: &DxfOptions, drawings: &[(Rect, bool)]) -> Result<Vec<DxfOutput>, String> {
export_drawings_with(doc, opts, drawings, bake_for_drawings)
}
/// `doc` with its live geometry effects applied and its symbols' art placed, or `None` when
/// nothing changes.
fn bake_for_drawings(doc: &Document) -> Option<Document> {
// Symbols' art is placed without clipping, as the scene places it.
let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false };
vectorcraft_effects::bake_document_placing_symbols(doc, false, layers)
}
/// [`export_drawings`] with `bake` applying the live effects.
fn export_drawings_with(
doc: &Document,
opts: &DxfOptions,
drawings: &[(Rect, bool)],
bake: impl Fn(&Document) -> Option<Document>,
) -> Result<Vec<DxfOutput>, String> {
if !(opts.scale.is_finite() && SCALE_RANGE.contains(&opts.scale)) {
return Err(format!("scale must be a number from {} to {}, not {}", SCALE_RANGE.start(), SCALE_RANGE.end(), opts.scale));
}
let r = opts.region;
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
if drawings.iter().any(|(r, _)| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())) {
return Err("the export region is not finite".into());
}
// Symbols' art is placed without clipping, as the scene places it.
let baked =
vectorcraft_effects::bake_document_placing_symbols(doc, false, vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true });
if drawings.is_empty() {
return Ok(vec![]);
}
let baked = bake(doc);
let doc = baked.as_ref().unwrap_or(doc);
Ok(scene::Scene::new(doc, opts).run())
Ok(drawings.iter().map(|&(region, crop)| scene::Scene::new(doc, &DxfOptions { region, crop, ..opts.clone() }).run()).collect())
}
#[cfg(test)]
+20 -19
View File
@@ -5,7 +5,6 @@
//! filled outlines where the look needs them.
use std::collections::HashMap;
use std::io::Cursor;
use kurbo::PathEl;
use vectorcraft_color::Paint;
@@ -1403,35 +1402,37 @@ impl<'a> Scene<'a> {
/// Image `im` as a file in the chosen format, and its size in pixels.
fn encode_image(&self, im: &ImageObject) -> Result<(DxfImage, (u32, u32)), String> {
use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image as CodecImage, SampleType};
let blob = self.doc.image_blob(im).filter(|b| !b.bytes.is_empty()).ok_or_else(|| "an image has no pixels and was left out".to_string())?;
// The pixels it converts to (RGBA, 4 bytes each) are read from its header before decoding.
let (w, h) = image::ImageReader::new(Cursor::new(blob.bytes.as_slice()))
.with_guessed_format()
.ok()
.and_then(|r| r.into_dimensions().ok())
.ok_or_else(|| UNDECODED.to_string())?;
let (w, h) = vectorcraft_doc::header_size(&blob.bytes).ok_or_else(|| UNDECODED.to_string())?;
if u64::from(w) * u64::from(h) > MAX_IMAGE_PIXELS {
return Err("an image is too large for DXF and was left out".to_string());
}
let img = image::load_from_memory(&blob.bytes).map_err(|_| UNDECODED.to_string())?;
let size = (img.width(), img.height());
let mut bytes = vec![];
let written = match self.o.raster {
RasterFormat::Png => img.to_rgba8().write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png),
let decoded = craft_image_codecs::decode(&blob.bytes).map_err(|_| UNDECODED.to_string())?;
let size = decoded.dimensions();
let mut rgba = decoded.to_rgba8();
let bytes = match self.o.raster {
RasterFormat::Png => {
let img = CodecImage::from_raw(size.0, size.1, ChannelLayout::Rgba, SampleType::U8, rgba)
.map_err(|e| format!("an image could not be written: {e}"))?;
craft_image_codecs::encode(&img, Format::Png, &EncodeOptions::default())
}
RasterFormat::Jpeg => {
// No alpha in JPEG: transparent pixels over white.
let mut rgba = img.to_rgba8();
for p in rgba.pixels_mut() {
let mut rgb = Vec::with_capacity(rgba.len() / 4 * 3);
for p in rgba.as_chunks_mut::<4>().0 {
let a = u32::from(p[3]);
for c in 0..3 {
p[c] = ((u32::from(p[c]) * a + 255 * (255 - a)) / 255) as u8;
for c in &p[..3] {
rgb.push(((u32::from(*c) * a + 255 * (255 - a)) / 255) as u8);
}
}
let rgb = image::DynamicImage::ImageRgba8(rgba).to_rgb8();
rgb.write_with_encoder(image::codecs::jpeg::JpegEncoder::new_with_quality(&mut bytes, 90))
let img = CodecImage::from_raw(size.0, size.1, ChannelLayout::Rgb, SampleType::U8, rgb)
.map_err(|e| format!("an image could not be written: {e}"))?;
craft_image_codecs::encode(&img, Format::Jpeg, &EncodeOptions { jpeg_quality: 90, ..EncodeOptions::default() })
}
};
written.map_err(|e| format!("an image could not be written: {e}"))?;
}
.map_err(|e| format!("an image could not be written: {e}"))?;
Ok((DxfImage { name: format!("{}.{}", blob.content_key(), self.o.raster.extension()), bytes }, size))
}
}
+224 -4
View File
@@ -852,8 +852,19 @@ fn the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_stro
/// A 4 × 2 px PNG placed at (10, 20) under key `raster-1`, and before it in paint order
/// `fill`'s rectangle.
fn image_and_fill_doc(fill: Paint) -> Document {
let mut png = vec![];
image::RgbaImage::from_pixel(4, 2, image::Rgba([0, 0, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let png = craft_image_codecs::encode(
&craft_image_codecs::Image::from_raw(
4,
2,
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U8,
[0u8, 0, 255, 255].repeat(8),
)
.unwrap(),
craft_image_codecs::Format::Png,
&craft_image_codecs::EncodeOptions::default(),
)
.unwrap();
let mut d = doc_with(|d| {
let im = ImageObject {
key: "raster-1".into(),
@@ -1312,8 +1323,19 @@ fn a_font_height_reference_is_written_as_the_size_drawn() {
#[test]
fn images_link_png_or_jpeg_files() {
let mut png = vec![];
image::RgbaImage::from_pixel(4, 2, image::Rgba([255, 0, 0, 128])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
let png = craft_image_codecs::encode(
&craft_image_codecs::Image::from_raw(
4,
2,
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U8,
[255u8, 0, 0, 128].repeat(8),
)
.unwrap(),
craft_image_codecs::Format::Png,
&craft_image_codecs::EncodeOptions::default(),
)
.unwrap();
let mut d = doc_with(|d| {
let im = ImageObject {
key: "raster-1".into(),
@@ -1471,3 +1493,201 @@ fn export_bytes_match_shared_writer_goldens() {
assert_eq!(got, expected, "DXF bytes changed versus {}", path.display());
}
}
/// One drawing written by applying the live effects for it alone and walking the result, as each
/// drawing of a multi-drawing export was written before [`export_drawings`].
fn export_baking_alone(doc: &Document, opts: &DxfOptions) -> DxfOutput {
let baked = crate::bake_for_drawings(doc);
crate::scene::Scene::new(baked.as_ref().unwrap_or(doc), opts).run()
}
/// A written drawing's bytes, linked images (name and bytes), warnings and setting notes.
type Written = (Vec<u8>, Vec<(String, Vec<u8>)>, Vec<String>, Vec<String>);
/// Every field of a written drawing, for comparing two.
fn written(out: &DxfOutput) -> Written {
let images = out.images.iter().map(|i| (i.name.clone(), i.bytes.clone())).collect();
(out.bytes.clone(), images, out.warnings.clone(), out.setting_notes.clone())
}
/// A Transform effect that moves its object `x` pt right.
fn moved_by(mut n: Node, x: f64) -> Node {
n.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": x}), visible: true });
n
}
/// A line moved by a Transform effect, an instance of a symbol whose art carries the same effect
/// stained by its fill, a semi-transparent line in a blending mode, and a placed PNG image.
fn drawings_doc() -> Document {
let png = craft_image_codecs::encode(
&craft_image_codecs::Image::from_raw(
2,
2,
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U8,
[0u8, 128, 255, 255].repeat(4),
)
.unwrap(),
craft_image_codecs::Format::Png,
&craft_image_codecs::EncodeOptions::default(),
)
.unwrap();
let mut d = doc_with(|d| {
let line = path(d, shapes::line((10.0, 10.0).into(), (20.0, 10.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0);
let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY });
instance.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0).into();
let mut faint = path(d, shapes::line((10.0, 90.0).into(), (190.0, 90.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0);
faint.opacity = 0.5;
faint.blend = vectorcraft_color::BlendMode::Multiply;
let im = ImageObject {
key: "raster-1".into(),
width: 2,
height: 2,
xf: Affine::translate((150.0, 20.0)) * Affine::scale(10.0),
link: None,
placement: Default::default(),
pixels: None,
};
vec![moved_by(line, 100.0), instance, faint, Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))]
});
let art = path(&mut d, shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved_by(art, 20.0)) });
d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None });
d
}
#[test]
fn drawings_apply_the_live_effects_once_and_match_drawings_written_alone() {
let d = drawings_doc();
assert!(crate::bake_for_drawings(&d).is_some(), "the document has live effects to apply");
// The left and right halves cropped, the whole page uncropped, and a region off the page.
let drawings = [
(Rect::new(0.0, 0.0, 100.0, 100.0), true),
(Rect::new(100.0, 0.0, 200.0, 100.0), true),
(Rect::new(0.0, 0.0, 200.0, 100.0), false),
(Rect::new(300.0, 0.0, 400.0, 100.0), true),
];
// With every option, and with images and hatches left out (which adds setting notes).
let all_in = opts(&d);
for o in [all_in.clone(), DxfOptions { include_images: false, include_hatches: false, ..all_in }] {
let bakes = std::cell::Cell::new(0);
let outs = crate::export_drawings_with(&d, &o, &drawings, |doc| {
bakes.set(bakes.get() + 1);
crate::bake_for_drawings(doc)
})
.unwrap();
assert_eq!(bakes.get(), 1, "the live effects are applied once for every drawing");
assert_eq!(outs.len(), drawings.len());
for ((region, crop), out) in drawings.iter().zip(&outs) {
let alone = export_baking_alone(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() });
assert_eq!(written(out), written(&alone), "the drawing over {region:?}, crop {crop}");
let one = export(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() }).unwrap();
assert_eq!(written(&one), written(&alone), "export over {region:?}, crop {crop}");
}
let public: Vec<_> = export_drawings(&d, &o, &drawings).unwrap().iter().map(written).collect();
assert_eq!(public, outs.iter().map(written).collect::<Vec<_>>());
// The halves hold different art, the left half a line with losses, and the region off the
// page nothing.
assert!(!entities(&outs[0]).is_empty() && !entities(&outs[1]).is_empty() && !outs[0].warnings.is_empty());
assert_ne!(outs[0].bytes, outs[1].bytes);
assert!(entities(&outs[3]).is_empty() && outs[3].images.is_empty());
if o.include_images {
assert_eq!(outs[2].images.len(), 1);
} else {
assert!(!outs[2].setting_notes.is_empty() && outs[2].images.is_empty());
}
}
}
#[test]
fn drawings_are_checked_before_the_live_effects_are_applied() {
let d = drawings_doc();
let o = opts(&d);
let bakes = std::cell::Cell::new(0);
let count = |doc: &Document| {
bakes.set(bakes.get() + 1);
crate::bake_for_drawings(doc)
};
let page = (d.artboards[0].rect, false);
let off = (Rect::new(0.0, 0.0, f64::NAN, 100.0), false);
assert_eq!(crate::export_drawings_with(&d, &o, &[page, off], count).unwrap_err(), "the export region is not finite");
let e = crate::export_drawings_with(&d, &DxfOptions { scale: 0.0, ..o.clone() }, &[page], count).unwrap_err();
assert!(e.starts_with("scale must be a number"), "{e}");
assert!(crate::export_drawings_with(&d, &o, &[], count).unwrap().is_empty());
assert_eq!(bakes.get(), 0, "nothing is applied for drawings that are refused or for none");
}
/// The thread's time on the CPU in nanoseconds where Linux reports it, otherwise `None`.
fn thread_cpu_ns() -> Option<u64> {
std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok()
}
/// Time a Use Artboards export of eight artboards whose art has live effects, written drawing by
/// drawing with the effects applied for each (as before [`export_drawings`]) and with
/// [`export_drawings`], alternating, seven times each, and check that both write the same
/// drawings. Prints the median of each in milliseconds of the thread's CPU time (on Linux) and of
/// wall-clock time.
/// Run with `cargo test --release -p vectorcraft-cad --lib dxf_artboards_bake_perf -- --ignored --nocapture`.
#[test]
#[ignore = "manual timing probe; wall-clock performance depends on machine load"]
fn dxf_artboards_bake_perf() {
const BOARDS: usize = 8;
let mut d = Document::new(200.0 * BOARDS as f64, 200.0);
let layer = d.layers[0].id;
let effect = |id: &str, params: serde_json::Value| vectorcraft_doc::Effect { id: id.into(), params, visible: true };
let mut art = vec![];
for i in 0..50 {
let (x, y) = (f64::from(i % 10) * 5.0, f64::from(i / 10) * 5.0);
art.push(Arc::new(path(&mut d, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), Paint::None, Paint::solid(Color::BLACK), 0.5)));
}
let mut cell = Node::group(d.alloc_id(), art);
cell.appearance.effects.push(effect("distort.zigZag", serde_json::json!({"size": 1.0, "relative": false, "ridges": 4, "points": "smooth"})));
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Cell".into(), art: Arc::new(cell) });
for b in 0..BOARDS {
let x0 = 200.0 * b as f64;
for i in 0..250 {
let (x, y) = (x0 + f64::from(i % 25) * 8.0, f64::from(i / 25) * 8.0);
let mut n = path(&mut d, shapes::ellipse(Rect::new(x, y, x + 6.0, y + 6.0)), Paint::None, Paint::solid(Color::BLACK), 0.5);
let params = serde_json::json!({"size": 1.0, "relative": false, "detail": 10.0, "points": "smooth", "seed": i});
n.appearance.effects.push(effect("distort.roughen", params));
d.insert(Some(layer), usize::MAX, n).unwrap();
}
for i in 0..20 {
let xf = Affine::translate((x0 + f64::from(i % 5) * 40.0, 100.0 + f64::from(i / 5) * 25.0));
let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Cell".into(), xf });
d.insert(Some(layer), usize::MAX, instance).unwrap();
}
}
let o = DxfOptions { unit: Unit::Points, ..DxfOptions::default() };
let drawings: Vec<(Rect, bool)> = (0..BOARDS).map(|b| (Rect::new(200.0 * b as f64, 0.0, 200.0 * (b + 1) as f64, 200.0), true)).collect();
let before = || drawings.iter().map(|&(region, crop)| export_baking_alone(&d, &DxfOptions { region, crop, ..o.clone() })).collect::<Vec<_>>();
let after = || export_drawings(&d, &o, &drawings).unwrap();
let time = |f: &dyn Fn() -> Vec<DxfOutput>| {
let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now());
let outs = f();
let wall = wall.elapsed().as_secs_f64() * 1000.0;
let cpu = cpu.zip(thread_cpu_ns()).map(|(a, b)| (b - a) as f64 / 1e6);
(outs, cpu, wall)
};
let (mut runs_before, mut runs_after) = (vec![], vec![]);
for _ in 0..7 {
let (a, cpu_a, wall_a) = time(&before);
let (b, cpu_b, wall_b) = time(&after);
assert_eq!(a.len(), BOARDS);
assert_eq!(a.iter().map(written).collect::<Vec<_>>(), b.iter().map(written).collect::<Vec<_>>(), "both write the same drawings");
runs_before.push((cpu_a, wall_a));
runs_after.push((cpu_b, wall_b));
}
let median = |runs: &[(Option<f64>, f64)], cpu: bool| {
let mut v: Vec<f64> = runs.iter().filter_map(|r| if cpu { r.0 } else { Some(r.1) }).collect();
v.sort_by(f64::total_cmp);
v.get(v.len() / 2).copied()
};
for (name, runs) in [("drawing by drawing", &runs_before), ("export_drawings", &runs_after)] {
println!(
"{name}: {BOARDS} artboards, median CPU {:?} ms, median wall {:?} ms; runs (CPU ms, wall ms) {runs:?}",
median(runs, true),
median(runs, false)
);
}
}
+14 -3
View File
@@ -347,7 +347,9 @@ pub fn profiles_generation() -> u64 {
/// Profile `name` as an ICC file to embed in an export: any RGB or CMYK profile of [`profiles`]
/// (by its current or legacy name), or [`GRAY`]. Built-in profiles are written in code from the
/// CMS: the RGB spaces from their primaries, the CMYK spaces as lookup tables sampled from their
/// model (both directions, perceptual and relative colorimetric, Lab PCS); a profile the user
/// model (both directions, perceptual and relative colorimetric, Lab PCS, with the model's paper
/// as the media white point; the colorimetric Lab → CMYK table without black-point
/// compensation, the perceptual and saturation ones with it); a profile the user
/// loaded is the file it came from. Cached.
pub fn icc_bytes(name: &str) -> Result<Arc<[u8]>, CmsError> {
static CACHE: Mutex<Vec<(String, Arc<[u8]>)>> = Mutex::new(Vec::new());
@@ -361,8 +363,17 @@ pub fn icc_bytes(name: &str) -> Result<Arc<[u8]>, CmsError> {
let bytes: Arc<[u8]> = if name == GRAY {
icc::encode(&icc::gray_profile(name))?
} else if BUILTIN_CMYK.contains(&name) {
let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() })?;
icc::encode(&icc::cmyk_profile(name, |c| cms.cmyk_to_lab(c), |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
// The perceptual and saturation tables map the shadows with black-point compensation; the
// colorimetric table is the inverse of the CMYK → Lab table, without it.
let mapped = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..ColorSettings::default() })?;
let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..ColorSettings::default() })?;
let paper = match &cms.cmyk {
CmykSpace::Generic(g) => g.paper_xyz(),
CmykSpace::Device | CmykSpace::Icc(_) => lab::D50,
};
let to_lab = |c| cms.cmyk_to_lab(c);
let shadows = |l| mapped.lab_to_cmyk(l, Intent::RelativeColorimetric);
icc::encode(&icc::cmyk_profile(name, paper, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))?
} else {
icc::builtin_rgb_bytes(name)?
}
+5
View File
@@ -133,6 +133,11 @@ pub struct GenericCmyk {
}
impl GenericCmyk {
/// Absolute XYZ (D50) of the paper.
pub fn paper_xyz(&self) -> [f32; 3] {
self.paper_xyz
}
pub fn new(params: GenericCmykParams) -> Self {
let paper_xyz = lab_to_xyz(params.paper);
let mut prim = [D50; 16];
+26 -12
View File
@@ -446,11 +446,20 @@ const B2A_GRID: usize = 17;
const GAMUT_GRID: usize = 9;
/// A CMYK output profile sampled from a conversion: `to_lab` (CMYK → media-relative Lab) in a
/// 9⁴ table, `from_lab` (Lab → CMYK, gamut-mapped) in a 17³ table, Lab PCS (ICC v4 encoding).
/// 9⁴ table, and Lab → CMYK in 17³ tables, Lab PCS (ICC v4 encoding): `mapped` (gamut-mapped,
/// with black-point compensation) for the perceptual and saturation intents, `colorimetric` (the
/// colorimetric inverse of `to_lab`) for the colorimetric intents and the gamut tag.
/// It carries every tag ICC.1 requires of an output profile: the tables for all three intents
/// and the gamut tag (Windows rejects a CMYK profile without them, so Photos couldn't show a CMYK
/// TIFF that embedded one, #2707).
pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, from_lab: impl Fn(lab::Lab) -> [f32; 4]) -> ColorProfile {
/// TIFF that embedded one, #2707). The media white point is `paper` (absolute XYZ, D50), which
/// the ICC-absolute colorimetric intent reproduces.
pub(super) fn cmyk_profile(
name: &str,
paper: [f32; 3],
to_lab: impl Fn([f32; 4]) -> lab::Lab,
mapped: impl Fn(lab::Lab) -> [f32; 4],
colorimetric: impl Fn(lab::Lab) -> [f32; 4],
) -> ColorProfile {
let unit = |i: usize, n: usize| i as f32 / (n - 1) as f32;
let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0).round() as u16;
let mut a2b = Vec::with_capacity(A2B_GRID.pow(4) * 3);
@@ -459,17 +468,21 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr
let l = to_lab(cmyk);
a2b.extend([l.l / 100.0, (l.a + 128.0) / 255.0, (l.b + 128.0) / 255.0].map(q));
}
let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4);
for i in 0..B2A_GRID.pow(3) {
let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID));
b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q));
}
let b2a_of = |from_lab: &dyn Fn(lab::Lab) -> [f32; 4]| {
let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4);
for i in 0..B2A_GRID.pow(3) {
let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID));
b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q));
}
b2a
};
let (b2a_mapped, b2a) = (b2a_of(&mapped), b2a_of(&colorimetric));
// Gamut: 0 where a colour separates and comes back within a ΔE of 3, else out of gamut.
let mut gamut = Vec::with_capacity(GAMUT_GRID.pow(3));
for i in 0..GAMUT_GRID.pow(3) {
let [l, a, b] = [2, 1, 0].map(|d| unit(i / GAMUT_GRID.pow(d) % GAMUT_GRID, GAMUT_GRID));
let want = lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0);
gamut.push(if lab::delta_e2000(want, to_lab(from_lab(want))) <= 3.0 { 0 } else { u16::MAX });
gamut.push(if lab::delta_e2000(want, to_lab(colorimetric(want))) <= 3.0 { 0 } else { u16::MAX });
}
let identity = |n: usize| vec![ToneReprCurve::Parametric(vec![1.0]); n];
let table = |inputs: usize, outputs: usize, grid: usize, clut: Vec<u16>| {
@@ -490,6 +503,7 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr
})
};
let a2b = table(4, 3, A2B_GRID, a2b);
let b2a_mapped = table(3, 4, B2A_GRID, b2a_mapped);
let b2a = table(3, 4, B2A_GRID, b2a);
let gamut = table(3, 1, GAMUT_GRID, gamut);
let mut p = ColorProfile::default();
@@ -498,12 +512,12 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr
p.pcs = DataColorSpace::Lab;
p.rendering_intent = RenderingIntent::RelativeColorimetric;
p.white_point = moxcms::WHITE_POINT_D50.to_xyzd();
p.media_white_point = Some(p.white_point);
p.media_white_point = Some(moxcms::Xyzd::new(f64::from(paper[0]), f64::from(paper[1]), f64::from(paper[2])));
p.lut_a_to_b_perceptual = Some(a2b.clone());
p.lut_a_to_b_saturation = Some(a2b.clone());
p.lut_a_to_b_colorimetric = Some(a2b);
p.lut_b_to_a_perceptual = Some(b2a.clone());
p.lut_b_to_a_saturation = Some(b2a.clone());
p.lut_b_to_a_perceptual = Some(b2a_mapped.clone());
p.lut_b_to_a_saturation = Some(b2a_mapped);
p.lut_b_to_a_colorimetric = Some(b2a);
p.gamut = Some(gamut);
labelled(p, name)
+59 -7
View File
@@ -30,11 +30,62 @@ fn cmyk_profiles_convert_like_the_cms() {
let de = delta_e2000(lab::srgb_to_lab(want), lab::srgb_to_lab(got));
assert!(de < 2.5, "{name} {cmyk:?}: {want:?} vs {got:?} (ΔE {de})");
}
// And back: an in-gamut colour separates to about the same inks.
let srgb = cms.cmyk_to_srgb([0.1, 0.6, 0.8, 0.0], false);
let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap();
let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false);
assert!(delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again)) < 3.0, "{back:?}");
// And back: in-gamut colours separate to inks that print them. The Lab → CMYK table is
// the colorimetric inverse of the CMYK → Lab table, with no black-point compensation.
for inks in [
[0.1, 0.6, 0.8, 0.0],
[0.5, 0.1, 0.3, 0.1],
[0.3, 0.3, 0.3, 0.2],
[0.05, 0.05, 0.4, 0.0],
[0.4, 0.3, 0.3, 0.6],
[0.6, 0.5, 0.5, 0.4],
[0.2, 0.2, 0.2, 0.8],
[0.0, 0.0, 0.0, 0.5],
] {
let srgb = cms.cmyk_to_srgb(inks, false);
let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap();
let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false);
let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again));
assert!(de < 1.5, "{name} {inks:?}: {srgb:?} -> {back:?} -> {again:?} (ΔE {de})");
}
// The perceptual table keeps black-point compensation: source black separates to inks
// that print the press's black point, as the CMS separates it with compensation.
let compensated = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..Default::default() }).unwrap();
let want = compensated.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric);
let got = p.from_srgb([0.0; 3], Intent::Perceptual).unwrap();
let printed = |inks: &[f32]| cms.cmyk_to_lab([inks[0], inks[1], inks[2], inks[3]]);
let de = delta_e2000(printed(&want), printed(&got));
assert!(de < 1.5, "{name}: perceptual black {got:?} prints {:?}, want {want:?} ({:?})", printed(&got), printed(&want));
}
}
#[test]
fn cmyk_profiles_separate_saturated_inks_back_without_clipping_to_srgb() {
// CMYK → PCS → CMYK through the profile's own colorimetric tables, by way of linear ProPhoto
// RGB, which holds every color these profiles print, so no display gamut clips the inks.
// Inks that print outside sRGB come back to inks that print the same color.
for name in BUILTIN_CMYK {
let p = IccProfile::from_bytes(None, &icc_bytes(name).unwrap()).unwrap();
let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..Default::default() }).unwrap();
for inks in
[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [1.0, 1.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [1.0, 0.0, 1.0, 0.0]]
{
let back = p.to_same_model_of(&p, &inks, Intent::RelativeColorimetric, false).unwrap();
let de = delta_e2000(cms.cmyk_to_lab(inks), cms.cmyk_to_lab([back[0], back[1], back[2], back[3]]));
// Within the ΔE of 3 that the gamut tag counts as reproduced.
assert!(de <= 3.0, "{name} {inks:?} -> {back:?} (ΔE {de})");
}
}
}
#[test]
fn cmyk_profiles_carry_their_paper_as_the_media_white() {
let generic = generic::swop_like();
let p = parse(&icc_bytes(GENERIC_CMYK).unwrap());
let white = p.media_white_point.unwrap();
let paper = lab::lab_to_xyz(generic.paper);
for (got, want) in [white.x, white.y, white.z].iter().zip(paper) {
assert!((*got - f64::from(want)).abs() < 2e-3, "{white:?} vs {paper:?}");
}
}
@@ -116,9 +167,10 @@ fn black_point_compensation_maps_the_darkest_ink_to_rgb_black() {
let rich = [0.75, 0.68, 0.67, 0.9];
let (on, off) = (icc_cmyk(true).cmyk_to_rgb(rich, Intent::RelativeColorimetric), icc_cmyk(false).cmyk_to_rgb(rich, Intent::RelativeColorimetric));
// Without compensation the profile's black is a dark grey; with it, rich black goes most of
// the way to RGB black (not all: it isn't quite the darkest ink the profile prints).
// the way to RGB black (not all: it isn't quite the darkest ink the profile prints, and the
// profile's Lab → CMYK table carries no compensation of its own).
assert!(off.iter().all(|v| *v > 0.1), "without: {off:?}");
assert!(on.iter().zip(off).all(|(a, b)| *a < 0.08 && *a < b * 0.5), "with: {on:?}, without: {off:?}");
assert!(on.iter().zip(off).all(|(a, b)| *a < 0.09 && *a < b * 0.55), "with: {on:?}, without: {off:?}");
// The screen shows what an sRGB conversion writes, compensated alike.
let srgb = |bpc| {
let c = icc_cmyk(bpc);
+7 -1
View File
@@ -294,13 +294,19 @@ impl GuideOptions {
}
}
/// The share of the way to its target (black or white, cool or warm, gray or full color) that the
/// variation at `step` goes: 0 at the center, the options' reach at the outermost steps.
pub fn step_fraction(opts: &GuideOptions, step: i32) -> f32 {
(step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * opts.reach()
}
/// Variation of `c` at `step` (−steps..=steps: negative towards shades/cool/muted, positive towards
/// tints/warm/vivid; 0 is `c` itself), in `c`'s model.
pub fn variation(c: Color, opts: &GuideOptions, step: i32) -> Color {
if step == 0 {
return c;
}
let f = (step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * opts.reach();
let f = step_fraction(opts, step);
let v = match opts.variation {
Variation::TintsShades => c.lerp(if step < 0 { &Color::BLACK } else { &Color::WHITE }, f),
Variation::WarmCool => {
+15 -6
View File
@@ -192,14 +192,23 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
// A mirrored conic turns counterclockwise, and CSS only turns clockwise: its stops
// are written mirrored about the seam instead.
let mirrored = g.gradient.kind == GradientKind::Conic && g.geom.is_some_and(|geom| geom.is_mirrored());
let stop = |s: &crate::GradientStop| {
let at = if mirrored { 1.0 - s.offset } else { s.offset };
format!("{} {}%", css_color(&s.color, s.opacity), at * 100.0)
let stop = |&(t, c, o): &(f32, Color, f32)| {
let at = if mirrored { 1.0 - t } else { t };
format!("{} {}%", css_color(&c, o), at * 100.0)
};
// Stops that repeat or reflect run that many times across the box.
// Stops that repeat or reflect run that many times across the box. CSS mixes
// hex colors evenly in sRGB between two stops
// (https://www.w3.org/TR/css-color-4/#interpolation-space), so an off-center
// midpoint and the curve of a Perceptual or hue gradient are written as stops
// of their own, each with its color and opacity. A gradient that would need
// more than `MAX_SPREAD_STOPS` stops that way is written with its own stops.
let unrolled = g.gradient.unrolled();
let stops: Vec<String> =
if mirrored { unrolled.stops.iter().rev().map(stop).collect() } else { unrolled.stops.iter().map(stop).collect() };
let expanded: Vec<(f32, Color, f32)> = if unrolled.expanded().nth(crate::gradient::MAX_SPREAD_STOPS).is_none() {
unrolled.expanded_stops()
} else {
unrolled.stops.iter().map(|s| (s.offset, s.color, s.opacity)).collect()
};
let stops: Vec<String> = if mirrored { expanded.iter().rev().map(stop).collect() } else { expanded.iter().map(stop).collect() };
match g.gradient.kind {
GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")),
// CSS sweeps clockwise from straight up; the angle is counted counterclockwise
+93
View File
@@ -284,6 +284,99 @@ fn css_writes_spread_gradient_swatches_with_their_stops_repeated() {
}
}
/// The color and opacity a written CSS gradient value has at `p` (0..1 along its stops), by the
/// CSS rule (https://www.w3.org/TR/css-images-3/#coloring-gradient-line): between two stops the
/// color mixes evenly with premultiplied alpha, in sRGB for hex colors
/// (https://www.w3.org/TR/css-color-4/#interpolation-space); before the first stop and after the
/// last the end colors hold.
fn css_gradient_at(value: &str, p: f64) -> ([f64; 3], f64) {
let list = value.split_once(", ").map_or("", |(_, rest)| rest).trim_end_matches(')');
let stops: Vec<([f64; 3], f64, f64)> = list
.split(", ")
.map(|stop| {
let (hex, at) = stop.split_once(' ').unwrap_or_else(|| panic!("stop {stop:?}"));
let byte = |i: usize| hex.get(1 + 2 * i..3 + 2 * i).map_or(255.0, |h| f64::from(u8::from_str_radix(h, 16).unwrap()));
let at: f64 = at.trim_end_matches('%').parse().unwrap();
([byte(0), byte(1), byte(2)].map(|v| v / 255.0), byte(3) / 255.0, at / 100.0)
})
.collect();
let p = p.clamp(stops[0].2, stops[stops.len() - 1].2);
let i = stops.windows(2).position(|w| p <= w[1].2).unwrap_or(0);
let ((c0, a0, p0), (c1, a1, p1)) = (stops[i], stops[i + 1]);
let w = if p1 > p0 { (p - p0) / (p1 - p0) } else { 1.0 };
let a = a0 + (a1 - a0) * w;
let c = std::array::from_fn(|k| if a > 0.0 { (c0[k] * a0 + (c1[k] * a1 - c0[k] * a0) * w) / a } else { 0.0 });
(c, a)
}
/// A gradient swatch's CSS draws, by the CSS rule, the colors and opacity the swatch has: an
/// off-center midpoint and the curve of a Perceptual or hue gradient are written as stops of their
/// own, also on a reflected and a mirrored conic swatch.
#[test]
fn css_gradient_swatches_draw_their_midpoints_and_curves() {
let check = |label: &str, gp: GradientPaint, at: &dyn Fn(f64) -> f64| {
let lib = SwatchLibrary {
name: "x".into(),
swatches: vec![Swatch { name: "x".into(), paint: Paint::Gradient(Box::new(gp.clone())), global: false, spot: false }],
groups: vec![],
};
let text = written(&lib, PaletteFormat::Css);
let value = text.lines().find_map(|l| l.trim().strip_prefix("--x: ")).unwrap_or_else(|| panic!("{text}")).trim_end_matches(';');
for i in 0..64 {
let p = (f64::from(i) + 0.5) / 64.0;
let (css, css_alpha) = css_gradient_at(value, p);
let (color, opacity) = gp.gradient.sample(at(p) as f32);
let want = color.to_rgb();
let off = (0..3).map(|k| (css[k] - f64::from(want[k])).abs()).fold((css_alpha - f64::from(opacity)).abs(), f64::max);
assert!(off < 2.0 / 255.0, "{label} at {p}: {css:?} {css_alpha} vs {want:?} {opacity}: {value}");
}
};
let ramp = |method| Gradient {
method,
..Gradient::new(
GradientKind::Linear,
vec![GradientStop { midpoint: 0.25, ..GradientStop::new(0.0, Color::rgb8(255, 0, 0)) }, GradientStop::new(1.0, Color::rgb8(0, 0, 255))],
)
};
for method in crate::GradientMethod::ALL {
check(&format!("{method:?}"), GradientPaint::new(ramp(method)), &|p| p);
}
// Opacity through an off-center midpoint, on one color so premultiplying does not change it.
let fade = Gradient::new(
GradientKind::Linear,
vec![
GradientStop { midpoint: 0.25, ..GradientStop::new(0.0, Color::BLACK) },
GradientStop { opacity: 0.0, ..GradientStop::new(1.0, Color::BLACK) },
],
);
check("fade", GradientPaint::new(fade), &|p| p);
let reflected = Gradient { spread: crate::GradientSpread::Reflect, repeats: 2, ..ramp(crate::GradientMethod::Classic) };
let spread = reflected.spreader();
check("reflect", GradientPaint::new(reflected), &spread);
let mut conic = GradientPaint::new(Gradient { kind: GradientKind::Conic, ..ramp(crate::GradientMethod::HueClockwise) });
conic.geom = Some(crate::GradientGeom { start: kurbo::Point::ZERO, end: kurbo::Point::new(0.0, -10.0), aspect: -1.0, focal: None });
check("mirrored conic", conic, &|p| 1.0 - p);
}
/// A gradient swatch whose curve would need more than `MAX_SPREAD_STOPS` stops is written with its
/// own stops.
#[test]
fn css_gradient_swatches_keep_their_stop_count_bounded() {
let n = 4000;
let stops = (0..n)
.map(|i| GradientStop::new(i as f32 / (n - 1) as f32, if i % 2 == 0 { Color::rgb8(255, 0, 0) } else { Color::rgb8(0, 255, 255) }))
.collect();
let g = Gradient { method: crate::GradientMethod::HueClockwise, ..Gradient::new(GradientKind::Linear, stops) };
assert!(g.expanded().nth(crate::gradient::MAX_SPREAD_STOPS).is_some(), "the curve needs more stops than allowed");
let lib = SwatchLibrary {
name: "x".into(),
swatches: vec![Swatch { name: "x".into(), paint: Paint::Gradient(Box::new(GradientPaint::new(g))), global: false, spot: false }],
groups: vec![],
};
let text = written(&lib, PaletteFormat::Css);
assert_eq!(text.matches('%').count(), n, "one stop for each of the gradient's own");
}
#[test]
fn holds_counts_the_swatches_each_format_writes() {
// `sample()` holds the spot color Ink, the linear gradient Fade, the pattern Tiles and two solid colors in a group.
+8 -2
View File
@@ -11,21 +11,27 @@ workspace = true
[features]
# `vectorcraft_doc::blend::spines_built` for other crates' tests (dev-dependencies only).
spine-count = []
# `vectorcraft_doc::symbols_read` for other crates' tests (dev-dependencies only).
symbol-read-count = []
[dependencies]
vectorcraft-geom = { workspace = true }
vectorcraft-color = { workspace = true }
kurbo = { workspace = true }
image = { workspace = true }
# Image headers (PNG and JPEG sizes, `pixels::header_size`) and CMYK JPEG inks (`cmyk`).
craft-image-codecs = { workspace = true }
tiff = { workspace = true }
# 1-bit TIFFs compressed with CCITT Group 3 (Compression 2 and 3).
hayro-ccitt = { workspace = true }
zune-jpeg = { workspace = true }
craft-stream-codecs = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
chrono = { workspace = true }
[dev-dependencies]
flate2 = { workspace = true }
# The CMYK JPEG reader `cmyk` had before craft-image-codecs, kept as the reference its inks match.
zune-jpeg = { workspace = true }
jpeg-encoder = { workspace = true }
proptest = { workspace = true }
+5
View File
@@ -143,6 +143,11 @@ impl Appearance {
pub fn fill_paint(&self) -> Paint {
self.fill().map(|f| f.paint.clone()).unwrap_or(Paint::None)
}
/// Whether any visible fill has non-None paint. Unlike [`Self::fill`], this
/// includes lower fills in the stack; zero opacity still counts for selecting its geometry.
pub fn has_visible_fill(&self) -> bool {
self.items.iter().any(|item| matches!(item, AppearanceItem::Fill(fill) if fill.visible && !fill.paint.is_none()))
}
pub fn stroke_paint(&self) -> Paint {
self.stroke().map(|s| s.paint.clone()).unwrap_or(Paint::None)
}
+6
View File
@@ -71,6 +71,11 @@ pub struct StrokeLayer {
/// Brush applied to the stroke (by brush name).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub brush: Option<String>,
/// This stroke's own brush settings (the Brushes panel's Options of Selected Object): brush
/// definition fields, by their `brush.options` names, that replace the brush's values on this
/// stroke only. Empty: the stroke draws the brush as it is. `vectorcraft-brush` reads them.
#[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
pub brush_options: serde_json::Map<String, serde_json::Value>,
#[serde(default = "one", skip_serializing_if = "crate::skip::is_one")]
pub opacity: f32,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
@@ -170,6 +175,7 @@ impl StrokeLayer {
arrow_scale: (100.0, 100.0),
profile: None,
brush: None,
brush_options: serde_json::Map::new(),
opacity: 1.0,
blend: BlendMode::Normal,
visible: true,
+106
View File
@@ -2174,6 +2174,70 @@ pub fn blend_steps(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<usize> {
StepCount::default().blend(keys, spec, Rail::new(keys, spec).as_ref()).0
}
/// Does each pair of `keys` blended with `spec` ask for the same number of steps
/// ([`blend_step_count`]) when each coordinate it counts from moves by up to `length` points and,
/// for Smooth Color, the difference between keys of different colors by up to `color` (0 to 1)?
/// False when a count sits that close to where it changes, and for Smooth Color by distance when
/// the keys are at most `4 × length` wide or high. Specified Steps always asks for the same number.
pub fn blend_steps_settled(keys: &[Arc<Node>], spec: &BlendSpec, length: f64, color: f64) -> bool {
let rail = Rail::new(keys, spec);
keys.windows(2).enumerate().all(|(i, w)| {
let [a, b] = w else { return true };
match spec.spacing {
BlendSpacing::Steps(_) => true,
// The count is `len / d` rounded, which grows with `len`.
BlendSpacing::Distance(d) => {
let len = rail.as_ref().map_or_else(|| center_of(a).distance(center_of(b)), |r| r.len(i));
let count = |len: f64| blend_step_count(a, b, BlendSpacing::Distance(d), len);
count(len - length) == count(len + length)
}
BlendSpacing::SmoothColor => smooth_color_settled(a, b, length, color),
}
})
}
/// [`blend_steps_settled`] for one pair of Smooth Color keys. Each count [`blend_step_count`]
/// takes grows with what it counts from (the color difference, the keys' reach, the distance
/// between their edges in key sizes), so the pair is settled when the least and the most of
/// these ask for the same count.
fn smooth_color_settled(a: &Node, b: &Node, length: f64, color: f64) -> bool {
let bounds = a.visual_bounds().zip(b.visual_bounds());
let by_level = |d: f64| level_steps(d.max(0.0)) as usize;
match (color_distance(a, b), bounds) {
// Colors that differ, but by too little to count, or by little more: moving them may cross
// where they stop counting as the same. (The same colors stay the same.)
(Some(d), _) if d > 0.0 && d * 255.0 <= 1e-3 + color * 255.0 => false,
(Some(d), Some((ba, bb))) if d * 255.0 > 1e-3 => {
let (ca, cb) = (ba.center(), bb.center());
let reach =
[(ca.x - cb.x).abs(), (ca.y - cb.y).abs(), ba.width(), ba.height(), bb.width(), bb.height()].into_iter().fold(0.0f64, f64::max);
// The centers and sizes move by up to twice `length`.
let by_density = |r: f64| (8.0 * r.max(0.0) + 0.5).floor().clamp(1.0, 254.0) as usize;
let least = by_level(d - color).min(by_density(reach - 2.0 * length));
let most = by_level(d + color).min(by_density(reach + 2.0 * length));
reach.is_finite() && least == most
}
(Some(d), None) if d * 255.0 > 1e-3 => by_level(d - color) == by_level(d + color),
(_, Some((ba, bb))) => {
let (w, h) = ((ba.width() + bb.width()) / 2.0, (ba.height() + bb.height()) / 2.0);
if w <= 4.0 * length || h <= 4.0 * length {
return false;
}
let dx = (ba.x0 - bb.x0).abs().max((ba.x1 - bb.x1).abs());
let dy = (ba.y0 - bb.y0).abs().max((ba.y1 - bb.y1).abs());
// Each edge moves by up to `length`: the distances between them by up to twice that,
// and the mean sizes too.
let q = |dx: f64, dy: f64, w: f64, h: f64| (dx.max(0.0) / w).max(dy.max(0.0) / h);
let count = |q: f64| ((q + 0.5).floor() - 1.0).clamp(1.0, 1000.0) as usize;
let m = 2.0 * length;
let least = q(dx - m, dy - m, w + m, h + m);
let most = q(dx + m, dy + m, w - m, h - m);
least.is_finite() && most.is_finite() && count(least) == count(most)
}
(_, None) => true,
}
}
/// Evaluate a blend: the keys and generated steps in paint order. The steps keep to
/// [`MAX_BLEND_STEPS`] in all ([`blend_steps`]).
pub fn blend_expand(keys: &[Arc<Node>], spec: &BlendSpec) -> Vec<Node> {
@@ -3535,4 +3599,46 @@ mod tests {
let (keys, spec) = blend_parts(&outer).unwrap();
assert_eq!(blend_steps(keys, spec), vec![99]);
}
/// A count is settled when moving the lengths by 0.01 pt and the colors by 0.001 can't change
/// it: Specified Steps always; Specified Distance unless the spine's length is a half step from
/// where its count changes; Smooth Color unless the colors differ by too little to count, the
/// color difference or the keys' reach sits where its count changes, or keys of the same color
/// are at most four times 0.01 pt wide.
#[test]
fn steps_settle_unless_rounding_can_change_their_count() {
let (length, color) = (0.01, 0.001);
let settled = |a: Node, b: Node, spacing: BlendSpacing| {
let spec = BlendSpec { spacing, ..Default::default() };
blend_steps_settled(&[Arc::new(a), Arc::new(b)], &spec, length, color)
};
let filled = |x: f64, size: f64, c: Color| smooth_key((x, 0.0), (size, size), Paint::solid(c), Paint::None, 0.0);
let gray = |x: f64| filled(x, 10.0, Color::rgb(0.5, 0.5, 0.5));
// The keys' centers are 100 pt apart: 100 / 25 is 4, and 100 / (100 / 3.5) is 3.5.
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::Steps(3)));
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::Distance(25.0)));
assert!(!settled(gray(0.0), gray(100.0), BlendSpacing::Distance(100.0 / 3.5)));
// Smooth Color between colors that differ: by a 2,000th of a step, by 51 steps of 255
// (settled) and by 51.5 (where the count changes).
let red = |x: f64, r: f32| filled(x, 10.0, Color::rgb(r, 0.0, 0.0));
assert!(!settled(red(0.0, 0.0), red(100.0, 0.0005), BlendSpacing::SmoothColor));
assert!(settled(red(0.0, 0.0), red(100.0, 51.0 / 255.0), BlendSpacing::SmoothColor));
assert!(!settled(red(0.0, 0.0), red(100.0, 51.5 / 255.0), BlendSpacing::SmoothColor));
// Black to white is counted by the keys' reach, eight steps a point: 10 pt is settled,
// 10.0625 pt (80.5 steps) is not.
let near = |size: f64| settled(filled(0.0, size, Color::BLACK), filled(5.0, size, Color::WHITE), BlendSpacing::SmoothColor);
assert!(near(10.0));
assert!(!near(10.0625));
// Keys without bounds are counted by their colors alone.
let bare = |r: f32| Node::path(NodeId(1), PathData::default(), Appearance::basic(Paint::solid(Color::rgb(r, 0.0, 0.0)), Paint::None, 0.0));
assert!(settled(bare(0.0), bare(51.0 / 255.0), BlendSpacing::SmoothColor));
assert!(!settled(bare(0.0), bare(51.5 / 255.0), BlendSpacing::SmoothColor));
// Keys of the same color are counted by distance in key sizes; keys 0.04 pt wide or less
// are never settled.
assert!(settled(gray(0.0), gray(100.0), BlendSpacing::SmoothColor));
assert!(!settled(filled(0.0, 0.04, Color::rgb(0.5, 0.5, 0.5)), filled(100.0, 0.04, Color::rgb(0.5, 0.5, 0.5)), BlendSpacing::SmoothColor));
assert!(settled(filled(0.0, 0.05, Color::rgb(0.5, 0.5, 0.5)), filled(100.0, 0.05, Color::rgb(0.5, 0.5, 0.5)), BlendSpacing::SmoothColor));
}
}
+148 -108
View File
@@ -9,10 +9,6 @@
use std::io::Cursor;
use std::sync::Arc;
use zune_jpeg::zune_core::bytestream::ZCursor;
use zune_jpeg::zune_core::colorspace::ColorSpace;
use zune_jpeg::zune_core::options::DecoderOptions;
use crate::ImageBlob;
/// Most pixels a CMYK image is decoded with (256 MB of samples): larger ones decode as RGB.
@@ -44,12 +40,7 @@ fn pixels(width: u32, height: u32) -> Option<u64> {
/// The number of colour components of JPEG `bytes` (its frame header); `None` when they aren't a
/// JPEG.
pub fn jpeg_components(bytes: &[u8]) -> Option<usize> {
if !bytes.starts_with(&[0xFF, 0xD8]) {
return None;
}
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
d.decode_headers().ok()?;
Some(d.info()?.components as usize)
craft_image_codecs::jpeg_inks::jpeg_components(bytes)
}
fn is_tiff(bytes: &[u8]) -> bool {
@@ -645,9 +636,7 @@ pub fn tiff_icc_profile(bytes: &[u8]) -> Option<Vec<u8>> {
/// The ICC profile of a JPEG, put together from all its numbered `ICC_PROFILE` APP2 segments;
/// `None` without one.
fn jpeg_icc(bytes: &[u8]) -> Option<Vec<u8>> {
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
d.decode_headers().ok()?;
d.icc_profile().filter(|icc| !icc.is_empty())
craft_image_codecs::jpeg_inks::jpeg_icc_profile(bytes)
}
/// The bytes after an `ICC_PROFILE` APP2 segment's length: its name, then the segment's number and
@@ -851,10 +840,7 @@ impl ImageBlob {
pub fn header_size(&self) -> Option<(u32, u32)> {
let bytes = self.bytes.as_slice();
if bytes.starts_with(&[0xFF, 0xD8]) {
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
d.decode_headers().ok()?;
let (w, h) = d.dimensions()?;
return Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?));
return craft_image_codecs::jpeg_inks::jpeg_dimensions(bytes);
}
tiff(bytes).and_then(|(_, mut d)| d.dimensions().ok())
}
@@ -932,30 +918,10 @@ fn sample_inks(inks: &Inks, x: f64, y: f64, size: u32) -> Option<[u8; 4]> {
/// The ink amounts of a four-component JPEG (its samples inverted back; YCCK converted to CMYK
/// first, as JPEG readers do).
fn jpeg_inks(bytes: &[u8]) -> Option<Inks> {
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
d.decode_headers().ok()?;
let space = d.input_colorspace()?;
if d.info()?.components != 4 || !matches!(space, ColorSpace::CMYK | ColorSpace::YCCK) {
return None;
}
let (w, h) = d.dimensions()?;
let (w, h) = (u32::try_from(w).ok()?, u32::try_from(h).ok()?);
pixels(w, h)?;
d.set_options(DecoderOptions::default().jpeg_set_out_colorspace(space));
let mut data = d.decode().ok()?;
for p in data.as_chunks_mut::<4>().0 {
if space == ColorSpace::YCCK {
let [y, cb, cr] = [p[0], p[1], p[2]].map(f32::from);
// libjpeg's YCCK → CMYK: the complement of the YCbCr colour's RGB.
p[0] = (434.456 - y - 1.402 * cr).clamp(0.0, 255.0) as u8;
p[1] = (119.541 - y + 0.344 * cb + 0.714 * cr).clamp(0.0, 255.0) as u8;
p[2] = (481.816 - y - 1.772 * cb).clamp(0.0, 255.0) as u8;
}
for v in p.iter_mut() {
*v = 255 - *v;
}
}
Inks::new(w, h, data)
let limits = craft_image_codecs::Limits { max_pixels: MAX_CMYK_PIXELS, ..craft_image_codecs::Limits::default() };
let image = craft_image_codecs::jpeg_inks::decode_jpeg_inks(bytes, &limits).ok()?;
let (w, h) = image.dimensions();
Inks::new(w, h, image.into_data())
}
/// The ink amounts of a CMYK TIFF (16-bit samples to 8 bits), its inks stored together or one plane
@@ -1107,9 +1073,20 @@ pub enum Group3Error {
TooLarge { w: u32, h: u32 },
/// A strip or tile ends before its last row or can't be decoded (it holds a code the decoder
/// doesn't read, such as T.4's uncompressed mode, or a row of the wrong width), or a tile is
/// larger than [`crate::MAX_RASTER_ALLOC`] allows as RGBA.
#[error("could not decode image: {0}")]
Damaged(hayro_ccitt::DecodeError),
/// larger than [`crate::MAX_RASTER_ALLOC`] allows as RGBA, or is wider than
/// [`craft_stream_codecs::MAX_CCITT_COLUMNS`].
#[error("could not decode image: {}", damage(*.0))]
Damaged(craft_stream_codecs::CcittErrorKind),
}
/// What went wrong in a Group 3 strip or tile, as [`Group3Error::Damaged`] says it.
fn damage(kind: craft_stream_codecs::CcittErrorKind) -> &'static str {
use craft_stream_codecs::CcittErrorKind as K;
match kind {
K::UnexpectedEof => "unexpected end of input",
K::Overflow => "arithmetic overflow in position calculation",
K::InvalidData => "invalid CCITT code sequence",
}
}
/// The pixels of a 1-bit TIFF compressed with CCITT Group 3, which the image decoder doesn't read,
@@ -1124,7 +1101,7 @@ pub enum Group3Error {
/// an error when the pixels would take more than [`crate::MAX_RASTER_ALLOC`] as RGBA, a tile is
/// larger than that allowance, or a strip or tile can't be decoded or ends before its last row.
pub fn group3_tiff_rgba(bytes: &[u8]) -> Option<Result<image::RgbaImage, Group3Error>> {
use hayro_ccitt::{DecodeError, DecodeSettings, DecoderContext, EncodingMode};
use craft_stream_codecs::{CcittErrorKind as DecodeError, CcittParams, decode_ccitt_raw};
use tiff::tags::Tag;
let (kind, mut d) = tiff(bytes)?;
let compression = d.find_tag_unsigned::<u16>(Tag::Compression).ok().flatten()?;
@@ -1143,12 +1120,8 @@ pub fn group3_tiff_rgba(bytes: &[u8]) -> Option<Result<image::RgbaImage, Group3E
}
let t4_options = d.find_tag_unsigned::<u32>(Tag::Unknown(292)).ok().flatten().unwrap_or(0);
let lsb_first = d.find_tag_unsigned::<u16>(Tag::FillOrder).ok().flatten() == Some(2);
let encoding = if compression == 3 && t4_options & 1 != 0 {
// Each row's tag bit says how it is coded.
EncodingMode::Group3_2D { k: 2 }
} else {
EncodingMode::Group3_1D
};
// Each row's tag bit says how it is coded (K above 0), or every row is one-dimensional (K 0).
let k = if compression == 3 && t4_options & 1 != 0 { 2 } else { 0 };
// The width and height of each strip or tile, and the tags of their offsets and byte counts.
let tiled = d.get_chunk_type() == tiff::decoder::ChunkType::Tile;
let (cw, ch, offsets, counts) = if tiled {
@@ -1182,76 +1155,54 @@ pub fn group3_tiff_rgba(bytes: &[u8]) -> Option<Result<image::RgbaImage, Group3E
budget -= len;
let data = bytes.get(start..start + len)?;
let data: std::borrow::Cow<[u8]> = if lsb_first { data.iter().map(|b| b.reverse_bits()).collect() } else { data.into() };
let settings = DecodeSettings {
columns: cw,
// A tile is coded whole; the last strip only has the image's remaining rows.
rows: if tiled { ch } else { ch.min(h - y0) },
end_of_block: compression == 3,
// A tile is coded whole; the last strip only has the image's remaining rows.
let rows = if tiled { ch } else { ch.min(h - y0) };
let params = CcittParams {
k,
columns: i64::from(cw),
rows: i64::from(rows),
end_of_line: compression == 3,
rows_are_byte_aligned: compression == 2,
encoding,
invert_black: false,
encoded_byte_align: compression == 2,
end_of_block: compression == 3,
// 1 bits are black runs, 0 bits white ones.
black_is_1: true,
};
let mut rows = Rows { out: &mut gray, width: w, height: h, x0, y0, x: 0, y: 0, zero };
if let Err(e) = hayro_ccitt::decode(&data, &mut rows, &mut DecoderContext::new(settings)) {
let Ok(out) = decode_ccitt_raw(&data, &params, rows) else {
// Wider than the decoder reads.
return damaged(DecodeError::Overflow);
};
if let Some(e) = out.error {
return damaged(e);
}
// The data ended, or six EOL codes came, before the strip's or tile's last row.
if rows.y < settings.rows {
if out.rows_decoded < rows {
return damaged(DecodeError::UnexpectedEof);
}
put_rows(&mut gray, (w, h), (x0, y0), cw, &out.data, zero);
}
let gray = image::GrayImage::from_raw(w, h, gray)?;
Some(Ok(image::DynamicImage::ImageLuma8(gray).to_rgba8()))
}
/// Where a strip or tile of a Group 3 TIFF ([`group3_tiff_rgba`]) puts its decoded pixels: `out`
/// holds the image's levels row by row, `width` × `height`, and the strip or tile starts at (`x0`,
/// `y0`). Pixels past the image's right or bottom edge (a tile's padding) are dropped.
struct Rows<'a> {
out: &'a mut [u8],
width: u32,
height: u32,
x0: u32,
y0: u32,
/// The next pixel in the strip or tile.
x: u64,
y: u32,
/// The level of a white run.
zero: u8,
}
impl Rows<'_> {
/// The next `n` pixels of the row, a white run's or a black run's.
fn run(&mut self, white: bool, n: u64) {
let level = if white { self.zero } else { u8::MAX - self.zero };
let row = u64::from(self.y0) + u64::from(self.y);
let left = u64::from(self.x0) + self.x;
let right = left.saturating_add(n).min(u64::from(self.width));
if row < u64::from(self.height) && left < right {
let at = row * u64::from(self.width);
if let (Ok(a), Ok(b)) = (usize::try_from(at + left), usize::try_from(at + right))
&& let Some(px) = self.out.get_mut(a..b)
{
px.fill(level);
}
/// The decoded rows `packed` of a strip or tile of a Group 3 TIFF ([`group3_tiff_rgba`]), `columns`
/// wide, one bit a pixel (1 a black run's), put into `out`, the image's levels row by row, `size`
/// (width, height), from (`x0`, `y0`): a 0 bit as `zero` (the level of a white run), a 1 bit as the
/// other level. Pixels past the image's right or bottom edge (a tile's padding) are dropped.
fn put_rows(out: &mut [u8], size: (u32, u32), (x0, y0): (u32, u32), columns: u32, packed: &[u8], zero: u8) {
let (width, height) = (size.0 as usize, size.1 as usize);
let (x0, y0, columns) = (x0 as usize, y0 as usize, columns as usize);
let stride = columns.div_ceil(8);
if stride == 0 {
return;
}
let across = columns.min(width.saturating_sub(x0));
for (y, row) in packed.chunks(stride).enumerate() {
let Some(at) = (y0 + y < height).then(|| (y0 + y) * width + x0) else { break };
let Some(px) = out.get_mut(at..at + across) else { break };
for (x, p) in px.iter_mut().enumerate() {
let black = row.get(x / 8).is_some_and(|b| b & (0x80 >> (x % 8)) != 0);
*p = if black { u8::MAX - zero } else { zero };
}
self.x = self.x.saturating_add(n);
}
}
impl hayro_ccitt::Decoder for Rows<'_> {
fn push_pixel(&mut self, white: bool) {
self.run(white, 1);
}
fn push_pixel_chunk(&mut self, white: bool, chunk_count: u32) {
self.run(white, u64::from(chunk_count) * 8);
}
fn next_line(&mut self) {
self.y = self.y.saturating_add(1);
self.x = 0;
}
}
@@ -2209,4 +2160,93 @@ mod tests {
assert_eq!(Inks::new(0, 2, vec![]), None, "empty");
assert_eq!(Inks::new(1 << 14, 1 << 13, vec![]), None, "too large");
}
/// The CMYK JPEG reader before craft-image-codecs read the inks (zune-jpeg, every sample
/// inverted, libjpeg's truncating YCCK conversion), the reference [`jpeg_inks`] matches.
fn zune_inks(bytes: &[u8]) -> Option<Inks> {
use zune_jpeg::zune_core::{bytestream::ZCursor, colorspace::ColorSpace, options::DecoderOptions};
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
d.decode_headers().ok()?;
let space = d.input_colorspace()?;
if d.info()?.components != 4 || !matches!(space, ColorSpace::CMYK | ColorSpace::YCCK) {
return None;
}
let (w, h) = d.dimensions()?;
let (w, h) = (u32::try_from(w).ok()?, u32::try_from(h).ok()?);
pixels(w, h)?;
d.set_options(DecoderOptions::default().jpeg_set_out_colorspace(space));
let mut data = d.decode().ok()?;
for p in data.as_chunks_mut::<4>().0 {
if space == ColorSpace::YCCK {
let [y, cb, cr] = [p[0], p[1], p[2]].map(f32::from);
p[0] = (434.456 - y - 1.402 * cr).clamp(0.0, 255.0) as u8;
p[1] = (119.541 - y + 0.344 * cb + 0.714 * cr).clamp(0.0, 255.0) as u8;
p[2] = (481.816 - y - 1.772 * cb).clamp(0.0, 255.0) as u8;
}
for v in p.iter_mut() {
*v = 255 - *v;
}
}
Inks::new(w, h, data)
}
/// CMYK and YCCK JPEGs of many sizes, samplings and qualities, baseline and progressive, with
/// and without Adobe's marker and an ICC profile, read the inks, size, component count and
/// profile the zune-jpeg reader read; so do gray and RGB JPEGs (no inks) and cut-off files.
/// The frames it panicked on (progressive 4:2:0 CMYK, whose C, M and Y `jpeg-encoder` writes at
/// 1×1 and K at 2×2) read as no inks.
#[test]
fn cmyk_jpegs_read_as_the_zune_reader_read_them() {
use jpeg_encoder::{ColorType, Encoder, SamplingFactor};
let reference_size = |bytes: &[u8]| {
use zune_jpeg::zune_core::{bytestream::ZCursor, options::DecoderOptions};
let mut d = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(bytes), DecoderOptions::default());
d.decode_headers().ok()?;
let (w, h) = d.dimensions()?;
Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?, usize::from(d.info()?.components), d.icc_profile().filter(|i| !i.is_empty())))
};
let (mut files, mut read, mut panicked) = (0, 0, 0);
for (i, (w, h)) in [(1u16, 1u16), (7, 3), (16, 16), (33, 31), (100, 77)].into_iter().enumerate() {
let n = usize::from(w) * usize::from(h);
let px: Vec<u8> = (0..n * 4).map(|k| ((k * 2_654_435_761 + i * 97) >> 7) as u8).collect();
for ty in [ColorType::Cmyk, ColorType::CmykAsYcck, ColorType::Rgba, ColorType::Luma] {
for (q, sampling, progressive, icc) in [
(100, SamplingFactor::R_4_4_4, false, false),
(70, SamplingFactor::R_4_2_0, true, true),
(40, SamplingFactor::R_4_2_2, false, false),
] {
let mut out = Vec::new();
let mut e = Encoder::new(&mut out, q);
e.set_sampling_factor(sampling);
e.set_progressive(progressive);
if icc {
let mut icc = vec![4; 70_000];
icc[16..20].copy_from_slice(b"CMYK");
e.add_icc_profile(&icc).unwrap();
}
let samples = if ty == ColorType::Luma { &px[..n] } else { &px[..] };
e.encode(samples, w, h, ty).unwrap();
let cut = out[..out.len() * 2 / 3].to_vec();
for file in [out, cut] {
let b = ImageBlob::new("image/jpeg", file.clone());
// The zune-jpeg reader panicked on some subsampled CMYK frames; those
// read as no inks now.
let inks = std::panic::catch_unwind(|| zune_inks(&file)).unwrap_or_else(|_| {
panicked += 1;
None
});
read += usize::from(inks.is_some());
assert_eq!(b.cmyk(), inks, "{w}x{h} {ty:?} q{q}");
let r = reference_size(&file);
assert_eq!(b.header_size(), r.as_ref().map(|r| (r.0, r.1)));
assert_eq!(jpeg_components(&file), r.as_ref().map(|r| r.2));
assert_eq!(jpeg_icc(&file), r.and_then(|r| r.3));
files += 1;
}
}
}
}
assert_eq!(files, 5 * 4 * 3 * 2);
assert!(read > 20 && panicked > 0, "{read} read as inks, {panicked} panicked");
}
}
+96
View File
@@ -0,0 +1,96 @@
//! Images decoded through craft-image-codecs as the image crate gave them (#778): the renderer,
//! File › Open and Place, SVG import, and embedded and linked images read their pixels with
//! [`decode_image`] and [`decode_within`], and size them from their header with [`decoded_layout`].
/// Decoded pixels, as stored and as the image crate gave them, and the ICC profile the file embeds.
pub type DecodedImage = (image::DynamicImage, Option<Vec<u8>>);
/// `bytes` decoded as `format` within `allowance` bytes, the pixels as stored (not turned
/// upright) and as the image crate gave them ([`dynamic`]), with the ICC profile the file embeds.
/// The renderer, File › Open and Place, SVG import, and embedded and linked images read images
/// with it.
pub fn decode_image(format: craft_image_codecs::Format, bytes: &[u8], allowance: u64) -> Result<DecodedImage, craft_image_codecs::CodecError> {
let opts = craft_image_codecs::DecodeOptions {
limits: craft_image_codecs::Limits { max_width: u32::MAX, max_height: u32::MAX, max_pixels: u64::MAX, max_alloc: allowance },
keep_orientation: true,
};
let mut img = craft_image_codecs::decode_as_with(format, bytes, &opts)?;
let icc = img.icc.take();
let img = dynamic(img).ok_or_else(|| craft_image_codecs::CodecError::InvalidImage("the decoded samples don't fit the image".into()))?;
Ok((img, icc))
}
/// `bytes` decoded within `max` bytes, counted as the file's samples and as RGBA (#1717), the
/// pixels as stored and as the image crate gave them, with the ICC profile the file embeds.
/// Image blobs read their pixels with it. `Ok(None)` when they would take more than `max` as
/// samples or as RGBA (the header alone decides; the pixels are not read). `Err` when the bytes
/// aren't an image the decoder reads, including a file whose header fits the allowance but whose
/// pixels can't be decoded (a cut-short file, or one the decoder refuses as a decompression bomb).
pub fn decode_within(bytes: &[u8], max: u64) -> Result<Option<DecodedImage>, craft_image_codecs::CodecError> {
let format = craft_image_codecs::detect(bytes).ok_or(craft_image_codecs::CodecError::UnknownFormat)?;
let (w, h, per_pixel) =
decoded_layout(bytes, format).ok_or_else(|| craft_image_codecs::CodecError::InvalidImage("the image's size can't be read".into()))?;
let pixels = u64::from(w) * u64::from(h);
if pixels.saturating_mul(per_pixel) > max || pixels.saturating_mul(4) > max {
return Ok(None);
}
decode_image(format, bytes, max).map(Some)
}
/// A decoded image as the image crate's: 8- and 16-bit gray, gray and alpha, RGB and RGBA as they
/// are, 32-bit float RGB and RGBA as they are, anything else as 8-bit RGBA.
fn dynamic(img: craft_image_codecs::Image) -> Option<image::DynamicImage> {
use craft_image_codecs::{ChannelLayout as L, SampleType as S};
use image::{DynamicImage as D, ImageBuffer as B};
let (w, h) = img.dimensions();
Some(match (img.layout(), img.sample_type()) {
(L::Gray, S::U8) => D::ImageLuma8(B::from_raw(w, h, img.into_data())?),
(L::GrayA, S::U8) => D::ImageLumaA8(B::from_raw(w, h, img.into_data())?),
(L::Rgb, S::U8) => D::ImageRgb8(B::from_raw(w, h, img.into_data())?),
(L::Rgba, S::U8) => D::ImageRgba8(B::from_raw(w, h, img.into_data())?),
(layout @ (L::Gray | L::GrayA | L::Rgb | L::Rgba), S::U16) => {
let v = img.to_u16_samples()?;
match layout {
L::Gray => D::ImageLuma16(B::from_raw(w, h, v)?),
L::GrayA => D::ImageLumaA16(B::from_raw(w, h, v)?),
L::Rgb => D::ImageRgb16(B::from_raw(w, h, v)?),
_ => D::ImageRgba16(B::from_raw(w, h, v)?),
}
}
_ => D::ImageRgba8(B::from_raw(w, h, img.to_rgba8())?),
})
}
/// The image's size and the bytes a pixel of it takes decoded ([`decode_as`]), read from its
/// header: palettes as RGB (RGBA with a transparent entry; GIF frames always RGBA), bitmaps as 8-bit
/// gray, 16-bit samples as two bytes. A PNG whose header alone is there is read from its `IHDR`;
/// a format whose header says only its size (TGA, ICO and the like) counts RGBA.
pub fn decoded_layout(bytes: &[u8], format: craft_image_codecs::Format) -> Option<(u32, u32, u64)> {
use craft_image_codecs::{Format as F, RasterColorType as T};
if let Some(i) = craft_image_codecs::inspect_raster(bytes).ok().flatten() {
let deep = i.bits_per_sample > 8 && i.color_type != T::Indexed;
let channels = match i.color_type {
_ if format == F::Gif => 4,
T::Indexed => 3 + u64::from(i.transparent_index.is_some()),
T::Bitmap => 1,
_ => u64::from(i.channels.max(1)),
};
return Some((i.width, i.height, channels * if deep { 2 } else { 1 }));
}
if format != F::Png {
return crate::header_size(bytes).map(|(w, h)| (w, h, 4));
}
if bytes.get(12..16)? != b"IHDR" {
return None;
}
let be = |at: usize| Some(u32::from_be_bytes(bytes.get(at..at + 4)?.try_into().ok()?));
let (depth, color) = (*bytes.get(24)?, *bytes.get(25)?);
let channels: u64 = match color {
0 => 1,
2 | 3 => 3,
4 => 2,
6 => 4,
_ => return None,
};
Some((be(16)?, be(20)?, channels * if depth == 16 { 2 } else { 1 }))
}
+12
View File
@@ -112,6 +112,18 @@ pub enum ArrowStyle {
None,
}
impl ArrowStyle {
/// The stroke arrowhead drawn at each end of the dimension line, or None for no head.
pub fn arrowhead(self) -> Option<crate::Arrowhead> {
match self {
Self::Filled => Some(crate::Arrowhead::Triangle),
Self::Open => Some(crate::Arrowhead::TriangleOpen),
Self::Tick => Some(crate::Arrowhead::Slash),
Self::None => None,
}
}
}
/// Where the label sits across the dimension line.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
+54 -1
View File
@@ -339,6 +339,7 @@ impl Document {
/// Index path from the top-level layer list to `id` (e.g. `[0, 3, 1]`): the first place in
/// tree order where `id` appears.
pub fn index_path(&self, id: NodeId) -> Option<Vec<usize>> {
crate::id_index::note_path_lookup();
// The cached path, while the node there still has the id ([`id_index`]).
let cached = self.index.get();
match cached.as_ref().and_then(|m| m.get(&id)) {
@@ -423,6 +424,44 @@ impl Document {
out
}
/// Every node whose id is in `ids`, in tree order (the order of [`Document::walk`]): unlike
/// [`Document::index_paths`], an id that appears more than once (a damaged file) gives every
/// node that has it. When the cache ([`id_index`]) holds each id once, at a path that still
/// checks out, the nodes are found along those paths; otherwise one walk of the tree finds
/// them. As for every cached lookup, a second node given an existing id after the cache was
/// built is not found while the first one's cached path checks out (see [`id_index`]).
pub fn nodes_in_order(&self, ids: impl IntoIterator<Item = NodeId>) -> Vec<&Node> {
let want: std::collections::HashSet<NodeId, std::hash::BuildHasherDefault<crate::id_index::IdHasher>> = ids.into_iter().collect();
// As in `index_paths`, one walk is quicker than checking the cached paths of a good share
// of the document.
if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) {
let mut paths = Vec::with_capacity(want.len());
let cached = want.iter().all(|id| match cache.get(id) {
Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => {
paths.push(p);
true
}
_ => false,
});
if cached {
// A node's path sorts after the paths of the nodes before it in tree order, its
// ancestors included.
paths.sort_unstable();
return paths.iter().filter_map(|p| self.node_at(p)).collect();
}
}
let mut out = Vec::new();
if !want.is_empty() {
crate::id_index::note_tree_walk();
self.walk(|n| {
if want.contains(&n.id) {
out.push(n);
}
});
}
out
}
/// The node at index path `path` (as [`Document::index_path`] gives it).
pub fn node_at(&self, path: &[usize]) -> Option<&Node> {
let (first, rest) = path.split_first()?;
@@ -752,6 +791,18 @@ impl Document {
/// [`Document::locked_artboards`] leaving out artboard `index`.
pub fn locked_artboards_except(&self, index: usize) -> LockedArtboards<'_> {
self.locks_except(index, false)
}
/// [`Document::locked_artboards`] starting with the symbol art boxes earlier hit tests kept
/// ([`Document::kept_symbol_boxes`]). Kept boxes made after it keep its measurements too
/// ([`crate::symbols::KeptBoxes::keeping`]).
pub(crate) fn locked_artboards_kept(&self) -> LockedArtboards<'_> {
self.locks_except(usize::MAX, true)
}
/// [`Document::locked_artboards_except`], with `kept` measuring with kept art boxes.
fn locks_except(&self, index: usize, kept: bool) -> LockedArtboards<'_> {
// Art flush with an edge from outside can overlap it by a rounding error, as in
// `art_bounds_on` (#1295).
let rects: Vec<Rect> =
@@ -770,7 +821,9 @@ impl Document {
if let Some(layer) = self.pattern_edit.as_ref().filter(|_| !rects.is_empty()).and_then(|e| self.layers.iter().find(|l| l.id == e.layer)) {
objects(layer, &mut pattern_art);
}
LockedArtboards { rects, symbols: self.symbol_boxes(), new_art: self.new_art.get(), pattern_art, held: Default::default() }
// Nothing is measured without a locked artboard.
let symbols = if kept && !rects.is_empty() { self.symbol_boxes_from_kept() } else { self.symbol_boxes() };
LockedArtboards { rects, symbols, new_art: self.new_art.get(), pattern_art, held: Default::default() }
}
/// Is `id` on a locked artboard ([`LockedArtboards::holds_id`])? A layer or sublayer is on none.
+440
View File
@@ -0,0 +1,440 @@
//! Flare objects: the settings a flare group was drawn with (the Flare tool, `shape.flare`). Its
//! children are ordinary paths for every renderer and exporter; the settings let it be drawn again.
use serde::{Deserialize, Serialize};
use serde_json::Value;
use vectorcraft_color::{BlendMode, Color, Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop, Paint};
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, Vec2, shapes};
use crate::Appearance;
use crate::node::{Node, NodeId, NodeKind};
/// The seed of the sizes a flare's rays and rings take when its settings give none.
pub const DEFAULT_SEED: u64 = 0x2545_f491_4f6c_dd1d;
/// One part of a flare: its name, outline, fill and opacity.
pub type Part = (&'static str, PathData, Paint, f32);
/// The number `key` of the settings `v`, or `default`.
fn number(v: &Value, key: &str, default: f64) -> f64 {
v.get(key).and_then(Value::as_f64).unwrap_or(default)
}
/// The parts of a flare with the settings `v` (`shape.flare`'s params, each one given): a bright
/// center, a halo ring, rays of varying length and rings along the path to the end point.
pub fn parts(v: &Value) -> Vec<Part> {
let c = Point::new(number(v, "cx", 0.0), number(v, "cy", 0.0));
let end = Point::new(number(v, "x2", c.x), number(v, "y2", c.y));
let pct = |k: &str| (number(v, k, 0.0) / 100.0).clamp(0.0, 10.0);
let r = (number(v, "diameter", 100.0) / 2.0).max(0.5);
let opacity = pct("opacity").min(1.0) as f32;
let brightness = pct("brightness").min(1.0) as f32;
let growth = pct("growth");
let fuzz = pct("fuzziness").min(1.0);
let rays = v.get("rays").and_then(Value::as_u64).unwrap_or(0).min(50) as usize;
let longest = pct("longest");
let ray_fuzz = pct("rayFuzziness").min(1.0);
let ray_turn = number(v, "rotation", 0.0).to_radians();
let rings = v.get("rings").and_then(Value::as_u64).unwrap_or(0).min(50) as usize;
let largest = pct("largest");
// Deterministic pseudo-random sizes (same parameters → same flare). `ringSeed` places the rings
// along the path from a sequence of its own; their count and sizes and the other parts stay.
// Xorshift64. Both streams start from a nonzero state.
let random = |mut state: u64| {
move || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
(state >> 11) as f64 / (1u64 << 53) as f64
}
};
let mut rnd = random(v.get("seed").and_then(Value::as_u64).unwrap_or(DEFAULT_SEED) | 1);
// Each `ringSeed` below 2^53 (what a JSON number holds exactly) gets a state of its own.
let mut ring_at = v.get("ringSeed").and_then(Value::as_u64).filter(|r| *r < 1 << 53).map(|r| {
// SplitMix64 initializes the ring-position stream.
let mut z = r.wrapping_add(0x9e37_79b9_7f4a_7c15);
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
random(z ^ (z >> 31))
});
let stop = |offset: f32, opacity: f32| GradientStop { opacity, ..GradientStop::new(offset, Color::WHITE) };
let radial = |centre: Point, radius: f64, stops: Vec<GradientStop>| {
let mut g = GradientPaint::new(Gradient::new(GradientKind::Radial, stops));
g.geom = Some(GradientGeom { start: centre, end: centre + Vec2::new(radius, 0.0), aspect: 1.0, focal: None });
Paint::Gradient(Box::new(g))
};
let circle = |centre: Point, radius: f64| shapes::ellipse(Rect::from_center_size(centre, (radius * 2.0, radius * 2.0)));
let mut parts: Vec<Part> = vec![];
// Halo: a soft ring just outside the centre.
let halo_r = r * (1.0 + growth) * 1.6;
let inner = (1.0 - fuzz as f32 * 0.6).clamp(0.05, 0.95);
parts.push(("Halo", circle(c, halo_r), radial(c, halo_r, vec![stop(0.0, 0.0), stop(inner * 0.75, 0.0), stop(inner, 0.5), stop(1.0, 0.0)]), 1.0));
// Rays: thin spikes of random length (Longest = % of the centre radius), fading outwards.
// `rotation` turns them clockwise about the center.
if rays > 0 {
let mut bp = BezPath::new();
let mut reach: f64 = 0.0;
for i in 0..rays {
let a = std::f64::consts::TAU * (i as f64 + rnd() * 0.6) / rays as f64 + ray_turn;
let len = r * longest * (1.0 - ray_fuzz * 0.75 * rnd()).max(0.1);
reach = reach.max(len);
let w = r * 0.035;
let dir = Vec2::new(a.cos(), a.sin());
let n = Vec2::new(-dir.y, dir.x) * w;
bp.move_to(c + n);
bp.line_to(c + dir * len);
bp.line_to(c - n);
bp.line_to(c - dir * (w * 4.0));
bp.close_path();
}
parts.push(("Rays", PathData::from_bezpath(&bp), radial(c, reach, vec![stop(0.0, 0.9), stop(0.25, 0.35), stop(1.0, 0.0)]), 1.0));
}
// Centre: bright core fading to transparent.
parts.push(("Center", circle(c, r), radial(c, r, vec![stop(0.0, 1.0), stop(0.25 + brightness * 0.5, 0.6), stop(1.0, 0.0)]), opacity));
// Rings along the path to the end point (Largest = % of the average ring size).
for _ in 0..rings {
let t = rnd();
let t = ring_at.as_mut().map_or(t, |next| next());
let at = c + (end - c) * t;
let rr = (r * largest * (0.25 + rnd() * 0.75)).max(0.5);
let solid = rnd() < 0.5;
let stops = if solid {
vec![stop(0.0, 0.25), stop(0.8, 0.2), stop(1.0, 0.0)]
} else {
vec![stop(0.0, 0.0), stop(0.7, 0.05), stop(0.92, 0.35), stop(1.0, 0.0)]
};
parts.push(("Ring", circle(at, rr), radial(at, rr, stops), 1.0));
}
parts
}
/// Part `part` of a flare as the object `id`, transformed by `xf` (the transform its flare has had
/// since it was drawn), with the pixel-aligned property when `aligned`.
pub fn part_node(id: NodeId, part: Part, xf: Affine, aligned: bool) -> Node {
let (name, pd, paint, op) = part;
let mut n = Node::path(id, pd, Appearance::basic(paint, Paint::None, 0.0));
n.name = Some(name.into());
n.blend = BlendMode::Screen;
n.opacity = op;
if aligned {
n.extras_mut().pixel_aligned = true;
}
if xf != Affine::IDENTITY {
n.transform(xf, false);
}
n
}
/// The ellipse of a radial gradient's placement `geom` as the symmetric matrix `[xx, xy, yy]` that
/// maps it to the unit circle's: the same for every end point and aspect that give that ellipse
/// (transforms applied one by one and all at once can put the end on different axes of it).
fn ellipse(geom: &GradientGeom) -> [f64; 3] {
let u = geom.end - geom.start;
let w = Vec2::new(-u.y, u.x) * geom.aspect;
[u.x * u.x + w.x * w.x, u.x * u.y + w.x * w.y, u.y * u.y + w.y * w.y]
}
/// The ellipse `[xx, xy, yy]` ([`ellipse`]) as its size, the length of its longer half-axis, and
/// its shape: the ratio of its shorter axis to its longer one, then the cosine and sine of twice
/// the longer axis's angle, each times one minus that ratio (0 for a circle). Each number is a
/// length or a ratio of lengths, never a squared length that a tiny flare or a narrow gradient
/// makes smaller than the tolerance.
fn ellipse_size_and_shape(geom: &GradientGeom) -> (f64, [f64; 3]) {
let [xx, xy, yy] = ellipse(geom);
let half_diff = (xx - yy) / 2.0;
let d = half_diff.hypot(xy);
let longer = (xx + yy) / 2.0 + d;
if longer.is_nan() || longer <= 0.0 {
return (0.0, [0.0; 3]);
}
// The product of the half-axes is the area factor of the map from the unit circle, `u` across
// `w` as [`ellipse`] builds them: a sum of squares times the aspect, without the cancellation
// of `xx * yy - xy * xy` for a narrow ellipse.
let u = geom.end - geom.start;
let w = Vec2::new(-u.y, u.x) * geom.aspect;
let ratio = ((u.x * w.y - u.y * w.x).abs() / longer).min(1.0);
let (cos, sin) = if d > 0.0 { (half_diff / d, xy / d) } else { (0.0, 0.0) };
(longer.sqrt(), [ratio, (1.0 - ratio) * cos, (1.0 - ratio) * sin])
}
/// `n` as JSON without what depends on how its transforms were applied: its id, the angle of its
/// bounding box, and which axis of a gradient's ellipse its end point is on (the ellipse stays: its
/// size in the placement, and its shape beside the placement, out of reach of a pixel-aligned
/// part's snap allowance, which is a length).
fn comparable(n: &Node) -> Value {
fn strip(v: &mut Value) {
match v {
Value::Object(m) => {
for key in ["id", "bbox_angle"] {
m.remove(key);
}
if let Some(geom) = m.get_mut("geom")
&& let Ok(g) = serde_json::from_value::<GradientGeom>(geom.clone())
&& let Value::Object(geom) = geom
{
let (size, shape) = ellipse_size_and_shape(&g);
geom.remove("end");
geom.remove("aspect");
geom.insert("ellipse".into(), serde_json::json!(size));
m.insert("ellipseShape".into(), serde_json::json!(shape));
}
m.values_mut().for_each(strip);
}
Value::Array(a) => a.iter_mut().for_each(strip),
_ => {}
}
}
let mut v = serde_json::to_value(n).unwrap_or(Value::Null);
strip(&mut v);
v
}
/// How close, relative to its size, a number in an outline or a gradient's placement must be to the
/// one its transforms give: a few thousandths of a point near the edge of the canvas.
const GEOMETRY_TOL: f64 = 1e-9;
/// Whether `a` and `b` are the same JSON, with each number within `tol` relative to its size; each
/// number in an outline (`path`) or a gradient's placement (`geom`) is within [`GEOMETRY_TOL`]
/// relative to its size (or `tol`, when smaller), and `snap` points as well.
fn close(a: &Value, b: &Value, tol: f64, snap: f64, geometry: bool) -> bool {
match (a, b) {
(Value::Number(x), Value::Number(y)) => match (x.as_f64(), y.as_f64()) {
(Some(x), Some(y)) => {
let (snap, tol) = if geometry { (snap, tol.min(GEOMETRY_TOL)) } else { (0.0, tol) };
(x - y).abs() <= snap + tol * (1.0 + x.abs().max(y.abs()))
}
_ => x == y,
},
(Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(x, y)| close(x, y, tol, snap, geometry)),
(Value::Object(x), Value::Object(y)) => {
x.len() == y.len()
&& x.iter().all(|(k, v)| {
// A gradient's shape is ratios: compared as closely as geometry, without the snap.
let snap = if k == "ellipseShape" { 0.0 } else { snap };
y.get(k).is_some_and(|w| close(v, w, tol, snap, geometry || k == "path" || k == "geom" || k == "ellipseShape"))
})
}
_ => a == b,
}
}
/// Whether `a` and `b` are the same JSON, with each number within `tol` relative to its size.
pub fn json_close(a: &Value, b: &Value, tol: f64) -> bool {
close(a, b, tol, 0.0, false)
}
/// How far a pixel-aligned object's points may be from where its transforms put them: snapping to
/// the pixel grid moves each by up to a pixel.
const PIXEL_SNAP: f64 = 1.0;
/// The settings of a flare group ([`crate::NodeExtras::flare`]).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FlareSpec {
/// `shape.flare`'s params the flare was drawn with, each one given: the center (`cx`, `cy`) and
/// the rings' end point (`x2`, `y2`) are in the coordinates it was drawn in.
pub params: serde_json::Value,
/// The transform its art has had since it was drawn (moves, scales, rotations, reflections and
/// shears).
#[serde(default = "identity", skip_serializing_if = "is_identity")]
pub transform: Affine,
}
fn identity() -> Affine {
Affine::IDENTITY
}
fn is_identity(a: &Affine) -> bool {
*a == Affine::IDENTITY
}
impl FlareSpec {
/// The settings of a flare drawn with `params`, not transformed since.
pub fn new(params: serde_json::Value) -> Self {
Self { params, transform: Affine::IDENTITY }
}
/// The point `key_x`, `key_y` of the params, where it is in the document now.
fn point(&self, key_x: &str, key_y: &str) -> Option<Point> {
let x = self.params.get(key_x)?.as_f64()?;
let y = self.params.get(key_y)?.as_f64()?;
Some(self.transform * Point::new(x, y)).filter(|p| p.x.is_finite() && p.y.is_finite())
}
/// The flare's center, where it is in the document now.
pub fn center(&self) -> Option<Point> {
self.point("cx", "cy")
}
/// The rings' end point, where it is in the document now.
pub fn end(&self) -> Option<Point> {
self.point("x2", "y2")
}
/// Its art transformed by `a`.
pub fn transform(&mut self, a: Affine) {
self.transform = a * self.transform;
}
/// Whether `group`'s parts are still the ones these settings draw, in place: none was edited,
/// distorted, removed or added, and the transform can be undone. The parts are compared where
/// they are in the document, at any scale.
pub fn draws(&self, group: &Node) -> bool {
let NodeKind::Group { children, .. } = &group.kind else { return false };
if !self.transform.is_finite() || self.transform.determinant() == 0.0 || !self.transform.inverse().is_finite() {
return false;
}
let expected = parts(&self.params);
expected.len() == children.len()
&& expected.into_iter().zip(children).all(|(part, child)| {
let aligned = child.extras().pixel_aligned;
let snap = if aligned { PIXEL_SNAP } else { 0.0 };
close(&comparable(&part_node(child.id, part, self.transform, aligned)), &comparable(child), 1e-6, snap, false)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
/// A flare's center and end point follow its art through a transform, and a save and reload
/// keeps its settings.
#[test]
fn a_flare_keeps_its_settings_through_a_transform_and_a_save() {
let mut g = Node::group(NodeId(1), vec![std::sync::Arc::new(Node::path(NodeId(2), PathData::default(), Default::default()))]);
g.extras_mut().flare = Some(Box::new(FlareSpec::new(json!({ "cx": 10.0, "cy": 20.0, "x2": 110.0, "y2": 20.0, "seed": 7 }))));
g.transform(Affine::translate((5.0, 0.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2), false);
let spec = g.extras().flare.as_deref().cloned().unwrap_or_else(|| panic!("no flare"));
let c = spec.center().unwrap_or_else(|| panic!("no center"));
let e = spec.end().unwrap_or_else(|| panic!("no end"));
assert!((c.x - -15.0).abs() < 1e-9 && (c.y - 10.0).abs() < 1e-9, "{c:?}");
assert!((e.x - -15.0).abs() < 1e-9 && (e.y - 110.0).abs() < 1e-9, "{e:?}");
let text = serde_json::to_string(&g).unwrap_or_else(|e| panic!("{e}"));
let back: Node = serde_json::from_str(&text).unwrap_or_else(|e| panic!("{e}"));
assert_eq!(back.extras().flare.as_deref(), Some(&spec));
// A flare that was not transformed writes no transform.
let plain = FlareSpec::new(json!({ "cx": 1.0 }));
assert_eq!(serde_json::to_value(&plain).unwrap_or_default(), json!({ "params": { "cx": 1.0 } }));
}
/// A flare group draws its settings until a part's gradient, opacity or outline is edited; a
/// pixel-aligned part may sit up to a pixel from where its transforms put it, but only in its
/// outline and its gradient's placement.
#[test]
fn a_flare_with_an_edited_part_no_longer_draws_its_settings() {
let v = json!({ "cx": 50.0, "cy": 50.0, "x2": 250.0, "y2": 50.0, "rays": 5, "rings": 2, "seed": 9, "diameter": 40.0,
"opacity": 50.0, "brightness": 30.0, "growth": 20.0, "fuzziness": 50.0, "longest": 300.0, "rayFuzziness": 100.0,
"rotation": 0.0, "largest": 50.0 });
let flare = |aligned: bool| {
let xf = Affine::rotate(0.3) * Affine::scale_non_uniform(1.5, 0.75);
let children = parts(&v).into_iter().enumerate().map(|(i, p)| std::sync::Arc::new(part_node(NodeId(10 + i as u64), p, xf, aligned)));
let mut g = Node::group(NodeId(1), children.collect());
g.extras_mut().flare = Some(Box::new(FlareSpec { params: v.clone(), transform: xf }));
g
};
let spec = |g: &Node| g.extras().flare.as_deref().cloned().unwrap_or_else(|| panic!("no flare"));
let edit = |g: &mut Node, f: &dyn Fn(&mut Node)| {
let NodeKind::Group { children, .. } = &mut g.kind else { panic!("not a group") };
// The center, drawn at half opacity.
f(std::sync::Arc::make_mut(&mut children[2]));
};
for aligned in [false, true] {
let g = flare(aligned);
assert!(spec(&g).draws(&g), "aligned {aligned}");
let mut moved = g.clone();
edit(&mut moved, &|n| n.transform(Affine::translate((0.4, 0.0)), false));
assert_eq!(spec(&moved).draws(&moved), aligned, "a fraction of a pixel, aligned {aligned}");
let mut faded = g.clone();
edit(&mut faded, &|n| n.opacity *= 0.8);
assert!(!spec(&faded).draws(&faded), "opacity, aligned {aligned}");
let mut shifted = g.clone();
edit(&mut shifted, &|n| {
if let Some(crate::AppearanceItem::Fill(fill)) = n.appearance.items.first_mut()
&& let Paint::Gradient(gp) = &mut fill.paint
&& let Some(geom) = &mut gp.geom
{
geom.start.x += 20.0;
}
});
assert!(!spec(&shifted).draws(&shifted), "gradient placement, aligned {aligned}");
let mut squashed = g.clone();
edit(&mut squashed, &|n| {
if let Some(crate::AppearanceItem::Fill(fill)) = n.appearance.items.first_mut()
&& let Paint::Gradient(gp) = &mut fill.paint
&& let Some(geom) = &mut gp.geom
{
geom.aspect *= 0.5;
}
});
assert!(!spec(&squashed).draws(&squashed), "gradient shape, aligned {aligned}");
}
}
/// An ellipse's size and shape are the same whichever axis its end point is on, and a narrow
/// gradient made narrower, or turned, changes its shape by more than [`GEOMETRY_TOL`].
#[test]
fn an_ellipse_shape_tells_narrow_gradients_apart() {
let geom = |end: (f64, f64), aspect: f64| GradientGeom { start: Point::new(1.0, 2.0), end: Point::new(end.0, end.1), aspect, focal: None };
let of = ellipse_size_and_shape;
let (size, shape) = of(&geom((11.0, 2.0), 0.5));
// The same ellipse with its end point on the other axis.
let (size2, shape2) = of(&geom((1.0, 7.0), 2.0));
assert!((size - size2).abs() < 1e-12 && shape.iter().zip(shape2).all(|(a, b)| (a - b).abs() < 1e-12), "{shape:?} {shape2:?}");
// A very narrow ellipse, given both ways, keeps its shape to within the tolerance.
let (thin, thin2) = (of(&geom((11.0, 2.0), 1e-8)).1, of(&geom((1.0, 2.0 + 1e-7), 1e8)).1);
assert!(thin.iter().zip(thin2).all(|(a, b)| (a - b).abs() < GEOMETRY_TOL), "{thin:?} {thin2:?}");
let narrow = of(&geom((11.0, 2.0), 1e-4)).1;
for other in [of(&geom((11.0, 2.0), 5e-5)).1, of(&geom((1.0, 12.0), 1e-4)).1] {
assert!(narrow.iter().zip(other).any(|(a, b)| (a - b).abs() > 1e3 * GEOMETRY_TOL), "{narrow:?} {other:?}");
}
assert_eq!(of(&geom((1.0, 2.0), 1.0)), (0.0, [0.0; 3]));
}
/// A flare scaled far down, in one direction or in all, anywhere on the canvas, still draws its
/// settings, and a part's gradient whose shape was edited is still told apart; a flattened flare
/// does not draw its settings.
#[test]
fn a_flare_scaled_far_down_still_draws_its_settings() {
let v = json!({ "cx": 50.0, "cy": 50.0, "x2": 250.0, "y2": 50.0, "rays": 5, "rings": 2, "seed": 9, "diameter": 40.0 });
let flare_aligned = |xf: Affine, aligned: bool| {
let children = parts(&v).into_iter().enumerate().map(|(i, p)| std::sync::Arc::new(part_node(NodeId(10 + i as u64), p, xf, aligned)));
let mut g = Node::group(NodeId(1), children.collect());
g.extras_mut().flare = Some(Box::new(FlareSpec { params: v.clone(), transform: xf }));
g
};
let flare = |xf: Affine| flare_aligned(xf, false);
// The center's gradient placement, to edit.
let center_geom = |g: &mut Node, f: &dyn Fn(&mut GradientGeom)| {
let NodeKind::Group { children, .. } = &mut g.kind else { panic!("not a group") };
if let Some(crate::AppearanceItem::Fill(fill)) = std::sync::Arc::make_mut(&mut children[2]).appearance.items.first_mut()
&& let Paint::Gradient(gp) = &mut fill.paint
&& let Some(geom) = &mut gp.geom
{
f(geom);
} else {
panic!("the center has no gradient fill");
}
};
let draws = |g: &Node| g.extras().flare.as_deref().is_some_and(|spec| spec.draws(g));
assert!(draws(&flare(Affine::scale(1e-7))), "scaled to 0.00001%");
assert!(draws(&flare(Affine::rotate(0.3) * Affine::scale_non_uniform(1.0, 1e-10))), "shrunk far on one axis");
assert!(draws(&flare(Affine::translate((crate::MAX_COORD - 1000.0, 0.0)) * Affine::scale(0.5))), "near the edge of the canvas");
assert!(draws(&flare(Affine::translate((1000.0, 0.0)) * Affine::scale(1e-5))), "scaled to 0.001% and moved away");
assert!(!draws(&flare(Affine::scale_non_uniform(1.0, 0.0))), "flattened");
// At that size a part whose gradient's shape was edited no longer draws the settings.
let mut squashed = flare(Affine::scale(1e-6));
assert!(draws(&squashed), "scaled to 0.0001%");
center_geom(&mut squashed, &|geom| geom.aspect *= 0.5);
assert!(!draws(&squashed), "gradient shape at 0.0001%");
// A pixel-aligned part may sit up to a pixel off, but its gradient's shape may not change,
// even when the ellipse keeps its size.
let mut reshaped = flare_aligned(Affine::IDENTITY, true);
assert!(draws(&reshaped), "aligned");
center_geom(&mut reshaped, &|geom| {
let a = geom.aspect;
geom.aspect = a * 0.5;
geom.end = geom.start + (geom.end - geom.start) * ((1.0 + a * a) / (1.0 + a * a / 4.0)).sqrt();
});
assert!(!draws(&reshaped), "gradient shape of the same size, aligned");
}
}
+32 -1
View File
@@ -140,7 +140,7 @@ impl crate::Document {
/// the text in graphs): the value axis numbers, the category labels (category axis, radar spokes, pie names) and the
/// legend labels (beside or across the top, or in pie wedges). `None` draws the default 9 pt black. The `*_para`
/// fields are the paragraph attributes each kind keeps the same way (`None`: the defaults); the graph still sets each
/// label's alignment.
/// label's alignment. [`Self::axis_rows`] and [`Self::ring_rows`] are the rows the graph's lines keep the same way.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct LabelStyles {
@@ -180,6 +180,14 @@ pub struct LabelStyles {
/// The object fill and stroke rows the legend labels keep, as [`Self::values_rows`].
#[serde(skip_serializing_if = "Option::is_none")]
pub legend_rows: Option<LabelRows>,
/// The object rows the axis lines and tick marks keep once set with the paint, stroke or Appearance controls
/// ([`LabelRows`]). They replace the default 0.5 pt black stroke; kept rows without paint draw none. `None`: the
/// default stroke.
#[serde(skip_serializing_if = "Option::is_none")]
pub axis_rows: Option<LabelRows>,
/// The object rows the rings of a radar graph keep, as [`Self::axis_rows`]. `None`: the default 0.25 pt gray stroke.
#[serde(skip_serializing_if = "Option::is_none")]
pub ring_rows: Option<LabelRows>,
}
impl LabelStyles {
@@ -483,6 +491,10 @@ pub struct GraphSpec {
pub first_column_in_front: bool,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub filled_lines: bool,
/// Graph Type › Line Width: how wide Draw Filled Lines draws a line, in points. `None` draws
/// [`DEFAULT_FILLED_LINE_WIDTH`]; see [`Self::filled_line_width`].
#[serde(skip_serializing_if = "Option::is_none")]
pub line_width: Option<f64>,
/// Graph Type › Add Drop Shadow (behind columns, bars, lines and pie wedges) and Add Legend Across Top (the
/// legend in rows above the plot instead of a column on its right).
#[serde(skip_serializing_if = "std::ops::Not::not")]
@@ -557,6 +569,24 @@ fn is_zero(n: &usize) -> bool {
*n == 0
}
/// Graph Type › Line Width: the width Draw Filled Lines draws a line at when the graph sets none, and the least and
/// greatest widths a graph takes, in points.
pub const DEFAULT_FILLED_LINE_WIDTH: f64 = 3.0;
pub const MIN_FILLED_LINE_WIDTH: f64 = 0.01;
pub const MAX_FILLED_LINE_WIDTH: f64 = 1000.0;
/// The weight of the black outline Draw Filled Lines draws around each band, in points.
pub const FILLED_LINE_OUTLINE_WIDTH: f64 = 0.25;
impl GraphSpec {
/// How wide Draw Filled Lines draws a line, in points: [`Self::line_width`], else [`DEFAULT_FILLED_LINE_WIDTH`]. A
/// width a file gives outside [`MIN_FILLED_LINE_WIDTH`] to [`MAX_FILLED_LINE_WIDTH`], or not finite, draws the
/// default.
pub fn filled_line_width(&self) -> f64 {
self.line_width.filter(|w| (MIN_FILLED_LINE_WIDTH..=MAX_FILLED_LINE_WIDTH).contains(w)).unwrap_or(DEFAULT_FILLED_LINE_WIDTH)
}
}
/// Edge-to-Edge Lines for a graph saved before the option existed: on, as it was drawn then.
fn edge_to_edge_before_the_option() -> bool {
true
@@ -696,6 +726,7 @@ impl Default for GraphSpec {
first_row_in_front: false,
first_column_in_front: false,
filled_lines: false,
line_width: None,
drop_shadow: false,
legend_across_top: false,
pie_legend_in_wedges: false,
+759 -160
View File
File diff suppressed because it is too large. Load diff
+761 -5
View File
@@ -164,8 +164,8 @@ fn clicks_in_a_clip_group_evaluate_its_clipping_paths_region_once_until_it_chang
// So with a marquee across the art's left edge: in the view, only in Outline view. The
// clipping path's own left edge lies there too, and counts in both.
let edge = Rect::new(-5.0, 40.0, 5.0, 60.0);
assert_eq!(marquee_in_view(&d, edge, None, true, false), [mask_id]);
assert_eq!(marquee_in_view(&d, edge, None, true, true), [mask_id, art_id]);
assert_eq!(marquee_in_view(&d, edge, None, true, false, false), [mask_id]);
assert_eq!(marquee_in_view(&d, edge, None, true, true, false), [mask_id, art_id]);
// `marquee_in` measures by the plain shapes, as its callers clip by them.
assert!(marquee_in(d.node(g).unwrap(), edge).is_some());
// Hidden, the effect no longer moves the region.
@@ -307,6 +307,423 @@ fn hovers_past_more_clip_groups_than_the_boxes_kept_evaluate_few_again() {
assert!(again < groups / 8, "{again} of {groups} regions evaluated again");
}
/// A stand-in for the engine's [`DrawnArt`]: an object with a visible effect named `test.shift`
/// draws 100 pt to the right of its own place, and one with a visible effect named `test.copy`
/// draws at its own place and 100 pt to the right. The effects are applied innermost first, and
/// the art keeps the ids of the objects it is drawn from. An instance of a symbol whose art has a
/// visible effect draws as a 50 pt square from (100, 0), white with a black 1 pt stroke. A clip
/// group with a visible effect named `test.mask_only` draws as a group of its clipping path alone,
/// as the engine's art for a clip group whose clipping path's strokes have geometry effects is.
/// Without any of these, no geometry effect changes what an object draws.
fn shifted_art(s: &SymbolBoxes<'_>, n: &Node) -> Option<Node> {
if n.clips()
&& n.appearance.effects.iter().any(|e| e.visible && e.id == "test.mask_only")
&& let Some(mask) = n.children().and_then(|c| c.first())
{
return Some(Node::group(n.id, vec![mask.clone()]));
}
fn draw(s: &SymbolBoxes<'_>, n: &Node, found: &mut bool) -> Node {
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind
&& s.has_effects(symbol)
{
*found = true;
return Node::path(n.id, shapes::rectangle(Rect::new(100.0, 0.0, 150.0, 50.0)), Appearance::default_art());
}
let mut m = n.clone();
if let Some(children) = m.children_mut() {
for c in children.iter_mut() {
*c = Arc::new(draw(s, c, found));
}
}
let has = |id: &str| n.appearance.effects.iter().any(|e| e.visible && e.id == id);
let (shift, copy) = (has("test.shift"), has("test.copy"));
m.appearance.effects.retain(|e| e.id != "test.shift" && e.id != "test.copy");
*found |= shift || copy;
let shifted = |m: &Node| moved(m, vectorcraft_geom::Affine::translate((100.0, 0.0)));
if shift {
shifted(&m)
} else if copy {
Node::group(n.id, vec![Arc::new(shifted(&m)), Arc::new(m)])
} else {
m
}
}
let mut found = false;
let art = draw(s, n, &mut found);
found.then_some(art)
}
/// A visible effect named `id`.
fn effect(id: &str) -> crate::Effect {
crate::Effect { id: id.into(), params: serde_json::json!({}), visible: true }
}
/// A 50 pt square at `x`, `y`, white with a black 1 pt stroke.
fn square(d: &mut Document, x: f64, y: f64) -> Node {
Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 50.0, y + 50.0)), Appearance::default_art())
}
/// The leaf and the kind a click at (`x`, `y`) hits.
fn hit_at(d: &Document, x: f64, y: f64, opt: HitOptions) -> Option<(NodeId, HitKind)> {
hit_test(d, Point::new(x, y), opt).map(|h| (h.leaf, h.kind))
}
/// A path that a geometry effect moves is clicked where it is drawn, and not at its own place,
/// which it no longer paints; with Object Selection by Path Only on its drawn outline, not its
/// fill. Outline view draws no effects: there its own outline is clicked. Hidden, the effect no
/// longer moves what clicks hit.
#[test]
fn a_click_hits_a_paths_shifted_art_not_its_source() {
set_drawn_art(shifted_art);
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let mut p = square(&mut d, 0.0, 0.0);
p.appearance.effects.push(effect("test.shift"));
let a = p.id;
d.insert(Some(l), 0, p).unwrap();
let opt = HitOptions::default();
assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a, HitKind::Fill)), "where it is drawn");
assert_eq!(hit_at(&d, 25.0, 25.0, opt), None, "its own place");
assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [a]);
assert!(objects_at(&d, Point::new(25.0, 25.0), opt, None).is_empty());
let path_only = HitOptions { path_only: true, ..opt };
assert_eq!(hit_at(&d, 125.0, 25.0, path_only), None, "path only: the drawn fill");
assert_eq!(hit_at(&d, 100.0, 25.0, path_only), Some((a, HitKind::Stroke)), "path only: the drawn outline");
let outline = HitOptions { outline: true, ..opt };
assert_eq!(hit_at(&d, 0.5, 25.0, outline), Some((a, HitKind::Outline)), "outline: its own outline");
assert_eq!(hit_at(&d, 100.5, 25.0, outline), None, "outline: no drawn art");
d.node_mut(a).unwrap().appearance.effects[0].visible = false;
assert_eq!(hit_at(&d, 25.0, 25.0, opt), Some((a, HitKind::Fill)), "hidden effect: its own place");
assert_eq!(hit_at(&d, 125.0, 25.0, opt), None, "hidden effect: nothing drawn there");
}
/// A geometry effect that copies a path is clicked on the copy and on the path, the topmost of the
/// stack first. The pointer moving over it evaluates its art once until it changes, and a path
/// without effects is not evaluated.
#[test]
fn a_click_hits_a_paths_copy_and_evaluates_its_art_once_until_it_changes() {
set_drawn_art(shifted_art);
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let below = square(&mut d, 100.0, 0.0);
let mut p = square(&mut d, 0.0, 0.0);
p.appearance.effects.push(effect("test.copy"));
let (a, b) = (p.id, below.id);
d.insert(Some(l), 0, below).unwrap();
d.insert(Some(l), 1, p).unwrap();
let evaluated = || DRAWN_EVALUATED.with(std::cell::Cell::get);
let before = evaluated();
let opt = HitOptions::default();
for _ in 0..3 {
assert_eq!(hit_at(&d, 25.0, 25.0, opt).map(|h| h.0), Some(a), "the path");
assert_eq!(hit_at(&d, 125.0, 25.0, opt).map(|h| h.0), Some(a), "its copy, over the square below");
}
assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [a, b]);
assert_eq!(evaluated(), before + 1, "evaluated once");
if let Some(NodeKind::Path { path, .. }) = d.node_mut(a).map(|n| &mut n.kind) {
*path = shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 50.0));
}
assert_eq!(hit_at(&d, 140.0, 25.0, opt).map(|h| h.0), Some(b), "narrowed, the copy leaves the square below");
assert_eq!(evaluated(), before + 2, "evaluated again after it changed");
// The square below has no effects: it is never evaluated.
assert_eq!(hit_at(&d, 145.0, 45.0, opt).map(|h| h.0), Some(b));
assert_eq!(evaluated(), before + 2);
}
/// A group without effects or fills and strokes of its own is not evaluated as a whole: a click
/// on the art of a moved member in it evaluates that member only, and finds the group by it.
#[test]
fn a_click_in_a_plain_group_evaluates_only_its_member_with_effects() {
set_drawn_art(shifted_art);
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let mut moved = square(&mut d, 0.0, 0.0);
moved.appearance.effects.push(effect("test.shift"));
let still = square(&mut d, 0.0, 100.0);
let (a, g) = (moved.id, d.alloc_id());
d.insert(Some(l), 0, Node::group(g, vec![Arc::new(moved), Arc::new(still)])).unwrap();
let evaluated = || DRAWN_EVALUATED.with(std::cell::Cell::get);
let before = evaluated();
let opt = HitOptions::default();
for _ in 0..3 {
assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a, HitKind::Fill)));
assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [g]);
}
assert_eq!(evaluated(), before + 1, "only the member with effects, once");
}
/// A compound path that a geometry effect moves keeps its hole where it is drawn, for clicks and
/// marquees.
#[test]
fn a_compound_paths_shifted_art_keeps_its_hole() {
set_drawn_art(shifted_art);
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let outer = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 60.0)), Appearance::default());
let hole = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(20.0, 20.0, 40.0, 40.0)), Appearance::default());
let c = d.alloc_id();
let mut compound = Node::new(c, NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(hole)], rule: FillRule::EvenOdd });
compound.appearance = Appearance::default_art().into();
compound.appearance.effects.push(effect("test.shift"));
d.insert(Some(l), 0, compound).unwrap();
let opt = HitOptions::default();
assert_eq!(hit_at(&d, 105.0, 5.0, opt), Some((c, HitKind::Fill)), "its drawn fill");
assert_eq!(hit_at(&d, 130.0, 30.0, opt), None, "its drawn hole");
assert_eq!(hit_at(&d, 5.0, 5.0, opt), None, "its own place");
assert_eq!(marquee(&d, Rect::new(155.0, 25.0, 165.0, 35.0), None, false), [c], "a marquee across the drawn edge");
assert!(marquee(&d, Rect::new(-5.0, 25.0, 5.0, 35.0), None, false).is_empty(), "a marquee across its own edge");
}
/// A marquee touches a path that a geometry effect moves where it is drawn, and not at its own
/// place; in Outline view, at its own place.
#[test]
fn a_marquee_touches_a_paths_shifted_art_not_its_source() {
set_drawn_art(shifted_art);
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let mut p = square(&mut d, 0.0, 0.0);
p.appearance.effects.push(effect("test.shift"));
let a = p.id;
d.insert(Some(l), 0, p).unwrap();
let (drawn, own) = (Rect::new(140.0, 40.0, 160.0, 60.0), Rect::new(40.0, 40.0, 60.0, 60.0));
for leaves in [false, true] {
assert_eq!(marquee(&d, drawn, None, leaves), [a], "where it is drawn");
assert!(marquee(&d, own, None, leaves).is_empty(), "its own place");
assert!(marquee_in_view(&d, drawn, None, leaves, true, false).is_empty(), "outline: no drawn art");
assert_eq!(marquee_in_view(&d, own, None, leaves, true, false), [a], "outline: its own place");
}
}
/// A group whose own geometry effect moves its members is clicked where each member is drawn: the
/// member, inside the group, is hit, and a locked member lets the click through to what is below
/// and is listed for unlocking there. A marquee there touches the group, or the member for Direct
/// Selection.
#[test]
fn a_groups_own_effect_moves_where_its_members_are_hit() {
set_drawn_art(shifted_art);
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let below = square(&mut d, 150.0, 0.0);
let (a, b) = (square(&mut d, 0.0, 0.0), square(&mut d, 50.0, 0.0));
let (below_id, a_id, b_id, g) = (below.id, a.id, b.id, d.alloc_id());
let mut group = Node::group(g, vec![Arc::new(a), Arc::new(b)]);
group.appearance.effects.push(effect("test.shift"));
d.insert(Some(l), 0, below).unwrap();
d.insert(Some(l), 1, group).unwrap();
let opt = HitOptions::default();
let h = hit_test(&d, Point::new(125.0, 25.0), opt).unwrap();
assert_eq!((h.leaf, h.top_object(None)), (a_id, g), "the first member, drawn there");
assert_eq!(h.ancestry, [l, g, a_id]);
assert_eq!(hit_at(&d, 175.0, 25.0, opt).map(|h| h.0), Some(b_id), "the second member, over the square below");
assert_eq!(hit_at(&d, 25.0, 25.0, opt), None, "the first member's own place");
assert_eq!(objects_at(&d, Point::new(175.0, 25.0), opt, None), [g, below_id]);
let drawn = Rect::new(195.0, 20.0, 205.0, 30.0);
assert_eq!(marquee(&d, drawn, None, false), [below_id, g]);
assert_eq!(marquee(&d, drawn, None, true), [below_id, b_id]);
assert!(marquee(&d, Rect::new(-5.0, 20.0, 5.0, 30.0), None, true).is_empty(), "the members' own place");
d.node_mut(b_id).unwrap().locked = true;
assert_eq!(hit_at(&d, 175.0, 25.0, opt).map(|h| h.0), Some(below_id), "a locked member lets the click through");
assert_eq!(marquee(&d, drawn, None, true), [below_id], "nor does a marquee collect it");
assert_eq!(locked_objects_at(&d, Point::new(175.0, 25.0), opt), [b_id], "the Unlock submenu lists it where it is drawn");
assert!(locked_objects_at(&d, Point::new(75.0, 25.0), opt).is_empty(), "and not at its own place");
// Outline view draws no effects: the members are clicked at their own places.
let outline = HitOptions { outline: true, ..opt };
assert_eq!(hit_at(&d, 0.5, 25.0, outline).map(|h| h.0), Some(a_id));
}
/// A layer whose own geometry effect moves its art is clicked and marqueed where the art is
/// drawn. With the layer's Preview off, its art is clicked at its own place, in outline.
#[test]
fn a_layers_own_effect_moves_where_its_art_is_hit() {
set_drawn_art(shifted_art);
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let a = square(&mut d, 0.0, 0.0);
let a_id = a.id;
d.insert(Some(l), 0, a).unwrap();
d.node_mut(l).unwrap().appearance.effects.push(effect("test.shift"));
let opt = HitOptions::default();
assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a_id, HitKind::Fill)), "where it is drawn");
assert_eq!(hit_at(&d, 25.0, 25.0, opt), None, "its own place");
assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [a_id]);
assert!(objects_at(&d, Point::new(25.0, 25.0), opt, None).is_empty());
let (drawn, own) = (Rect::new(145.0, 20.0, 155.0, 30.0), Rect::new(-5.0, 20.0, 5.0, 30.0));
for leaves in [false, true] {
assert_eq!(marquee(&d, drawn, None, leaves), [a_id], "a marquee where it is drawn");
assert!(marquee(&d, own, None, leaves).is_empty(), "a marquee at its own place");
}
if let Some(NodeKind::Layer { preview, .. }) = d.node_mut(l).map(|n| &mut n.kind) {
*preview = false;
}
assert_eq!(hit_at(&d, 0.5, 25.0, opt), Some((a_id, HitKind::Outline)), "preview off: its own outline");
assert_eq!(hit_at(&d, 125.0, 25.0, opt), None, "preview off: no drawn art");
assert_eq!(marquee(&d, own, None, false), [a_id], "preview off: a marquee at its own place");
}
/// In a layer whose own geometry effect moves its art, a sublayer with Preview off is clicked in
/// outline: on the outline of its art where the art is drawn, not inside its fill.
#[test]
fn a_preview_off_sublayer_of_an_effected_layer_is_clicked_in_outline() {
set_drawn_art(shifted_art);
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let sub = d.alloc_id();
d.insert(Some(l), 0, Node::layer(sub, "Sub", crate::LayerColor::Preset(2))).unwrap();
let a = square(&mut d, 0.0, 0.0);
let a_id = a.id;
d.insert(Some(sub), 0, a).unwrap();
d.node_mut(l).unwrap().appearance.effects.push(effect("test.shift"));
let opt = HitOptions::default();
assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((a_id, HitKind::Fill)), "preview on: inside its fill");
if let Some(NodeKind::Layer { preview, .. }) = d.node_mut(sub).map(|n| &mut n.kind) {
*preview = false;
}
assert_eq!(hit_at(&d, 125.0, 25.0, opt), None, "preview off: inside its fill");
assert_eq!(hit_at(&d, 100.5, 25.0, opt), Some((a_id, HitKind::Outline)), "preview off: on its outline");
}
/// A group with fills and strokes of its own around an instance of a symbol whose art has an
/// effect is clicked where its art is drawn, though no object in the group has an effect.
#[test]
fn a_painted_group_around_an_effected_symbols_instance_is_hit_where_its_art_is_drawn() {
set_drawn_art(shifted_art);
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let mut art = square(&mut d, 0.0, 0.0);
art.appearance.effects.push(effect("test.raster"));
d.symbols.push(crate::Symbol { dynamic: false, name: "Effected".into(), art: Arc::new(art) });
let (g, inst) = (d.alloc_id(), d.alloc_id());
let instance = Node::new(inst, NodeKind::SymbolInstance { symbol: "Effected".into(), xf: vectorcraft_geom::Affine::IDENTITY });
let mut group = Node::group(g, vec![Arc::new(instance)]);
group.appearance = Appearance::default_art().into();
d.insert(Some(l), 0, group).unwrap();
let opt = HitOptions::default();
assert_eq!(hit_at(&d, 125.0, 25.0, opt), Some((inst, HitKind::Fill)), "where its art is drawn");
assert_eq!(objects_at(&d, Point::new(125.0, 25.0), opt, None), [g]);
}
/// In a layer with fills and strokes of its own whose art is evaluated for a member's geometry
/// effect, an Intertwine group's members are still clicked in the order they are drawn at the
/// click: where the lower member is woven over the upper one, the click takes the lower member.
#[test]
fn an_intertwine_group_in_a_layers_drawn_art_is_hit_in_its_woven_order() {
set_drawn_art(shifted_art);
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
d.node_mut(l).unwrap().appearance = Appearance::default_art().into();
let mut a = square(&mut d, 0.0, 100.0);
a.extras_mut().intertwine = Some(Box::new(shapes::rectangle(Rect::new(25.0, 100.0, 50.0, 150.0))));
let b = square(&mut d, 25.0, 100.0);
let (a_id, b_id, g) = (a.id, b.id, d.alloc_id());
d.insert(Some(l), 0, Node::new(g, NodeKind::Intertwine { children: vec![Arc::new(a), Arc::new(b)] })).unwrap();
let mut moved = square(&mut d, 200.0, 0.0);
moved.appearance.effects.push(effect("test.shift"));
d.insert(Some(l), 1, moved).unwrap();
let opt = HitOptions::default();
assert_eq!(hit_at(&d, 40.0, 125.0, opt), Some((a_id, HitKind::Fill)), "where the lower member is woven over");
assert_eq!(hit_at(&d, 60.0, 125.0, opt), Some((b_id, HitKind::Fill)), "where the upper member is drawn over");
}
/// The clipping path of a clip group and of a clipping layer is still marqueed by its own geometry
/// when a geometry effect moves what it draws.
#[test]
fn a_clipping_path_keeps_its_own_geometry_under_a_geometry_effect() {
set_drawn_art(shifted_art);
let edge = Rect::new(-5.0, 40.0, 5.0, 60.0);
// A clip group.
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let (mut mask, art) = half_clipped(&mut d);
mask.appearance.effects.push(effect("test.shift"));
let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id);
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
clip.set_clips(true);
d.insert(Some(l), 0, clip).unwrap();
assert_eq!(marquee(&d, edge, None, true), [mask_id, art_id], "clip group");
// A clipping layer.
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let (mut mask, art) = half_clipped(&mut d);
mask.appearance.effects.push(effect("test.shift"));
let (mask_id, art_id) = (mask.id, art.id);
let layer = d.node_mut(l).unwrap();
if let NodeKind::Layer { children, clip, .. } = &mut layer.kind {
(*children, *clip) = (vec![Arc::new(mask), Arc::new(art)], true);
}
assert_eq!(marquee(&d, edge, None, true), [mask_id, art_id], "clipping layer");
}
/// The selection tools take the clipping path of a clip group whose own geometry effect moves it
/// on its outline where it is drawn, before the art it clips, and not at its own place.
#[test]
fn a_clip_groups_own_effect_moves_where_its_mask_outline_is_hit() {
set_drawn_art(shifted_art);
let mut d = Document::new(400.0, 200.0);
let l = d.layers[0].id;
let (mask, art) = half_clipped(&mut d);
let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id);
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
clip.set_clips(true);
clip.appearance.effects.push(effect("test.shift"));
d.insert(Some(l), 0, clip).unwrap();
let tools = HitOptions { clip_outlines: true, ..HitOptions::default() };
assert_eq!(hit_at(&d, 199.5, 50.0, tools), Some((mask_id, HitKind::Outline)), "the drawn edge, over the art");
assert_eq!(hit_at(&d, 150.0, 50.0, tools).map(|h| h.0), Some(art_id), "the drawn art inside the mask");
assert_eq!(hit_at(&d, 0.5, 50.0, tools), None, "the mask's own edge");
// The same clip group in a group whose own effect moves it.
let mut d = Document::new(400.0, 200.0);
let l = d.layers[0].id;
let (mask, art) = half_clipped(&mut d);
let (g, mask_id, art_id) = (d.alloc_id(), mask.id, art.id);
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
clip.set_clips(true);
let mut outer = Node::group(d.alloc_id(), vec![Arc::new(clip)]);
outer.appearance.effects.push(effect("test.shift"));
d.insert(Some(l), 0, outer).unwrap();
assert_eq!(hit_at(&d, 199.5, 50.0, tools), Some((mask_id, HitKind::Outline)), "in a moved group: the drawn edge, over the art");
assert_eq!(hit_at(&d, 150.0, 50.0, tools).map(|h| h.0), Some(art_id), "in a moved group: the drawn art");
}
/// In isolation mode in a clip group whose own geometry effect moves it, the selection tools take
/// the art outside the clipping mask by its own geometry, for a marquee as for a click.
#[test]
fn an_isolated_clip_group_with_its_own_effect_is_marqueed_by_its_members_own_geometry() {
set_drawn_art(shifted_art);
let mut d = Document::new(400.0, 200.0);
let l = d.layers[0].id;
let (mask, art) = half_clipped(&mut d);
let (g, art_id) = (d.alloc_id(), art.id);
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
clip.set_clips(true);
clip.appearance.effects.push(effect("test.shift"));
d.insert(Some(l), 0, clip).unwrap();
let tools = HitOptions { clip_outlines: true, scope: Some(g), ..HitOptions::default() };
assert_eq!(hit_at(&d, 150.0, 50.0, tools).map(|h| h.0), Some(art_id), "a click outside the mask");
let edge = Rect::new(190.0, 40.0, 210.0, 60.0);
for leaves in [false, true] {
assert_eq!(marquee(&d, edge, Some(g), leaves), [art_id], "a marquee across its own edge outside the mask");
}
}
/// A clip group whose drawn art holds only its clipping path still has the art it clips clicked
/// inside the mask.
#[test]
fn a_clip_groups_art_is_hit_when_its_drawn_art_holds_only_the_clipping_path() {
set_drawn_art(shifted_art);
let mut d = Document::new(400.0, 200.0);
let l = d.layers[0].id;
let (mask, art) = half_clipped(&mut d);
let (g, art_id) = (d.alloc_id(), art.id);
let mut clip = Node::group(g, vec![Arc::new(mask), Arc::new(art)]);
clip.set_clips(true);
clip.appearance.effects.push(effect("test.mask_only"));
d.insert(Some(l), 0, clip).unwrap();
let opt = HitOptions::default();
assert_eq!(hit_at(&d, 50.0, 50.0, opt), Some((art_id, HitKind::Fill)), "inside the mask");
assert_eq!(objects_at(&d, Point::new(50.0, 50.0), opt, None), [g]);
assert!(hit_at(&d, 150.0, 50.0, opt).is_none(), "outside the mask");
}
/// Every test of a clip group by its clipping path follows the region a live effect moved it to:
/// the selected art hidden by the mask, a click into a group holding the clip group, the locked
/// objects under the pointer, and, below a clipping layer whose Preview is on, art on a sublayer
@@ -453,6 +870,68 @@ fn a_selected_guide_hidden_by_a_mask_counts_only_while_guides_can_be_clicked() {
assert_eq!(selected_hidden_at(&d, hidden, HitOptions { skip_guides: true, ..opt }, &[guide_id]), None);
}
/// #8538: while guides are locked or hidden (`skip_guides`), a marquee touches no guide path, at
/// the top of a layer or in a group (the group is not taken for it), nor in a group in a group,
/// with leaves or without. The group's other members still take it, and with the guides unlocked
/// the guide does.
#[test]
fn a_marquee_skips_guide_paths_in_groups_while_guides_are_locked() {
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let guide = |d: &mut Document, r: Rect| {
let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art());
if let NodeKind::Path { guide, .. } = &mut n.kind {
*guide = true;
}
n
};
let top = guide(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0));
let inner = guide(&mut d, Rect::new(100.0, 0.0, 120.0, 20.0));
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(200.0, 0.0, 220.0, 20.0)), Appearance::default_art());
let (top_id, inner_id, art_id) = (top.id, inner.id, art.id);
let (outer_id, nested_id) = (d.alloc_id(), d.alloc_id());
let nested = Node::group(nested_id, vec![Arc::new(inner)]);
d.insert(Some(l), 0, top).unwrap();
d.insert(Some(l), 1, Node::group(outer_id, vec![Arc::new(nested), Arc::new(art)])).unwrap();
let (on_top, on_inner, on_art) = (Rect::new(-5.0, 5.0, 5.0, 10.0), Rect::new(95.0, 5.0, 105.0, 10.0), Rect::new(195.0, 5.0, 205.0, 10.0));
for leaves in [false, true] {
let m = |r: Rect, skip: bool| marquee_in_view(&d, r, None, leaves, false, skip);
assert!(m(on_top, true).is_empty(), "a guide at the top, leaves {leaves}");
assert!(m(on_inner, true).is_empty(), "a guide in a group in a group, leaves {leaves}");
assert!(m(Rect::new(0.0, 0.0, 300.0, 200.0), true).iter().all(|id| ![top_id, inner_id].contains(id)), "all, leaves {leaves}");
assert_eq!(m(on_art, true), [if leaves { art_id } else { outer_id }], "the group's art, leaves {leaves}");
// Unlocked: the guides are touched.
assert_eq!(m(on_top, false), [top_id], "unlocked, leaves {leaves}");
assert_eq!(m(on_inner, false), [if leaves { inner_id } else { outer_id }], "unlocked, leaves {leaves}");
}
// An enclosing loop's candidates leave them out alike.
assert!(enclosure_candidates(&d, on_inner, None, false, true).is_empty());
assert_eq!(enclosure_candidates(&d, on_inner, None, false, false), [inner_id]);
}
/// #8538: an enclosing loop's candidates leave out a compound path whose touched contours are all
/// locked or hidden guides, as the marquee does.
#[test]
fn guide_contours_do_not_make_a_compound_an_enclosure_candidate() {
let mut d = Document::new(300.0, 200.0);
let l = d.layers[0].id;
let part = |d: &mut Document, r: Rect| {
let mut n = Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::default_art());
if let NodeKind::Path { guide, .. } = &mut n.kind {
*guide = true;
}
Arc::new(n)
};
let (a, b) = (part(&mut d, Rect::new(10.0, 10.0, 50.0, 50.0)), part(&mut d, Rect::new(20.0, 20.0, 40.0, 40.0)));
let id = d.alloc_id();
let mut compound = Node::group(id, vec![]);
compound.kind = NodeKind::Compound { children: vec![a, b], rule: Default::default() };
d.insert(Some(l), 0, compound).unwrap();
let r = Rect::new(0.0, 0.0, 60.0, 60.0);
assert!(enclosure_candidates(&d, r, None, false, true).is_empty(), "locked or hidden");
assert_eq!(enclosure_candidates(&d, r, None, false, false), [id], "shown and unlocked");
}
/// A selected path in a Shaper group's original shapes, where an outer mask hides it, counts only
/// while those shapes can be clicked (Construction mode, with them isolated), however deep it
/// lies in them.
@@ -845,6 +1324,60 @@ fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() {
assert_eq!(evaluated(), before + 2);
}
/// For instances of the symbol "Painted", a fill that paints the square from (300, 0) to
/// (320, 20); nothing for anything else.
fn painted_far_away(_: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> {
match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if symbol == "Painted" => {
let square = shapes::rectangle(Rect::new(300.0, 0.0, 320.0, 20.0)).to_bezpath();
vec![(square, FillRule::NonZero, AppearanceItem::Fill(crate::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))))]
}
_ => vec![],
}
}
/// Clicks and hovers measure the shapes a symbol instance's fill and stroke effects paint once,
/// and again only after the instance or the symbols change.
#[test]
fn clicks_measure_a_symbol_instances_painted_shapes_once_until_it_changes() {
set_image_paint(painted_far_away);
let mut d = Document::new(1000.0, 1000.0);
let l = d.layers[0].id;
let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art());
d.symbols.push(crate::Symbol { dynamic: false, name: "Painted".into(), art: Arc::new(art) });
let inst = d.alloc_id();
let mut n = Node::new(inst, NodeKind::SymbolInstance { symbol: "Painted".into(), xf: vectorcraft_geom::Affine::IDENTITY });
n.appearance = Appearance::default_art().into();
let offset = crate::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 10}), visible: true };
n.appearance.items[0].effects_mut().push(offset);
d.insert(Some(l), 0, n).unwrap();
let measured = || PAINT_EVALUATED.with(std::cell::Cell::get);
let before = measured();
let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 10.0), HitOptions::default()).map(|h| h.leaf);
assert_eq!(at(&d, 310.0), Some(inst), "a click where the instance's fill paints");
assert_eq!(at(&d, 500.0), None);
assert_eq!(at(&d, 10.0), Some(inst));
assert_eq!(measured(), before + 1);
d.node_mut(inst).unwrap().appearance.items[0].effects_mut()[0].params = serde_json::json!({"offset": 12});
assert_eq!(at(&d, 310.0), Some(inst));
assert_eq!(measured(), before + 2, "a changed instance is measured again");
let other = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art());
d.symbols.push(crate::Symbol { dynamic: false, name: "Other".into(), art: Arc::new(other) });
assert_eq!(at(&d, 310.0), Some(inst));
assert_eq!(measured(), before + 3, "changed symbols measure it again");
assert_eq!(at(&d, 310.0), Some(inst));
assert_eq!(measured(), before + 3);
// An image's pixels change when its file is read again, so with one in a symbol's art every
// click measures the instance.
let xf = vectorcraft_geom::Affine::IDENTITY;
let im = crate::ImageObject { key: "k".into(), width: 10, height: 10, xf, link: None, placement: Default::default(), pixels: None };
let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)));
d.symbols.push(crate::Symbol { dynamic: false, name: "Photo".into(), art: Arc::new(image) });
assert_eq!(at(&d, 310.0), Some(inst));
assert_eq!(at(&d, 310.0), Some(inst));
assert!(measured() >= before + 5, "each click measures it: {}", measured() - before);
}
/// A kept evaluation is the evaluation of the object only while the fonts and plug-ins
/// ([`LiveInputs`]) are as they were.
#[test]
@@ -857,19 +1390,32 @@ fn a_kept_evaluation_is_stale_after_the_live_inputs_change() {
}
/// An evaluation of `n` in `d`, with inputs 7, holding no symbols, patterns or art.
fn kept_evaluation(d: &Document, n: &Node) -> EvaluatedLive {
EvaluatedLive {
fn kept_evaluation(d: &Document, n: &Node) -> Evaluated<Vec<Node>> {
Evaluated {
node: n.clone(),
symbols: vec![],
patterns: vec![],
swatches: d.swatches.clone(),
swatch_groups: d.swatch_groups.clone(),
unknown: d.unknown.clone(),
inputs: 7,
art: std::rc::Rc::new(vec![]),
size: 0,
}
}
/// A kept evaluation is stale once a symbol's 9-slice guides or natural size change: they place
/// the symbol's art, and the document keeps them apart from the symbols.
#[test]
fn a_kept_evaluation_is_stale_after_a_symbols_placement_changes() {
let mut d = Document::new(100.0, 100.0);
let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art());
let e = kept_evaluation(&d, &n);
assert!(e.is_of(&d, &n, 7));
d.unknown.insert(crate::SYMBOL_SIZES.into(), serde_json::json!({"Logo": [40.0, 20.0]}));
assert!(!e.is_of(&d, &n, 7));
}
/// A kept evaluation is stale once a swatch changes, in a color group too: a painted live effect's
/// pieces name swatches.
#[test]
@@ -1406,6 +1952,216 @@ fn objects_at_matches_repeated_hits_on_random_documents() {
}
}
/// [`objects_at_repeated_after`] with each found object looked up in the ordered list itself: the
/// reference the tests below hold the set lookup to, and the base that `select_behind_isolation_timing` times.
fn objects_at_repeated_after_by_list(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>, mut tops: Vec<NodeId>) -> Vec<NodeId> {
while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) {
if tops.contains(&top) {
break;
}
tops.push(top);
}
tops
}
/// A layer holding a group of `count` overlapping 50 × 50 squares, member `i` at x = 5 × (`i` mod
/// 10), with a square at x = 0 below the group and above it, and one at x = 100 above it: the
/// document, the group and its members, topmost first.
fn isolated_stack(count: u32) -> (Document, NodeId, Vec<NodeId>) {
let mut d = Document::new(200.0, 200.0);
let l = d.layers[0].id;
let square = |d: &mut Document, x: f64| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default_art());
let below = square(&mut d, 0.0);
d.insert(Some(l), usize::MAX, below).unwrap();
let members: Vec<Node> = (0..count).map(|i| square(&mut d, f64::from(i % 10) * 5.0)).collect();
let mut ids: Vec<NodeId> = members.iter().map(|n| n.id).collect();
let g = d.alloc_id();
d.insert(Some(l), usize::MAX, Node::group(g, members.into_iter().map(Arc::new).collect())).unwrap();
for x in [0.0, 100.0] {
let above = square(&mut d, x);
d.insert(Some(l), usize::MAX, above).unwrap();
}
ids.reverse();
(d, g, ids)
}
/// Select Behind in an isolated group of 40 overlapping squares, with art around the group above
/// and below them: each member once, front to back, over 41 rounds of hit tests, and nothing where
/// only the art around the group lies.
#[test]
fn select_behind_in_isolation_lists_a_large_stack_once() {
let (d, g, ids) = isolated_stack(40);
let at = |x: f64, scope| objects_at(&d, Point::new(x, 25.0), HitOptions::default(), scope);
assert_eq!(at(47.5, Some(g)), ids);
assert_eq!(at(47.5, Some(g)).iter().collect::<HashSet<_>>().len(), 40, "no object twice");
assert_eq!(at(47.5, None).len(), 3, "not isolated: the square above, the group and the square below");
// At x = 17.5 only the members at x = 0 to 20 are hit (the one at 20 on its stroke, within
// the tolerance): `ids[k]` is member 39 - k.
let left: Vec<NodeId> = ids.iter().enumerate().filter(|(k, _)| (39 - k) % 10 <= 4).map(|(_, id)| *id).collect();
assert_eq!(left.len(), 20);
assert_eq!(at(17.5, Some(g)), left);
assert!(at(125.0, Some(g)).is_empty(), "only the square around the group");
assert_eq!(at(125.0, None).len(), 1);
let isolated = HitOptions { scope: Some(g), ..HitOptions::default() };
let p = Point::new(47.5, 25.0);
assert_eq!(objects_at_repeated_after(&d, p, isolated, Some(g), ids[..15].to_vec()), ids, "the objects passed in stay first");
let (d, g, clip, art) = masked_square(false);
let isolated = HitOptions { scope: Some(g), ..SELECTING };
for p in [Point::new(140.0, 90.0), Point::new(170.0, 90.0), Point::new(100.0, 90.0)] {
let want = objects_at_repeated_after_by_list(&d, p, isolated, Some(g), vec![]);
assert_eq!(objects_at(&d, p, SELECTING, Some(g)), want, "clip group isolated, {p:?}");
}
assert_eq!(objects_at(&d, Point::new(170.0, 90.0), SELECTING, Some(g)), vec![art], "the art its mask hides");
assert!(objects_at(&d, Point::new(140.0, 90.0), SELECTING, Some(g)).contains(&clip), "the mask on its outline");
}
/// Documents built at random (nested groups, clipping groups, envelopes in Edit Contents, hidden
/// and locked objects), each object in turn isolated, and each list started with some of the
/// objects already found: the set lookup returns what the ordered-list lookup returns, field for
/// field.
#[test]
fn select_behind_in_isolation_matches_the_list_lookup_on_random_documents() {
let mut seed = 0x2545_f491_u32;
let mut next = move |n: u32| {
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
seed % n
};
fn fill(d: &mut Document, parent: NodeId, depth: u32, next: &mut impl FnMut(u32) -> u32) {
for _ in 0..2 + next(5) {
let id = d.alloc_id();
let rect = |next: &mut dyn FnMut(u32) -> u32| {
let (x, y) = (f64::from(next(60)), f64::from(next(60)));
Rect::new(x, y, x + 10.0 + f64::from(next(50)), y + 10.0 + f64::from(next(50)))
};
let mut n = match next(if depth < 3 { 9 } else { 4 }) {
4 | 5 => Node::group(id, Vec::new()),
6 => {
let mut g = Node::group(id, Vec::new());
g.set_clips(true);
g
}
7 => {
let content =
(0..2).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(rect(next)), Appearance::default_art()))).collect();
Node::new(
id,
NodeKind::Envelope {
content,
kind: Box::new(crate::live::EnvelopeKind::Warp {
style: "arc".to_string(),
bend: 0.0,
h: 0.0,
v: 0.0,
horizontal: true,
version: 0,
}),
fidelity: 100.0,
editing: next(2) == 0,
options: Default::default(),
frame: Box::new(vectorcraft_geom::Affine::IDENTITY),
},
)
}
_ => Node::path(id, shapes::rectangle(rect(next)), if next(4) == 0 { Appearance::default() } else { Appearance::default_art() }),
};
n.visible = next(8) != 0;
n.locked = next(8) == 0;
let group = matches!(n.kind, NodeKind::Group { .. });
d.insert(Some(parent), usize::MAX, n).unwrap();
if group {
fill(d, id, depth + 1, next);
}
}
}
let mut compared = 0;
for round in 0..60 {
let mut d = Document::new(120.0, 120.0);
let layer = d.layers[0].id;
fill(&mut d, layer, 0, &mut next);
let mut scopes = vec![None];
d.walk(|n| {
if n.id != layer {
scopes.push(Some(n.id));
}
});
for _ in 0..6 {
let p = Point::new(f64::from(next(120)), f64::from(next(120)));
let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() };
for &scope in &scopes {
let opt = HitOptions { scope, ..opt };
let want = objects_at_repeated_after_by_list(&d, p, opt, scope, vec![]);
let context = format!("round {round}, {p:?}, {opt:?}");
assert_eq!(objects_at_repeated_after(&d, p, opt, scope, vec![]), want, "{context}");
if scope.is_some() {
assert_eq!(objects_at(&d, p, opt, scope), want, "{context}");
}
for found in 1..want.len() {
let start = want[..found].to_vec();
assert_eq!(objects_at_repeated_after(&d, p, opt, scope, start.clone()), want, "{context}, {found} found");
assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, scope, start), want, "{context}, {found} found");
}
compared += usize::from(!want.is_empty());
}
}
}
assert!(compared > 500, "only {compared} non-empty lists compared");
}
/// Times Select Behind in an isolated group of 200 and of 1,000 overlapping squares, the set lookup
/// against the ordered-list lookup, alternating the two in one process:
/// `cargo test --release -p vectorcraft-doc --lib -- --ignored --nocapture select_behind_isolation_timing`.
#[test]
#[ignore = "a timing, not a check"]
fn select_behind_isolation_timing() {
/// This thread's CPU time in nanoseconds on Linux; the elapsed time since `start` elsewhere.
fn clock(start: std::time::Instant) -> u128 {
let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok();
cpu.and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or_else(|| start.elapsed().as_nanos())
}
type Lookup = fn(&Document, Point, HitOptions, Option<NodeId>, Vec<NodeId>) -> Vec<NodeId>;
let start = std::time::Instant::now();
println!("clock: {}", if std::fs::metadata("/proc/thread-self/schedstat").is_ok() { "thread CPU time" } else { "wall clock" });
let p = Point::new(47.5, 25.0);
for count in [200, 1_000] {
let (d, g, ids) = isolated_stack(count);
let opt = HitOptions { scope: Some(g), ..HitOptions::default() };
assert_eq!(objects_at_repeated_after(&d, p, opt, Some(g), vec![]), ids);
assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, Some(g), vec![]), ids);
// The time per call of `f`: batches of calls double until one takes at least 100 ms.
let per_call = |f: Lookup| {
let mut calls = 1u32;
loop {
let t = clock(start);
for _ in 0..calls {
std::hint::black_box(f(&d, std::hint::black_box(p), opt, Some(g), vec![]));
}
let spent = clock(start) - t;
if spent >= 100_000_000 || calls >= 1 << 20 {
return (spent as f64 / f64::from(calls), calls);
}
calls *= 2;
}
};
let (mut old, mut new) = (vec![], vec![]);
for _ in 0..7 {
old.push(per_call(objects_at_repeated_after_by_list));
new.push(per_call(objects_at_repeated_after));
}
old.sort_by(|a, b| a.0.total_cmp(&b.0));
new.sort_by(|a, b| a.0.total_cmp(&b.0));
let (o, n) = (old[3], new[3]);
println!(
"{count} objects: list lookup {:.2} ms per call ({} calls), set lookup {:.2} ms per call ({} calls), median of 7 runs",
o.0 / 1e6,
o.1,
n.0 / 1e6,
n.1
);
}
}
/// Select Behind finds a symbol instance by its symbol's art, as a click does: art from
/// (100, 60) to (140, 80), outside the 20 × 20 square around the origin, drawn where it lies by
/// one instance and 100 pt lower by an instance in a group.
@@ -1980,7 +2736,7 @@ fn a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art
assert_eq!(marquee(&d, edge, None, false), [g], "layer {layer}");
assert_eq!(marquee(&d, edge, None, true), [inst], "layer {layer}");
assert!(marquee(&d, past, None, false).is_empty());
assert!(marquee_in_view(&d, edge, None, false, true).is_empty(), "Outline view");
assert!(marquee_in_view(&d, edge, None, false, true, false).is_empty(), "Outline view");
}
// Preview off for the layer the instance is on.
let (mut d, _, _) = build("test.move", Affine::IDENTITY, false, true, false);
+26
View File
@@ -82,6 +82,16 @@ impl Paths {
pub(crate) fn len(&self) -> usize {
self.ids.len()
}
/// The entry of `id` in the table: `Some(None)` when the id appears more than once, `None`
/// when it isn't in the table.
pub(crate) fn entry(&self, id: &NodeId) -> Option<Option<u32>> {
self.ids.get(id).copied()
}
/// Entry `e`'s parent entry (`u32::MAX` for a top-level layer) and its index among its
/// siblings.
pub(crate) fn place(&self, e: u32) -> Option<(u32, u32)> {
self.at.get(e as usize).copied()
}
}
/// Lookups that had to walk (the cache didn't have the id, or its path no longer checks out)
@@ -108,6 +118,22 @@ pub(crate) fn note_tree_walk() {
TREE_WALKS.set(TREE_WALKS.get().saturating_add(1));
}
thread_local! {
/// [`path_lookups`] of this thread.
static PATH_LOOKUPS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// How many times [`crate::Document::index_path`] has run on this thread, the lookups that
/// [`crate::Document::node`] and [`crate::Document::ancestry`] make through it included.
pub fn path_lookups() -> u64 {
PATH_LOOKUPS.get()
}
/// Adds one to [`path_lookups`].
pub(crate) fn note_path_lookup() {
PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1));
}
/// The cache, shared by clones of a document (each checks every path it uses against its own tree).
#[derive(Default)]
pub struct IdIndex(RwLock<Option<Arc<Paths>>>, std::sync::atomic::AtomicU32);
+107 -16
View File
@@ -15,7 +15,8 @@ use crate::{AppearanceItem, Document, Node, NodeKind};
pub struct Inks {
/// Process inks C, M, Y, K (0..1).
pub cmyk: [f32; 4],
/// Spot ink (swatch name, tint 0..1).
/// Spot ink (swatch name, tint 0..1). A spot ink named like a process plate ("Cyan",
/// "Magenta", "Yellow", "Black") prints on that plate: its tint is in `cmyk` too.
pub spot: Option<(String, f32)>,
/// Registration: the tint (every process ink's) prints on every spot plate too.
pub registration: bool,
@@ -49,7 +50,20 @@ pub struct Plate {
pub rgb: [f32; 3],
}
/// The plates of `doc`: the four process plates plus one per spot swatch.
/// Spot swatch `name` as art links to it: [`Document::swatch`] `name` when that is a spot swatch of
/// a solid colour.
fn spot_swatch<'a>(doc: &'a Document, name: &str) -> Option<&'a vectorcraft_color::Swatch> {
doc.swatch(name).filter(|s| s.spot && s.paint.color().is_some())
}
/// The index in [`PROCESS_PLATES`] of the process plate named `name`.
fn process_plate(name: &str) -> Option<usize> {
PROCESS_PLATES.iter().position(|p| *p == name)
}
/// The plates of `doc`: the four process plates plus one per spot swatch that art can link to. A
/// link names a swatch, which is the first swatch of that name ([`Document::swatch`]), so a spot
/// swatch after another of its name, or named like a process plate, gets no plate.
pub fn plates(doc: &Document) -> Vec<Plate> {
let c = vectorcraft_color::cms::active();
let mut v: Vec<Plate> = PROCESS_PLATES
@@ -61,20 +75,29 @@ pub fn plates(doc: &Document) -> Vec<Plate> {
Plate { name: (*n).into(), spot: false, rgb: c.cmyk_to_srgb(ink, false) }
})
.collect();
let mut seen = std::collections::HashSet::new();
for sw in doc.swatches_iter() {
if let (true, Paint::Solid { color, .. }) = (sw.spot, &sw.paint)
&& !v.iter().any(|p| p.name == sw.name)
// Only the first swatch of a name is the one [`spot_swatch`] finds.
if !seen.insert(sw.name.as_str()) {
continue;
}
if let (true, Some(color)) = (sw.spot, sw.paint.color())
&& !PROCESS_PLATES.contains(&sw.name.as_str())
{
v.push(Plate { name: sw.name.clone(), spot: true, rgb: c.display_rgb(&doc.linked_color(*color, true)) });
v.push(Plate { name: sw.name.clone(), spot: true, rgb: c.display_rgb(&doc.linked_color(color, true)) });
}
}
v
}
/// The ink colour of spot swatch `name` as it shows ([`Document::linked_color`]).
/// The ink colour of spot swatch `name` as it shows ([`Document::linked_color`]); `None` when
/// [`Document::swatch`] `name` is not a spot swatch, or `name` is a process plate's, whose ink
/// prints on that plate.
pub fn spot_color(doc: &Document, name: &str) -> Option<Color> {
let s = doc.swatch(name).filter(|s| s.spot)?;
s.paint.color().map(|c| doc.linked_color(c, true))
if process_plate(name).is_some() {
return None;
}
spot_swatch(doc, name)?.paint.color().map(|c| doc.linked_color(c, true))
}
/// A colour's swatch link and tint (`(swatch name, tint 0..1)`), as the colour visitors pass it.
@@ -86,16 +109,22 @@ fn ink_amount(v: f32) -> f32 {
}
/// Separate one colour into inks. A colour linked to a spot swatch prints on that plate only, at
/// its tint; one linked to the Registration swatch prints its tint on every plate. A tint that is
/// not a finite number prints no ink.
/// its tint, and one linked to a spot swatch named like a process plate prints its tint on that
/// process plate, as PDF and EPS export write it; one linked to the Registration swatch prints its
/// tint on every plate. A tint that is not a finite number prints no ink.
pub fn inks(doc: &Document, c: &Cms, color: &Color, link: Link, intent: Intent) -> Inks {
if let Some((REGISTRATION, tint)) = link {
return Inks { cmyk: [ink_amount(tint); 4], spot: None, registration: true };
}
if let Some((name, tint)) = link
&& doc.swatch(name).is_some_and(|s| s.spot && s.paint.color().is_some())
&& spot_swatch(doc, name).is_some()
{
return Inks { cmyk: [0.0; 4], spot: Some((name.to_string(), ink_amount(tint))), registration: false };
let tint = ink_amount(tint);
let mut cmyk = [0.0; 4];
if let Some(i) = process_plate(name) {
cmyk[i] = tint;
}
return Inks { cmyk, spot: Some((name.to_string(), tint)), registration: false };
}
Inks { cmyk: c.to_cmyk(color, intent), spot: None, registration: false }
}
@@ -106,11 +135,18 @@ pub type StopPlates = Option<[f32; 4]>;
/// [`inks`] of a colour that may print process plates `plates` with its spot tint. The plates
/// print only beside a spot ink: a colour without a valid spot link, or linked to Registration,
/// prints as [`inks`] separates it. A plate amount that is not a finite number prints no ink.
/// prints as [`inks`] separates it. A spot ink named like a process plate prints its tint layered
/// over that plate's amount; EPS export can't write that ink beside process plates in one DeviceN
/// space, so it writes such a gradient in process colors with a warning. A plate amount that is
/// not a finite number prints no ink.
pub fn stop_inks(doc: &Document, c: &Cms, color: &Color, link: Link, plates: StopPlates, intent: Intent) -> Inks {
let mut ink = inks(doc, c, color, link, intent);
if let (Some(p), Some(_)) = (plates, &ink.spot) {
ink.cmyk = p.map(ink_amount);
if let (Some(p), Some((name, tint))) = (plates, &ink.spot) {
let mut cmyk = p.map(ink_amount);
if let Some(i) = process_plate(name) {
cmyk[i] = 1.0 - (1.0 - cmyk[i]) * (1.0 - tint);
}
ink.cmyk = cmyk;
}
ink
}
@@ -201,7 +237,7 @@ pub fn map_document_colors(doc: &mut Document, f: &mut dyn FnMut(&Color, Link) -
mod tests {
use super::*;
use crate::{NodeId, SymbolOverride};
use vectorcraft_color::{Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Swatch};
use vectorcraft_color::{Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Swatch, SwatchGroup};
use vectorcraft_geom::Affine;
/// A document with spot swatch `Gold` and process swatch `Teal`.
@@ -233,6 +269,61 @@ mod tests {
}
}
/// The names of `doc`'s spot plates, in order.
fn spot_plates(doc: &Document) -> Vec<String> {
plates(doc).into_iter().filter(|p| p.spot).map(|p| p.name).collect()
}
#[test]
fn a_spot_swatch_named_like_an_earlier_process_swatch_gets_no_plate() {
// Art links to a swatch by name, which finds the earlier process `Teal`: the later spot
// `Teal` in a colour group prints nothing, so it gets no plate.
let mut d = gold_doc();
let spot_teal = Swatch { name: "Teal".into(), paint: Paint::solid(Color::cmyk(0.9, 0.0, 0.4, 0.0)), global: true, spot: true };
d.swatch_groups.push(SwatchGroup { name: "Inks".into(), swatches: vec![spot_teal.clone()] });
let c = vectorcraft_color::cms::active();
let look = Color::cmyk(0.8, 0.0, 0.3, 0.0);
let teal = inks(&d, &c, &look, Some(("Teal", 1.0)), Intent::RelativeColorimetric);
assert_eq!(teal, Inks { cmyk: c.to_cmyk(&look, Intent::RelativeColorimetric), spot: None, registration: false });
let stop = stop_inks(&d, &c, &look, Some(("Teal", 1.0)), Some([0.25, 0.0, 0.4, 0.0]), Intent::RelativeColorimetric);
assert_eq!(stop, teal, "a gradient stop linked to it separates as process too");
assert_eq!(spot_color(&d, "Teal"), None);
assert_eq!(spot_plates(&d), ["Gold"], "no plate for the spot swatch that no art reaches");
// The first swatch of a name decides either way: a spot swatch first gets its plate, and a
// later process swatch of the same name does not take it away.
let mut d = gold_doc();
d.swatches.retain(|s| s.name != "Teal");
d.swatches.insert(0, spot_teal);
let process_teal = Swatch { name: "Teal".into(), paint: Paint::solid(look), global: true, spot: false };
d.swatch_groups.push(SwatchGroup { name: "Inks".into(), swatches: vec![process_teal] });
assert_eq!(spot_plates(&d), ["Teal", "Gold"]);
let teal = inks(&d, &c, &look, Some(("Teal", 0.5)), Intent::RelativeColorimetric);
assert_eq!(teal, Inks { cmyk: [0.0; 4], spot: Some(("Teal".into(), 0.5)), registration: false });
assert_eq!(spot_color(&d, "Teal"), Some(Color::cmyk(0.9, 0.0, 0.4, 0.0)));
}
#[test]
fn a_spot_swatch_named_like_a_process_plate_prints_on_that_plate() {
// A spot `Cyan` has the process Cyan plate's name, so art linked to it prints its tint on
// that plate, as a Separation ink named `Cyan` in PDF and EPS export does, instead of a
// spot amount that no plate prints.
let mut d = gold_doc();
let blue = Color::cmyk(1.0, 0.3, 0.0, 0.1);
d.swatches.insert(0, Swatch { name: "Cyan".into(), paint: Paint::solid(blue), global: true, spot: true });
let c = vectorcraft_color::cms::active();
let ink = inks(&d, &c, &blue, Some(("Cyan", 0.5)), Intent::RelativeColorimetric);
assert_eq!(ink, Inks { cmyk: [0.5, 0.0, 0.0, 0.0], spot: Some(("Cyan".into(), 0.5)), registration: false });
assert_eq!((ink.on_plate("Cyan"), ink.on_plate("Magenta"), ink.on_plate("Gold")), (0.5, 0.0, 0.0));
let nan = inks(&d, &c, &blue, Some(("Cyan", f32::NAN)), Intent::RelativeColorimetric);
assert_eq!(nan.cmyk, [0.0; 4], "a tint that is not a number prints no ink");
// A gradient stop's own process plates still print, with the tint layered over its Cyan.
let stop = stop_inks(&d, &c, &blue, Some(("Cyan", 0.5)), Some([0.2, 0.4, 0.0, 0.0]), Intent::RelativeColorimetric);
assert!((stop.on_plate("Cyan") - 0.6).abs() < 1e-6, "{stop:?}");
assert_eq!((stop.on_plate("Magenta"), stop.on_plate("Yellow"), stop.on_plate("Black")), (0.4, 0.0, 0.0));
assert_eq!(spot_color(&d, "Cyan"), None);
assert_eq!(spot_plates(&d), ["Gold"]);
}
#[test]
fn a_spot_or_registration_tint_that_is_not_a_finite_number_prints_no_ink() {
let d = gold_doc();
+218 -10
View File
@@ -117,6 +117,29 @@ impl Document {
/// symbol that shows itself inline ([`Self::inline_art_bounds`]) is shown as an empty slot.
/// Returns the ids of the texts in the layers that changed.
pub fn resolve_inline_art_with(&mut self, layout: &mut dyn FnMut(&mut TextObject)) -> Vec<NodeId> {
self.resolve_inline_art_since(None, layout).changed
}
/// [`Self::resolve_inline_art_with`], given `last`: a document an earlier pass left resolved,
/// with the bounds that pass measured ([`InlinePass::measured`]). When this document has the
/// same symbols, graph designs, pattern tiles and foreign data (`unknown`, which holds the
/// symbols' natural sizes and 9-slice guides) as `last`, and each symbol name measured then
/// still measures the same, the type in the layer trees that are the same nodes as `last`'s
/// already has these bounds: only the other layer trees are checked, in the same order, and
/// the document and the ids returned are those of the full pass. Otherwise, or without `last`,
/// the full pass runs.
pub fn resolve_inline_art_since(&mut self, last: Option<(&Document, &InlineMeasured)>, layout: &mut dyn FnMut(&mut TextObject)) -> InlinePass {
if let Some((last, kept)) = last
&& self.same_inline_inputs(last, kept)
{
let measured = Measured(RefCell::new(kept.0.clone()));
let mut changed = vec![];
let layers = resolve_kids(Some(&last.layers), &self.layers, &|n| measured.get(n, || self.inline_art_bounds(n)), layout, &mut changed);
for (i, layer) in layers {
self.layers[i] = layer;
}
return InlinePass { changed, measured: InlineMeasured(measured.0.into_inner()), partial: true };
}
let mut out = vec![];
let mut unused = vec![];
let graph = InlineGraph::of(self);
@@ -147,10 +170,44 @@ impl Document {
}
}
}
out
InlinePass { changed: out, measured: InlineMeasured(measured.0.into_inner()), partial: false }
}
/// Whether the type in this document's layer trees that are the same nodes as `last`'s already
/// has the bounds a full pass would give it (see [`Self::resolve_inline_art_since`]).
fn same_inline_inputs(&self, last: &Document, kept: &InlineMeasured) -> bool {
self.symbols.len() == last.symbols.len()
&& self.symbols.iter().zip(&last.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
&& self.graph_designs.len() == last.graph_designs.len()
&& self.graph_designs.iter().zip(&last.graph_designs).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art))
&& self.patterns.len() == last.patterns.len()
&& self
.patterns
.iter()
.zip(&last.patterns)
.all(|(a, b)| a.name == b.name && a.art.len() == b.art.len() && a.art.iter().zip(&b.art).all(|(x, y)| Arc::ptr_eq(x, y)))
&& crate::Shared::ptr_eq(&self.unknown, &last.unknown)
&& kept.0.iter().all(|(name, b)| self.inline_art_bounds(name) == *b)
}
}
/// What a pass of [`Document::resolve_inline_art_since`] did.
#[derive(Debug)]
pub struct InlinePass {
/// The ids of the texts in the layers that changed, in the order the full pass finds them.
pub changed: Vec<NodeId>,
/// The bounds the pass gave the inline graphics of each symbol name, for the next pass.
pub measured: InlineMeasured,
/// Whether only the layer trees that differ from the last resolved document's were checked.
pub partial: bool,
}
/// The art bounds a pass of [`Document::resolve_inline_art_since`] gave the inline graphics of each
/// symbol name it was asked for. A pass that checks only some layer trees keeps the names the
/// pass before it measured, so the names of all the type in the document stay listed.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct InlineMeasured(HashMap<String, Option<Rect>>);
/// Whether `t` has inline graphics whose bounds differ from what `bounds` gives their symbols.
fn stale_by(t: &TextObject, bounds: &dyn Fn(&str) -> Option<Rect>) -> bool {
t.runs.iter().filter_map(|r| r.inline.as_ref()).any(|a| a.bounds != bounds(&a.symbol))
@@ -185,6 +242,22 @@ fn resolve_tree(
layout: &mut dyn FnMut(&mut TextObject),
changed: &mut Vec<NodeId>,
) -> bool {
resolve_since(None, n, bounds, layout, changed)
}
/// [`resolve_tree`], given `old`: the node `n` was before an edit, in a document whose type was
/// resolved with the same `bounds`. The opacity mask art and children of `n` that are the same
/// nodes as `old`'s are skipped: their type already has these bounds. Without `old`, every node
/// of the tree is visited.
fn resolve_since(
old: Option<&Node>,
n: &mut Arc<Node>,
bounds: &dyn Fn(&str) -> Option<Rect>,
layout: &mut dyn FnMut(&mut TextObject),
changed: &mut Vec<NodeId>,
) -> bool {
#[cfg(test)]
tests::VISITS.with(|v| v.set(v.get() + 1));
let mut copied = false;
if matches!(&n.kind, NodeKind::Text(t) if stale_by(t, bounds)) {
let node = Arc::make_mut(n);
@@ -196,17 +269,17 @@ fn resolve_tree(
}
copied = true;
}
let old_mask = old.and_then(|o| o.extras().mask.as_deref()).map(|m| &m.art);
let mask = n.extras().mask.as_deref().and_then(|m| {
let mut art = m.art.clone();
resolve_tree(&mut art, bounds, layout, changed).then_some(art)
});
let mut kids = vec![];
for (i, c) in n.children().into_iter().flatten().enumerate() {
let mut c = c.clone();
if resolve_tree(&mut c, bounds, layout, changed) {
kids.push((i, c));
if old_mask.is_some_and(|o| Arc::ptr_eq(o, &m.art)) {
return None;
}
}
let mut art = m.art.clone();
let old_art = old_mask.filter(|o| o.id == art.id).map(|o| &**o);
resolve_since(old_art, &mut art, bounds, layout, changed).then_some(art)
});
let old_kids = old.map(|o| o.children().map_or(&[][..], Vec::as_slice));
let kids = resolve_kids(old_kids, n.children().map_or(&[][..], Vec::as_slice), bounds, layout, changed);
if mask.is_none() && kids.is_empty() {
return copied;
}
@@ -224,6 +297,35 @@ fn resolve_tree(
true
}
/// Resolves the trees `kids` as [`resolve_since`] does, each with the node of `old` (the same list
/// before an edit) that has its id, found at the same position or else by id, and skips those that
/// are the same nodes as theirs. Without `old`, every tree is visited. Returns the position and new
/// node of each tree that changed.
fn resolve_kids(
old: Option<&[Arc<Node>]>,
kids: &[Arc<Node>],
bounds: &dyn Fn(&str) -> Option<Rect>,
layout: &mut dyn FnMut(&mut TextObject),
changed: &mut Vec<NodeId>,
) -> Vec<(usize, Arc<Node>)> {
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
let mut out = vec![];
for (i, c) in kids.iter().enumerate() {
let o = old.and_then(|old| match old.get(i) {
Some(b) if b.id == c.id => Some(b),
_ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(),
});
if o.is_some_and(|o| Arc::ptr_eq(o, c)) {
continue;
}
let mut c = c.clone();
if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) {
out.push((i, c));
}
}
out
}
/// The art bounds of each symbol, measured once in a pass of [`Document::resolve_inline_art_with`].
/// A symbol is first asked for after its own type is resolved (the pass goes in
/// [`InlineGraph::order`]), so its measurement stays current for the rest of the pass.
@@ -436,6 +538,112 @@ impl std::fmt::Debug for InlineCycles {
mod tests {
use super::*;
thread_local! {
/// How many nodes [`resolve_since`] has visited on this thread.
pub(super) static VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The nodes visited since the last call.
fn visits() -> usize {
VISITS.with(|v| v.replace(0))
}
/// A copy of `d` resolved by the full pass, and the ids that pass returns.
fn fully_resolved(d: &Document) -> (Document, Vec<NodeId>) {
let mut full = d.clone();
let ids = full.resolve_inline_art_with(&mut |_| {});
(full, ids)
}
/// The children of the layer at `i`, for an edit.
fn layer_kids(d: &mut Document, i: usize) -> &mut Vec<Arc<Node>> {
match Arc::make_mut(&mut d.layers[i]).children_mut() {
Some(kids) => kids,
None => panic!("layer {i} is a group"),
}
}
/// 50 groups of 20 squares, symbol `S`, type showing `S` in the first group, and type showing
/// `S` in the opacity mask of the second.
fn many_groups() -> Document {
let mut d = Document::new(500.0, 500.0);
let square = stroked(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0));
symbol(&mut d, "S", vec![square]);
for _ in 0..50 {
let kids = (0..20).map(|_| stroked(&mut d, Rect::new(0.0, 0.0, 5.0, 5.0))).collect();
let group = Node::group(d.alloc_id(), kids);
d.layers.push(Arc::new(group));
}
let t = showing(&mut d, "S");
layer_kids(&mut d, 0).push(t);
let masked = showing(&mut d, "S");
Arc::make_mut(&mut d.layers[1]).extras_mut().mask = Some(Box::new(crate::OpacityMask::new((*masked).clone(), true)));
d
}
#[test]
fn a_pass_after_an_edit_checks_only_the_trees_the_edit_changed() {
let mut d = many_groups();
let first = d.resolve_inline_art_since(None, &mut |_| {});
assert!(!first.partial);
assert_eq!(first.changed.len(), 2);
let last = d.clone();
visits();
let _ = fully_resolved(&d);
let full_visits = visits();
// The edit moves a square in the 31st group, adds type showing S to the 41st, and gives the
// second group's opacity mask new type: its 20 squares stay the same nodes.
let moved = stroked(&mut d, Rect::new(1.0, 1.0, 6.0, 6.0));
layer_kids(&mut d, 30)[5] = moved;
let added = showing(&mut d, "S");
layer_kids(&mut d, 40).push(added.clone());
let mask_type = showing(&mut d, "S");
if let Some(m) = Arc::make_mut(&mut d.layers[1]).extras_if_any().and_then(|e| e.mask.as_deref_mut()) {
m.art = mask_type.clone();
}
let (want, ids) = fully_resolved(&d);
assert_eq!(ids, [mask_type.id, added.id]);
visits();
let pass = d.resolve_inline_art_since(Some((&last, &first.measured)), &mut |_| {});
let partial_visits = visits();
assert!(pass.partial);
assert_eq!(pass.changed, ids);
assert_eq!(d, want);
// The three changed groups, the mask's new type, the moved square and the added type.
assert_eq!(partial_visits, 6);
assert!(full_visits > 1000, "{full_visits}");
assert_eq!(pass.measured, first.measured);
}
#[test]
fn changed_symbols_or_symbol_sizes_take_the_full_pass() {
let mut d = many_groups();
let mut pass = d.resolve_inline_art_since(None, &mut |_| {});
// A natural size for S, its art unchanged.
let last = d.clone();
d.unknown.insert(SYMBOL_SIZES.into(), serde_json::json!({ "S": [40.0, 20.0] }));
let (want, ids) = fully_resolved(&d);
assert_eq!(ids.len(), 2);
pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {});
assert!(!pass.partial);
assert_eq!((&d, &pass.changed), (&want, &ids));
// New art for S.
let last = d.clone();
let bigger = stroked(&mut d, Rect::new(0.0, 0.0, 30.0, 30.0));
d.symbols[0].art = Arc::new(Node::group(d.alloc_id(), vec![bigger]));
let (want, ids) = fully_resolved(&d);
assert_eq!(ids.len(), 2);
pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {});
assert!(!pass.partial);
assert_eq!((&d, &pass.changed), (&want, &ids));
// A measurement that no longer holds, with the same symbols and foreign data.
let last = d.clone();
let stale = InlineMeasured(HashMap::from([("S".to_owned(), Some(Rect::new(0.0, 0.0, 1.0, 1.0)))]));
pass = d.resolve_inline_art_since(Some((&last, &stale)), &mut |_| {});
assert!(!pass.partial);
assert!(pass.changed.is_empty());
}
/// The position of each node in `order`.
fn positions(order: &[usize]) -> Vec<usize> {
let mut at = vec![0; order.len()];
+16 -6
View File
@@ -14,13 +14,15 @@ pub mod cmyk;
pub mod color_mask;
pub mod compound_shape;
pub mod corners;
pub mod decode;
pub mod depth;
pub mod dimension;
pub mod flare;
pub mod graph;
mod halftone_radii;
pub mod hit;
mod id_index;
pub use id_index::tree_walks;
pub use id_index::{path_lookups, tree_walks};
pub mod inks;
mod inline;
pub mod intertwine;
@@ -28,8 +30,9 @@ pub mod shared;
mod symbol_export_type;
mod symbol_nine_slice;
pub mod symbol_overrides;
mod symbol_pixel_aligned;
mod symbol_registration;
pub use inline::{SYMBOL_HALF, SYMBOL_SIZES};
pub use inline::{InlineMeasured, InlinePass, SYMBOL_HALF, SYMBOL_SIZES};
pub use shared::Shared;
pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType};
pub use symbol_nine_slice::{
@@ -37,6 +40,7 @@ pub use symbol_nine_slice::{
SymbolNineSlice, charge_symbol_art,
};
pub use symbol_overrides::SymbolOverride;
pub use symbol_pixel_aligned::SYMBOL_PIXEL_ALIGNED;
pub use symbol_registration::{SYMBOL_REGISTRATION, SymbolRegistration};
pub mod links;
pub mod live;
@@ -45,6 +49,8 @@ pub mod marks;
mod mem;
pub use mem::{appearance_heap_bytes, paint_heap_bytes};
pub mod metadata;
mod nearest;
pub use nearest::NearestFinder;
pub mod node;
pub mod objects_on_path;
pub mod orient;
@@ -52,7 +58,7 @@ pub mod overprint;
pub mod pattern;
pub mod perspective;
mod pixels;
pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick};
pub use pixels::{GraySource, MAX_RASTER_ALLOC, PixelPick, header_size};
pub mod placed_document;
pub mod plugin_data;
pub mod ppi;
@@ -72,6 +78,9 @@ pub mod style_libs;
pub mod swatches;
mod symbols;
pub use symbols::SymbolBoxes;
#[cfg(any(test, feature = "symbol-read-count"))]
#[doc(hidden)]
pub use symbols::symbols_read;
pub mod text;
pub mod trace;
pub mod twist;
@@ -94,8 +103,9 @@ pub use compound_shape::ShapeMode;
pub use corners::LiveCorners;
pub use depth::{MAX_DEPTH, MAX_SYMBOL_NODES};
pub use graph::{
ColumnDesign, ColumnType, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows, LabelStyles, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES,
PiePosition, PieSort, SeriesPaint, TickLength, ValueAxisSide,
ColumnDesign, ColumnType, DEFAULT_FILLED_LINE_WIDTH, FILLED_LINE_OUTLINE_WIDTH, Fractions, GraphDesign, GraphKind, GraphSpec, LabelRows,
LabelStyles, MAX_FILLED_LINE_WIDTH, MAX_GRAPH_CATEGORIES, MAX_GRAPH_SERIES, MIN_FILLED_LINE_WIDTH, PiePosition, PieSort, SeriesPaint, TickLength,
ValueAxisSide,
};
pub use hit::{Hit, HitKind};
pub use links::{LinkInfo, PlacementOptions};
@@ -161,7 +171,7 @@ use limits::MAX_NEXT_ID;
pub use limits::{DocError, FORMAT_VERSION, MAX_COORD};
pub use records::{ImageBlob, MaskEdit, NewArtIds, SavedSelection, SavedView, SvgFilter, Symbol, SymbolEdit};
pub use stored_art::{StoredPlace, StoredRoot};
pub use units::{ColorMode, Unit, parse_number};
pub use units::{ColorMode, Unit, arithmetic_signs, decimal_point, finite_in_every_unit, parse_number};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Document {
+47 -29
View File
@@ -145,9 +145,9 @@ impl ImageBlob {
/// This blob after its pixels are decoded once, within [`crate::MAX_RASTER_ALLOC`], to check
/// that they can be read; with `proxy`, it also gets the preview [`Self::with_proxy`] makes,
/// made from that decode. `None` when the pixels can't be read, as with a file cut short that
/// has a header but not all its pixels. An image whose pixels would take more than the
/// allowance as RGBA is not decoded, and one whose decode needs more than the allowance stops
/// decoding; either is returned as it is.
/// has a header but not all its pixels, or one the decoder refuses as a decompression bomb.
/// An image whose pixels would take more than the allowance as RGBA is not decoded and is
/// returned as it is.
pub fn checked_with_proxy(self, proxy: bool) -> Option<Self> {
self.checked_with_pixels(proxy).map(|(blob, _)| blob)
}
@@ -155,22 +155,12 @@ impl ImageBlob {
/// [`Self::checked_with_proxy`], with the pixels it decoded: `None` beside the blob when it
/// decoded none (an image past the allowance).
pub fn checked_with_pixels(mut self, proxy: bool) -> Option<(Self, Option<image::DynamicImage>)> {
let max = crate::MAX_RASTER_ALLOC;
let reader = || image::ImageReader::new(Cursor::new(self.bytes.as_slice())).with_guessed_format().ok();
let (w, h) = reader()?.into_dimensions().ok()?;
if u64::from(w) * u64::from(h) > max / 4 {
return Some((self, None));
}
let mut r = reader()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(max);
r.limits(limits);
let img = match r.decode() {
Ok(img) => img,
Err(image::ImageError::Limits(_)) => return Some((self, None)),
let img = match crate::decode::decode_within(&self.bytes, crate::MAX_RASTER_ALLOC) {
Ok(Some((img, _))) => img,
Ok(None) => return Some((self, None)),
Err(_) => return None,
};
if proxy && self.proxy.is_none() && w.max(h) > PROXY_SIZE {
if proxy && self.proxy.is_none() && img.width().max(img.height()) > PROXY_SIZE {
self.proxy = proxy_of(&img).map(Arc::new);
}
Some((self, Some(img)))
@@ -210,21 +200,16 @@ pub fn missing_placeholder() -> Option<Vec<u8>> {
/// `bytes` decoded and shrunk to fit [`PROXY_SIZE`] as a PNG; `None` when small enough already or
/// undecodable.
fn proxy_png(bytes: &[u8]) -> Option<Vec<u8>> {
let (w, h) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()?;
let format = craft_image_codecs::detect(bytes)?;
let (w, h, _) = crate::decode::decoded_layout(bytes, format)?;
if w.max(h) <= PROXY_SIZE {
return None;
}
// The proxy decodes within the project's raster cap, counted as RGBA like every other
// decode path (#3597): the header alone decides whether the pixels could ever fit, and the
// decoder gets the same budget instead of image's own default.
if u64::from(w) * u64::from(h) > crate::MAX_RASTER_ALLOC / 4 {
return None;
}
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(crate::MAX_RASTER_ALLOC);
reader.limits(limits);
proxy_of(&reader.decode().ok()?)
// The proxy decodes within the project's raster cap, counted as the file's samples and as
// RGBA like every other decode path (#3597, #1717): the header alone decides whether the
// pixels could ever fit, and the decoder gets the same budget.
let (img, _) = crate::decode::decode_within(bytes, crate::MAX_RASTER_ALLOC).ok()??;
proxy_of(&img)
}
/// Decoded image `img` shrunk to fit [`PROXY_SIZE`] as a PNG.
@@ -748,4 +733,37 @@ mod tests {
assert!(p.pixels().all(|q| q.0 == [200, 30, 30, 128]), "{:?}", p.get_pixel(0, 0));
}
}
/// A PNG that says it is `w` × `h` 1-bit grey pixels (header and a stub IDAT, no rows).
fn png_header_1bit(w: u32, h: u32) -> Vec<u8> {
let mut out = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
let push = |out: &mut Vec<u8>, chunk: &[u8]| {
out.extend((chunk.len() as u32 - 4).to_be_bytes());
out.extend(chunk);
out.extend(crc32(chunk).to_be_bytes());
};
let mut ihdr = b"IHDR".to_vec();
ihdr.extend(w.to_be_bytes());
ihdr.extend(h.to_be_bytes());
ihdr.extend([1, 0, 0, 0, 0]);
push(&mut out, &ihdr);
push(&mut out, b"IDAT\x78\x9c");
push(&mut out, b"IEND");
out
}
/// A header-only 23,170 × 23,170 1-bit gray PNG is within the 2 GiB RGBA allowance, so Place
/// decodes it and must refuse it (no pixel rows). 23,171 × 23,170 is past the allowance and is
/// kept unread, not refused. craft-image-codecs reports the cut-short file as LimitExceeded
/// (its decompression-bomb guard); that is still "pixels can't be read", not "past the allowance".
#[test]
fn a_gray_header_within_the_allowance_is_unreadable() {
let within = png_header_1bit(23_170, 23_170);
let over = png_header_1bit(23_171, 23_170);
assert!(crate::decode::decode_within(&within, crate::MAX_RASTER_ALLOC).is_err(), "header-only within the allowance");
assert!(matches!(crate::decode::decode_within(&over, crate::MAX_RASTER_ALLOC), Ok(None)), "past the allowance is not decoded");
assert!(ImageBlob::new("image/png", within).checked_with_pixels(false).is_none(), "Place refuses the file");
let (_, pixels) = ImageBlob::new("image/png", over).checked_with_pixels(false).expect("past the allowance is kept unread");
assert!(pixels.is_none());
}
}
+28 -1
View File
@@ -65,7 +65,10 @@ pub use expand::{
#[cfg(test)]
use mesh::grid_eval;
pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds};
pub use warp::{WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, pieces, uses_net, warp_point, warp_version};
pub use warp::{
WARP_NET, WarpNet, WarpStyle, fit_piece, map_handles_within, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net,
warp_point, warp_version,
};
#[cfg(test)]
mod tests {
@@ -88,6 +91,30 @@ mod tests {
}
}
/// The smooth map takes each handle along the map's derivative, also far from the origin,
/// where a fixed sampling step would round away (#7069): the identity map keeps a curve's
/// handles there.
#[test]
fn map_smooth_within_keeps_handles_far_from_the_origin() {
for at in [0.0, 1e13] {
let o = Point::new(at, at);
let curve = PathData::single(vectorcraft_geom::SubPath::new(
vec![
vectorcraft_geom::Anchor::with_handles(o, o, o + vectorcraft_geom::Vec2::new(0.2, 0.0)),
vectorcraft_geom::Anchor::with_handles(
o + vectorcraft_geom::Vec2::new(1.0, 0.5),
o + vectorcraft_geom::Vec2::new(0.8, 0.5),
o + vectorcraft_geom::Vec2::new(1.0, 0.5),
),
],
false,
));
let out = map_smooth_within(&curve, 10.0, usize::MAX, |p| p);
let (a, b) = (&curve.subpaths[0].anchors, &out.subpaths[0].anchors);
assert!(a[0].h_out.distance(b[0].h_out) < 0.01 && a[1].h_in.distance(b[1].h_in) < 0.01, "at {at}: {:?} {:?}", b[0].h_out, b[1].h_in);
}
}
/// #3578: a non-linear map within an anchor budget splits its segments into longer pieces,
/// down to one a segment, and matches the plain map where the budget leaves room.
#[test]
+1
View File
@@ -316,6 +316,7 @@ fn content_hash(text: &crate::TextObject) -> Option<[u64; 2]> {
let inline_bounds = text.runs.iter().filter_map(|r| r.inline.as_ref()).map(|i| i.bounds.map(|b| [b.x0, b.y0, b.x1, b.y1].map(f64::to_bits)));
for h in &mut feed.0 {
h.write_u8(u8::from(text.first_para_continues));
h.write_u32(text.first_para_lead.map_or(u32::MAX, u32::from));
for b in inline_bounds.clone() {
match b {
None => h.write_u8(0),
+99 -6
View File
@@ -497,6 +497,48 @@ pub fn map_nonlinear(path: &PathData, max_piece: f64, f: impl Fn(Point) -> Point
/// where pieces of `max_piece` would make more, the pieces grow until they don't ([`fit_piece`]),
/// a coarser approximation of the image curve. Geometry effects map within their anchor budget.
pub fn map_nonlinear_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn(Point) -> Point) -> PathData {
map_pieces_within(path, max_piece, max, &f, |_, h| f(h))
}
/// [`map_nonlinear_within`] with each handle mapped along `f`'s derivative at its point
/// ([`mapped_handle`]) rather than as a point of its own: where `f` turns quickly (Twist), handles
/// mapped as points point different ways on the two sides of a join and the curve kinks there
/// (#7069); along the derivative, the pieces on both sides leave each join in one direction.
pub fn map_smooth_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn(Point) -> Point) -> PathData {
map_pieces_within(path, max_piece, max, &f, |p, h| mapped_handle(&f, p, h))
}
/// [`map_nonlinear_within`] with `handle(point, handle)` supplying each mapped handle position.
pub fn map_handles_within(
path: &PathData,
max_piece: f64,
max: usize,
f: impl Fn(Point) -> Point,
handle: impl Fn(Point, Point) -> Point,
) -> PathData {
map_pieces_within(path, max_piece, max, &f, handle)
}
/// Handle `h` of point `p` mapped through `f`: `f(p)` plus `f`'s derivative at `p` along `h - p`
/// (a central difference), so the image curve leaves `f(p)` the way `f` takes the curve.
fn mapped_handle(f: &impl Fn(Point) -> Point, p: Point, h: Point) -> Point {
let v = h - p;
let len = v.hypot();
// A retracted handle stays retracted, and a non-finite one has no direction to follow.
if len.is_nan() || len <= 0.0 || len.is_infinite() {
return f(p);
}
// A thousandth of the handle, or more where the coordinates are so large that so short a
// step would round away (#7069): the samples stay a billionth of the coordinates apart, and
// at most at the handle's own end.
let size = p.x.abs().max(p.y.abs()).max(1.0);
let step = (1e-3f64).max(size * 1e-9 / len).min(1.0);
let d = (f(p + v * step) - f(p - v * step)) / (2.0 * step);
f(p) + d
}
/// [`map_nonlinear_within`]'s pieces, with `handle(point, handle)` giving each mapped handle.
fn map_pieces_within(path: &PathData, max_piece: f64, max: usize, f: &impl Fn(Point) -> Point, handle: impl Fn(Point, Point) -> Point) -> PathData {
let mut max_piece = max_piece.max(1e-3);
// Each segment adds one anchor per piece past its first.
let room = max.saturating_sub(path.anchor_count());
@@ -516,20 +558,21 @@ pub fn map_nonlinear_within(path: &PathData, max_piece: f64, max: usize, f: impl
let mut pending_in: Option<Point> = None;
for i in 0..n {
let a = &sp.anchors[i];
let h_in = pending_in.take().unwrap_or_else(|| f(a.h_in));
res.push(Anchor { p: f(a.p), h_in, h_out: f(a.h_out), kind: a.kind });
let h_in = pending_in.take().unwrap_or_else(|| handle(a.p, a.h_in));
res.push(Anchor { p: f(a.p), h_in, h_out: handle(a.p, a.h_out), kind: a.kind });
if i < segs {
let c = seg_cubic(sp, i);
let k = pieces(poly_len(&c), max_piece, MAX_PIECES);
for j in 0..k {
let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64));
// Evaluating an unchanged curve can overflow even when its control points are finite.
let sub = if k == 1 { c } else { c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64)) };
if let Some(last) = res.last_mut() {
last.h_out = f(sub.p1);
last.h_out = handle(sub.p0, sub.p1);
}
if j + 1 < k {
res.push(Anchor { p: f(sub.p3), h_in: f(sub.p2), h_out: f(sub.p3), kind: Default::default() });
res.push(Anchor { p: f(sub.p3), h_in: handle(sub.p3, sub.p2), h_out: f(sub.p3), kind: Default::default() });
} else {
pending_in = Some(f(sub.p2));
pending_in = Some(handle(sub.p3, sub.p2));
}
}
}
@@ -582,3 +625,53 @@ pub(super) fn resample(poly: &[Point], m: usize) -> Vec<Point> {
}
out
}
#[cfg(test)]
mod handle_tests {
use super::*;
#[test]
fn an_unsplit_curve_keeps_its_finite_control_points() {
let start = Point::new(1e308, 0.0);
let end = Point::new(1.03e308, 0.0);
let path = PathData::new(vec![SubPath::new(
vec![Anchor::with_handles(start, start, Point::new(1.01e308, 1.0)), Anchor::with_handles(end, Point::new(1.02e308, 1.0), end)],
false,
)]);
assert_eq!(map_handles_within(&path, 1.0, 2, |p| p, |_, h| h), path);
}
#[test]
fn rounded_samples_preserve_a_smooth_interior_join() {
let center = Point::new(1e16, 0.0);
let path = PathData::new(vec![SubPath::new(
vec![
Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(-18.0, 0.0)),
Anchor::with_handles(
center,
center + vectorcraft_geom::kurbo::Vec2::new(-6.0, 0.0),
center + vectorcraft_geom::kurbo::Vec2::new(6.0, 0.0),
),
Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(18.0, 0.0)),
],
false,
)]);
let mapped = map_smooth_within(&path, f64::INFINITY, 3, |p| Point::new(p.x, p.y + (p.x - center.x).powi(2) * 0.1));
let join = &mapped.subpaths[0].anchors[1];
let incoming = join.p - join.h_in;
let outgoing = join.h_out - join.p;
assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}");
assert!(incoming.dot(outgoing) > 0.0);
}
#[test]
fn a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction() {
for x in [1e16, 1e16 + 2.0, -1e16] {
for offset in [-6.0, -2.0, 2.0, 6.0] {
let p = Point::new(x, 0.0);
let h = Point::new(x + offset, 0.0);
assert_eq!(mapped_handle(&|point| point, p, h), h);
}
}
}
}
+1
View File
@@ -271,6 +271,7 @@ fn node_bytes(n: &Node, other: Option<&Node>, counted: &mut HashSet<usize>) -> u
.as_deref()
.map_or(0, |m| ALLOC + size_of::<crate::color_mask::ColorMask>() + m.key.capacity() + m.from.capacity() + m.colors.capacity() * 3);
b += e.trace.as_ref().map_or(0, |t| ALLOC + size_of::<Value>() + json_bytes(t));
b += e.flare.as_ref().map_or(0, |f| ALLOC + size_of::<crate::flare::FlareSpec>() + json_bytes(&f.params));
b += e.intertwine.as_deref().map_or(0, |a| ALLOC + size_of::<PathData>() + path_bytes(a));
if e.intertwine_tiers.capacity() > 0 {
b += ALLOC + e.intertwine_tiers.capacity() * size_of::<PathData>() + e.intertwine_tiers.iter().map(path_bytes).sum::<usize>();
+90
View File
@@ -0,0 +1,90 @@
//! The nearest node of a kind at or above each of many objects, found along one index path per
//! object.
use std::sync::Arc;
use crate::id_index::Paths;
use crate::{Document, Node, NodeId};
/// Finds, for one object after another, the nearest node that passes a test: the object itself,
/// then its parent, and so on up to its layer. Made by [`Document::nearest_finder`].
///
/// Each node on the way is tested as [`Document::node`] gives its id, so the answer is the one that
/// `doc.ancestry(id)` read from the end, with `doc.node` for each id, gives. While the lookup cache
/// places the object and each id on its path where they are, a lookup reads that one path; an id
/// the cache does not place there (one that appears more than once, or a cache older than the
/// tree) is looked up with [`Document::node`].
pub struct NearestFinder<'a> {
doc: &'a Document,
cache: Option<Arc<Paths>>,
/// The cache entries from the top-level layer down to the object.
entries: Vec<u32>,
/// The nodes at those entries.
nodes: Vec<&'a Node>,
}
impl Document {
/// A [`NearestFinder`] for this document.
pub fn nearest_finder(&self) -> NearestFinder<'_> {
NearestFinder { doc: self, cache: self.index.get(), entries: vec![], nodes: vec![] }
}
}
impl<'a> NearestFinder<'a> {
/// The node nearest `id` (itself, then its parent, and so on up to its layer) for which `pred`
/// holds; `None` when `id` is not in the tree or no node on its path passes.
pub fn nearest(&mut self, id: NodeId, mut pred: impl FnMut(&Node) -> bool) -> Option<&'a Node> {
let doc = self.doc;
let ids: Vec<NodeId> = if self.cached_path(id) {
let cache = self.cache.as_deref()?;
// The depth of the first id from the object up that the cache does not place there.
let mut unplaced = None;
for (k, (&node, &e)) in self.nodes.iter().zip(&self.entries).enumerate().rev() {
if cache.entry(&node.id) != Some(Some(e)) {
unplaced = Some(k);
break;
}
if pred(node) {
return Some(node);
}
}
let k = unplaced?;
self.nodes[..=k].iter().map(|n| n.id).collect()
} else {
doc.ancestry(id).unwrap_or_default()
};
let found = ids.into_iter().rev().find_map(|a| doc.node(a).filter(|n| pred(n)));
// Those lookups may have built the cache again.
self.cache = doc.index.get();
found
}
/// Fill `entries` and `nodes` with the cached path to `id`; false when the cache has no path for
/// it or the path no longer leads to it.
fn cached_path(&mut self, id: NodeId) -> bool {
self.entries.clear();
self.nodes.clear();
let Some(cache) = self.cache.as_deref() else { return false };
let Some(Some(mut e)) = cache.entry(&id) else { return false };
loop {
let Some((parent, _)) = cache.place(e) else { return false };
self.entries.push(e);
if parent == u32::MAX {
break;
}
// A parent's entry is made before its children's, so the walk up ends.
if parent >= e {
return false;
}
e = parent;
}
self.entries.reverse();
let mut siblings: &'a [Arc<Node>] = &self.doc.layers;
for &e in &self.entries {
let Some(n) = cache.place(e).and_then(|(_, i)| siblings.get(i as usize)) else { return false };
self.nodes.push(&**n);
siblings = n.children().map_or(&[], |c| c.as_slice());
}
self.nodes.last().is_some_and(|n| n.id == id)
}
}
+4
View File
@@ -41,6 +41,9 @@ pub struct NodeExtras {
/// Dimension object: the live measurement it draws; its ordinary group children hold its
/// exportable appearance (Object › Dimensions, the Dimension tool).
pub dimension: Option<Box<crate::dimension::Dimension>>,
/// Flare object: the settings its group was drawn with (the Flare tool); its ordinary group
/// children hold its art.
pub flare: Option<Box<crate::flare::FlareSpec>>,
/// Object › Intertwine: as a member of an Intertwine group, the area (document coordinates,
/// filled non-zero) where this object is drawn over the group's other members.
pub intertwine: Option<Box<PathData>>,
@@ -100,6 +103,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
slice: None,
perspective: None,
dimension: None,
flare: None,
intertwine: None,
intertwine_tiers: Vec::new(),
live_paint_gaps: None,
+42
View File
@@ -179,6 +179,48 @@ impl LiveShape {
*xf = Affine::rotate_about((now - angle).to_radians(), centre) * *xf;
}
}
/// A line's length in the document, from its first end to its second. None for other shapes.
pub fn line_length(&self) -> Option<f64> {
let LiveShape::Line { a, b } = self else { return None };
Some((*b - *a).hypot())
}
/// A line's angle: the counterclockwise degrees in [0, 360) from the page's horizontal to the
/// direction from its first end to its second (the Rotate field's sense). 0 for a line whose
/// ends meet. None for other shapes.
pub fn line_angle(&self) -> Option<f64> {
let LiveShape::Line { a, b } = self else { return None };
if a == b {
return Some(0.0);
}
// No −0° or 360° from rounding: a line drawn left to right reads 0°.
let a = (-self.angle_deg()).rem_euclid(360.0);
Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 })
}
/// Make a line `len` long (0 or more), keeping its first end in place and its direction, or
/// pointing it to the right when its ends meet.
pub fn set_line_length(&mut self, len: f64) {
let LiveShape::Line { a, b } = self else { return };
if !len.is_finite() || len < 0.0 {
return;
}
let now = (*b - *a).hypot();
*b = if now > 0.0 { *a + (*b - *a) * (len / now) } else { Point::new(a.x + len, a.y) };
}
/// Turn a line about its midpoint to `angle` (degrees, as [`LiveShape::line_angle`]). A line
/// whose ends meet stays as it is.
pub fn set_line_angle(&mut self, angle: f64) {
let LiveShape::Line { a, b } = self else { return };
let half = (*b - *a).hypot() / 2.0;
if !angle.is_finite() || half <= 0.0 {
return;
}
let mid = a.midpoint(*b);
let t = angle.to_radians();
// The page's y axis points down, so a counterclockwise angle goes up the page.
let (dx, dy) = (half * t.cos(), -half * t.sin());
*a = Point::new(mid.x - dx, mid.y - dy);
*b = Point::new(mid.x + dx, mid.y + dy);
}
/// Make a polygon's sides equal (Make Sides Equal): drop the uneven scale and the shear from
/// `xf`, keeping its centre, angle, reflection and [`LiveShape::polygon_radius`].
pub fn make_sides_equal(&mut self) {
+75 -13
View File
@@ -90,6 +90,42 @@ impl Node {
matches!(self.kind, NodeKind::RulerGuide { .. } | NodeKind::Path { guide: true, .. })
}
/// This object without the paths made into guides among the members of its groups, layers,
/// Intertwine groups and compound paths, at any depth, for measuring the art around them while
/// Lock Guides or Hide Guides leaves them out (#8538). The clipping path of a clip group or
/// layer and the original shapes of a Shaper group stay, guides or not, so the object keeps
/// its structure. `None` when it holds no such guide.
pub fn without_guides(&self) -> Option<Node> {
let (NodeKind::Layer { children, .. }
| NodeKind::Group { children, .. }
| NodeKind::Intertwine { children }
| NodeKind::Compound { children, .. }) = &self.kind
else {
return None;
};
let keep = usize::from(self.clips() || self.extras().shaper.is_some());
let mut changed = false;
let mut out = Vec::with_capacity(children.len());
for (i, c) in children.iter().enumerate() {
if i >= keep && matches!(c.kind, NodeKind::Path { guide: true, .. }) {
changed = true;
} else if let Some(stripped) = c.without_guides() {
changed = true;
out.push(Arc::new(stripped));
} else {
out.push(c.clone());
}
}
if !changed {
return None;
}
let mut n = self.clone();
if let Some(c) = n.children_mut() {
*c = out;
}
Some(n)
}
/// A template layer (Layer Options → Template).
pub fn is_template(&self) -> bool {
matches!(self.kind, NodeKind::Layer { template: true, .. })
@@ -216,8 +252,10 @@ impl Node {
/// path give it ([`crate::hit::set_clip_region`]). An image's box takes in
/// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers
/// without a clipping mask and Intertwine groups take in their members' boxes, grown by their
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box
/// takes in where its spine can put its keys and steps.
/// own strokes. Symbol instances are measured as in [`Node::visual_bounds`], taking in the
/// shapes their art paints with the geometry effects of their own fill or stroke
/// ([`crate::hit::set_image_paint`]). A blend's box takes in where its spine can put its keys
/// and steps.
pub fn reach_bounds(&self) -> Option<Rect> {
self.reach(None)
}
@@ -254,14 +292,8 @@ impl Node {
.map(|b| b.inflate(o, o))
}
NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))),
// The frame and each shape the image's own fills and strokes paint, a stroke's grown by
// the farthest it can reach from its shape.
NodeKind::Image(_) => {
crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| {
let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
})
}
// The frame and each shape the image's own fills and strokes paint.
NodeKind::Image(_) => self.with_own_paint(self.geometric(symbols), symbols),
// Keys and steps placed on a spine, turned to it with Align to Path, can reach past the
// keys and the spine.
NodeKind::Blend { children, spec } => {
@@ -272,13 +304,15 @@ impl Node {
NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => {
vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c)))
}
// The live geometry effects of the clipping paths in the art can draw it past its box.
// The live geometry effects of the clipping paths in the art can draw it past its box,
// and the box takes in each shape the art paints with the geometry effects of the
// instance's own fill or stroke.
NodeKind::SymbolInstance { symbol, xf } => {
let Some((s, art, region)) = symbols.and_then(|s| {
let a = s.art(symbol)?;
Some((s, a, a.reshaped?))
}) else {
return self.visual(symbols);
return self.with_own_paint(self.visual(symbols), symbols);
};
let map = s.document().symbol_slice_map_of(symbol, art.geometric, *xf);
let placed = if moves_only(*xf) && map.is_none() {
@@ -294,12 +328,22 @@ impl Node {
map.map_or_else(|| xf.transform_rect_bbox(all), |m| m.placement_bounds(all)).inflate(grow, grow)
};
let o = self.appearance.outset();
vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o)))
self.with_own_paint(vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o))), symbols)
}
_ => self.visual(symbols),
}
}
/// `start` grown by each shape the node's own fills and strokes paint
/// ([`crate::hit::set_image_paint`]), a stroke's grown by the farthest it can reach from its
/// shape.
fn with_own_paint(&self, start: Option<Rect>, symbols: Option<&SymbolBoxes>) -> Option<Rect> {
crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(start, |acc, (bp, _, item)| {
let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 };
vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o)))
})
}
/// Geometric bounds (no stroke), recursively. Clip groups are bounded by their clip path. A
/// symbol instance is measured as its transform applied to the 20 × 20 square around the origin
/// that symbols made in the app keep their art in ([`Node::geometric_bounds_with`] measures
@@ -476,6 +520,12 @@ impl Node {
{
dimension.transform(a);
}
// So does a flare's center and end point.
if let Some(e) = self.extras_if_any()
&& let Some(flare) = &mut e.flare
{
flare.transform(a);
}
// The path the objects are attached to, before it is transformed.
let on_path_before = self.on_path_data().cloned();
if !self.is_layer() {
@@ -608,6 +658,18 @@ impl Node {
}
}
/// [`Self::walk`] that ends at the first node for which `f` returns [`std::ops::ControlFlow::Break`]: no
/// node after it is visited, and the break is returned.
pub fn try_walk<'a, B>(&'a self, f: &mut impl FnMut(&'a Node) -> std::ops::ControlFlow<B>) -> std::ops::ControlFlow<B> {
f(self)?;
if let Some(ch) = self.children() {
for c in ch {
c.try_walk(f)?;
}
}
std::ops::ControlFlow::Continue(())
}
/// Count of nodes in this subtree, ruler guides left out.
pub fn count(&self) -> usize {
let mut n = 0;
+28
View File
@@ -805,3 +805,31 @@ fn mapping_ruler_guide_positions_looks_at_each_child_of_nested_layers_once() {
assert!(Arc::ptr_eq(&group.children().unwrap()[0], &twice));
assert_eq!(calls, 0);
}
/// `try_walk` visits in `walk`'s order and visits nothing after the node that breaks it: not its
/// children, its later siblings or its ancestors' later siblings.
#[test]
fn try_walk_ends_at_the_break() {
use std::ops::ControlFlow;
let leaf = |id| Arc::new(Node::group(NodeId(id), vec![]));
let inner = Node::group(NodeId(2), vec![leaf(3), leaf(4), leaf(5)]);
let root = Node::group(NodeId(1), vec![Arc::new(inner), leaf(6), leaf(7)]);
let mut all = vec![];
root.walk(&mut |n| all.push(n.id));
let mut seen = vec![];
assert_eq!(
root.try_walk(&mut |n| {
seen.push(n.id);
ControlFlow::<()>::Continue(())
}),
ControlFlow::Continue(())
);
assert_eq!(seen, all, "without a break it visits what walk visits, in the same order");
seen.clear();
let flow = root.try_walk(&mut |n| {
seen.push(n.id);
if n.id == NodeId(3) { ControlFlow::Break(n.id) } else { ControlFlow::Continue(()) }
});
assert_eq!(flow, ControlFlow::Break(NodeId(3)));
assert_eq!(seen, [NodeId(1), NodeId(2), NodeId(3)]);
}
+5
View File
@@ -45,6 +45,7 @@ impl Serialize for Node {
is_default(&self.bbox_angle),
e.perspective.is_none(),
e.dimension.is_none(),
e.flare.is_none(),
e.intertwine.is_none(),
e.intertwine_tiers.is_empty(),
e.live_paint_gaps.is_none(),
@@ -91,6 +92,7 @@ impl Serialize for Node {
field!("bbox_angle", &self.bbox_angle);
field!("perspective", &e.perspective);
field!("dimension", &e.dimension);
field!("flare", &e.flare);
field!("intertwine", &e.intertwine);
field!("intertwine_tiers", &e.intertwine_tiers);
field!("live_paint_gaps", &e.live_paint_gaps);
@@ -228,6 +230,8 @@ pub(super) struct NodeWire {
#[serde(default)]
dimension: Option<Box<crate::dimension::Dimension>>,
#[serde(default)]
flare: Option<Box<crate::flare::FlareSpec>>,
#[serde(default)]
intertwine: Option<Box<PathData>>,
#[serde(default, deserialize_with = "counted_list")]
intertwine_tiers: Vec<PathData>,
@@ -271,6 +275,7 @@ impl From<NodeWire> for Node {
slice: w.slice,
perspective: w.perspective,
dimension: w.dimension,
flare: w.flare,
intertwine: w.intertwine,
intertwine_tiers: w.intertwine_tiers,
live_paint_gaps: w.live_paint_gaps,
+119 -7
View File
@@ -4,7 +4,7 @@
use std::sync::Arc;
use vectorcraft_color::{BlendMode, Color, Paint};
use vectorcraft_color::{BlendMode, Color, GradientKind, Paint};
use crate::{Document, Node, NodeId, NodeKind};
@@ -46,14 +46,21 @@ impl Default for OverprintBlack {
}
impl OverprintBlack {
/// Whether `p` is black: a solid colour (linked to one of the spot swatches `spots` only with
/// [`Self::spot`]), or a gradient whose every stop is.
/// Whether `p` is black: a solid color (linked to one of the spot swatches `spots` only with
/// [`Self::spot`]), a gradient whose every stop is, or a freeform gradient with color points
/// whose every point is (it draws from its points, not its stops).
fn black(&self, p: &Paint, spots: &[String]) -> bool {
let ink = |color: &Color, swatch: &Option<String>| {
(self.spot || !swatch.as_ref().is_some_and(|s| spots.contains(s))) && is_black_ink(color, self.min_k, self.rich)
};
match p {
Paint::Solid { color, swatch, .. } => {
(self.spot || !swatch.as_ref().is_some_and(|s| spots.contains(s))) && is_black_ink(color, self.min_k, self.rich)
}
Paint::Gradient(g) => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| is_black_ink(&s.color, self.min_k, self.rich)),
Paint::Solid { color, swatch, .. } => ink(color, swatch),
// Only a freeform gradient draws its points; another kind draws its stops whatever it holds.
Paint::Gradient(g) => match g.freeform.as_ref().filter(|f| g.gradient.kind == GradientKind::Freeform && !f.points.is_empty()) {
Some(f) => f.points.iter().all(|pt| is_black_ink(&pt.color, self.min_k, self.rich)),
// Without points of its own a freeform gradient places them from its stops.
None => !g.gradient.stops.is_empty() && g.gradient.stops.iter().all(|s| ink(&s.color, &s.swatch)),
},
_ => false,
}
}
@@ -85,6 +92,52 @@ impl OverprintBlack {
}
changed
}
/// [`Self::apply`] to every node of `a`'s subtree, copying only the nodes on the way to those
/// that change. Returns whether anything changed.
pub fn apply_deep(&self, a: &mut Arc<Node>, spots: &[String]) -> bool {
match self.marked(a, spots) {
Some(n) => {
*a = n;
true
}
None => false,
}
}
/// `n`'s subtree with [`Self::apply`] done to each node, when that changes anything (`None`
/// otherwise). Each node is visited once, and only the nodes on the way to a change are copied.
fn marked(&self, n: &Arc<Node>, spots: &[String]) -> Option<Arc<Node>> {
let members: Vec<(usize, Arc<Node>)> =
n.children().into_iter().flatten().enumerate().filter_map(|(i, c)| Some((i, self.marked(c, spots)?))).collect();
if members.is_empty() && !self.changes(n, spots) {
return None;
}
let mut copy = Arc::clone(n);
let m = Arc::make_mut(&mut copy);
self.apply(m, spots);
if let Some(children) = m.children_mut() {
for (i, c) in members {
if let Some(slot) = children.get_mut(i) {
*slot = c;
}
}
}
Some(copy)
}
/// Whether [`Self::apply`] changes a fill, stroke or character of `n` itself.
fn changes(&self, n: &Node, spots: &[String]) -> bool {
let on = !self.remove;
let item = |it: &crate::AppearanceItem| {
it.overprint() != on && (if it.is_fill() { self.fill } else { self.stroke }) && self.black(it.paint(), spots)
};
let run = |r: &crate::TextRun| {
(self.fill && r.style.overprint_fill != on && self.black(&r.style.fill, spots))
|| (self.stroke && r.style.overprint_stroke != on && self.black(&r.style.stroke, spots))
};
n.appearance.items.iter().any(item) || matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(run))
}
}
impl Node {
@@ -236,6 +289,65 @@ mod tests {
assert!(tx.runs[0].style.overprint_fill);
}
#[test]
fn a_freeform_gradient_is_black_when_every_point_is() {
use vectorcraft_color::freeform::{Freeform, FreeformPoint};
let k = Color::cmyk(0.0, 0.0, 0.0, 1.0);
let mut g = vectorcraft_color::GradientPaint::new(vectorcraft_color::Gradient { kind: GradientKind::Freeform, ..Default::default() });
for s in &mut g.gradient.stops {
s.color = k;
}
let points = vec![FreeformPoint::new(Point::ZERO, k), FreeformPoint::new(Point::new(10.0, 0.0), Color::cmyk(1.0, 0.0, 0.0, 0.0))];
g.freeform = Some(Freeform { points, ..Default::default() });
let fill = |g: &vectorcraft_color::GradientPaint| Appearance::basic(Paint::Gradient(Box::new(g.clone())), Paint::None, 0.0);
let mut n = Node::path(NodeId(1), Default::default(), fill(&g));
assert!(!OverprintBlack::default().apply(&mut n, &[]), "a cyan point is drawn, whatever the stops");
// Another kind of gradient draws its black stops, not the points it still holds.
let mut linear = g.clone();
linear.gradient.kind = GradientKind::Linear;
let mut n = Node::path(NodeId(1), Default::default(), fill(&linear));
assert!(OverprintBlack::default().apply(&mut n, &[]), "a linear gradient is judged by its stops");
if let Some(f) = &mut g.freeform {
f.points[1].color = Color::gray(1.0);
}
let mut n = Node::path(NodeId(1), Default::default(), fill(&g));
assert!(OverprintBlack::default().apply(&mut n, &[]), "every point black");
g.freeform = Some(Freeform::default());
let mut n = Node::path(NodeId(1), Default::default(), fill(&g));
assert!(OverprintBlack::default().apply(&mut n, &[]), "no points: placed from the black stops");
}
#[test]
fn a_gradient_with_a_spot_linked_stop_is_black_only_with_spot() {
let mut g = vectorcraft_color::GradientPaint::new(Default::default());
for s in &mut g.gradient.stops {
s.color = Color::cmyk(0.0, 0.0, 0.0, 1.0);
}
g.gradient.stops[0].swatch = Some("Ink".into());
let k = Paint::Gradient(Box::new(g));
let mut n = Node::path(NodeId(1), Default::default(), Appearance::basic(k, Paint::None, 0.0));
let spots = ["Ink".to_string()];
assert!(!OverprintBlack::default().apply(&mut n, &spots), "a stop linked to a spot swatch is not process black");
assert!(OverprintBlack { spot: true, ..Default::default() }.apply(&mut n, &spots), "Include Spot Blacks takes it");
}
#[test]
fn apply_deep_copies_only_the_nodes_that_change() {
let k = cmyk(0.0, 0.0, 0.0, 1.0);
let black = Arc::new(Node::path(NodeId(2), Default::default(), Appearance::basic(k, Paint::None, 0.0)));
let cyan = Arc::new(Node::path(NodeId(3), Default::default(), Appearance::basic(cmyk(1.0, 0.0, 0.0, 0.0), Paint::None, 0.0)));
let mut group = Arc::new(Node::group(NodeId(1), vec![black.clone(), cyan.clone()]));
let before = group.clone();
assert!(OverprintBlack::default().apply_deep(&mut group, &[]));
let members = group.children().unwrap();
assert!(members[0].appearance.fill().unwrap().overprint && !black.has_overprint(), "the copy is marked, not the original");
assert!(Arc::ptr_eq(&members[1], &cyan), "the cyan member is shared, not copied");
assert!(!before.has_overprint());
let marked = group.clone();
assert!(!OverprintBlack::default().apply_deep(&mut group, &[]), "nothing left to change");
assert!(Arc::ptr_eq(&group, &marked), "and nothing is copied");
}
#[test]
fn legacy_overprint_black_list_migrates() {
let mut d = Document::new(100.0, 100.0);
+126 -23
View File
@@ -20,15 +20,41 @@ pub type PixelPick<'a> = (Option<[f64; 4]>, usize, &'a dyn Fn(f64, f64) -> bool)
/// the header first: the decoder's limit is on the file's samples, and a gray image is a quarter
/// of what it becomes here (#1717).
fn rgba_within(bytes: &[u8], max: u64) -> Option<image::RgbaImage> {
let (w, h) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()?;
if u64::from(w) * u64::from(h) > max / 4 {
Some(crate::decode::decode_within(bytes, max).ok()??.0.into_rgba8())
}
/// An image file's stored size in pixels, read from its header by craft-image-codecs without
/// decoding any pixels: PNG's IHDR, a JPEG's frame, a TIFF's first full-resolution page, a
/// still or animated WebP's canvas, BMP's header ([`craft_image_codecs::probe_allocation_size`],
/// with no size limit), and a GIF's logical screen and the other formats' headers
/// ([`craft_image_codecs::probe_size`]). Not turned by an EXIF orientation. `None` when no header
/// gives a size.
pub fn header_size(bytes: &[u8]) -> Option<(u32, u32)> {
if craft_image_codecs::detect(bytes) == Some(craft_image_codecs::Format::Gif) {
// A GIF frame may be larger than the logical screen the image crate gave as its size.
return craft_image_codecs::probe_size(bytes).ok();
}
craft_image_codecs::probe_allocation_size(bytes)
.ok()
.or_else(|| craft_image_codecs::probe_size(bytes).ok())
// A BMP whose pixel data does not match its header (a truncated file, or a header that
// declares more pixels than the file holds) is refused by the image crate decoder the
// probes use. The BITMAPINFOHEADER still names the size, which Place, Paste and Open
// need so they can say the image is too large to draw instead of that its size can't
// be read.
.or_else(|| bmp_header_size(bytes))
}
/// Width and height from a BMP file's BITMAPINFOHEADER, without opening it as a decoder would.
/// Height may be negative (top-down storage); the stored magnitude is the size.
fn bmp_header_size(bytes: &[u8]) -> Option<(u32, u32)> {
if bytes.get(..2) != Some(b"BM") {
return None;
}
let mut reader = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?;
let mut limits = image::Limits::default();
limits.max_alloc = Some(max);
reader.limits(limits);
Some(reader.decode().ok()?.into_rgba8())
let dim = |at: usize| -> Option<i32> { Some(i32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?)) };
let width = u32::try_from(dim(18)?).ok().filter(|&n| n > 0)?;
let height = dim(22)?.unsigned_abs();
(height > 0).then_some((width, height))
}
impl ImageBlob {
@@ -385,30 +411,43 @@ mod tests {
assert!(ImageBlob::png(b"not a png".to_vec()).sample_pixels(&[(None, 100, &any)]).is_none());
}
/// A GIF whose `w` × `h` screen holds one opaque red pixel at the top left. The file holds no
/// other pixels, and the decoder makes them transparent.
fn gif_with_one_red_pixel(w: u16, h: u16) -> Vec<u8> {
let mut gif = b"GIF89a".to_vec();
gif.extend_from_slice(&w.to_le_bytes());
gif.extend_from_slice(&h.to_le_bytes());
// Flags for a global color table of two colors, the background and aspect bytes, then the
// table: red and black.
gif.extend_from_slice(&[0x80, 0, 0, 255, 0, 0, 0, 0, 0]);
// A 1 × 1 image at (0, 0), its LZW data (clear, color 0, end), and the end of the file.
gif.extend_from_slice(&[0x2C, 0, 0, 0, 0, 1, 0, 1, 0, 0, 2, 2, 0x44, 0x01, 0, 0x3B]);
gif
/// An RGBA PNG of `w` × `h` pixels with one opaque red pixel at the top left, the rest
/// transparent. Written row by row so the 11,586² allowance image is not held decoded
/// while it is encoded.
fn png_with_one_red_pixel(w: u32, h: u32) -> Vec<u8> {
use std::io::Write;
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast());
let mut row = vec![0u8; 1 + w as usize * 4];
row[1..5].copy_from_slice(&[255, 0, 0, 255]);
z.write_all(&row).unwrap();
row[1..5].fill(0);
for _ in 1..h {
z.write_all(&row).unwrap();
}
let idat = [&b"IDAT"[..], &z.finish().unwrap()].concat();
let ihdr = [&b"IHDR"[..], &w.to_be_bytes(), &h.to_be_bytes(), &[8, 6, 0, 0, 0]].concat();
let mut out = b"\x89PNG\r\n\x1a\n".to_vec();
for chunk in [&ihdr[..], &idat[..], b"IEND"] {
out.extend((chunk.len() as u32 - 4).to_be_bytes());
out.extend(chunk);
let mut crc = flate2::Crc::new();
crc.update(chunk);
out.extend(crc.sum().to_be_bytes());
}
out
}
/// The pixels are decoded within the allowance, not within the decoder's own 512 MB: an RGBA
/// image of 11,586 × 11,586 pixels (536,941,584 bytes) is recolored and sampled.
/// image of 11,586 × 11,586 pixels (536,941,584 bytes) is recolored and sampled. A PNG, not a
/// sparse GIF: craft-image-codecs refuses a GIF whose unbacked logical screen is past 256 MiB.
#[test]
fn pixels_past_the_decoders_own_limit_are_decoded_within_the_allowance() {
let (w, h) = (11_586, 11_586);
let rgba = u64::from(w) * u64::from(h) * 4;
assert!(rgba > 512 << 20);
let gif = gif_with_one_red_pixel(w, h);
assert!(rgba_within(&gif, rgba - 1).is_none(), "past the allowance");
let b = ImageBlob::new("image/gif", gif);
let png = png_with_one_red_pixel(w, h);
assert!(rgba_within(&png, rgba - 1).is_none(), "past the allowance");
let b = ImageBlob::png(png);
assert!(b.map_rgb(|[r, g, bl]| [bl, g, r]).is_some(), "red becomes blue");
assert_eq!(b.sample(0.5, 0.5, 1), Some([255, 0, 0, 255]));
assert_eq!(b.sample(f64::from(w) - 0.5, f64::from(h) - 0.5, 1), None, "transparent");
@@ -556,4 +595,68 @@ mod tests {
assert_eq!(la8.coverage(), Some((4, 1, vec![255, 0, 204, 128])));
assert_eq!(ImageBlob::png(vec![1, 2, 3]).coverage(), None);
}
/// Embedded-image pixels through craft-image-codecs (#778) are those the image crate decoded:
/// the same layout and samples for PNG, GIF, WebP, TIFF and BMP at each depth the image
/// crate writes, and JPEG samples within two steps.
#[test]
fn decoded_pixels_are_those_the_image_crate_read() {
use image::{DynamicImage as D, ImageFormat as F};
let rgba =
image::RgbaImage::from_fn(9, 5, |x, y| image::Rgba([(x * 29) as u8, (y * 47) as u8, ((x + 2 * y) * 9) as u8, 255 - (x * y * 6) as u8]));
let deep = image::ImageBuffer::<image::Rgba<u16>, _>::from_fn(9, 5, |x, y| {
image::Rgba([(x * 7_001) as u16, (y * 12_007) as u16, 5, 65_535 - (x * y) as u16])
});
let images = [
D::ImageRgba8(rgba.clone()),
D::ImageRgb8(D::ImageRgba8(rgba.clone()).to_rgb8()),
D::ImageLuma8(D::ImageRgba8(rgba.clone()).to_luma8()),
D::ImageLumaA8(D::ImageRgba8(rgba).to_luma_alpha8()),
D::ImageRgba16(deep.clone()),
D::ImageLuma16(D::ImageRgba16(deep).to_luma16()),
];
let mut checked = 0;
for img in &images {
for f in [F::Png, F::Gif, F::WebP, F::Tiff, F::Bmp, F::Jpeg] {
let mut bytes = Vec::new();
if img.write_to(&mut Cursor::new(&mut bytes), f).is_err() {
continue;
}
let what = format!("{f:?} {:?}", img.color());
let want = image::load_from_memory_with_format(&bytes, f).unwrap();
let (got, _) = crate::decode::decode_within(&bytes, MAX_RASTER_ALLOC)
.unwrap_or_else(|e| panic!("{what}: {e}"))
.unwrap_or_else(|| panic!("{what}: past the allowance"));
let tolerance = if f == F::Jpeg { 2 * 257 } else { 0 };
if f != F::Jpeg {
assert_eq!(got.color(), want.color(), "{what}");
}
let worst = got.to_rgba16().as_raw().iter().zip(want.to_rgba16().as_raw()).map(|(a, b)| a.abs_diff(*b)).max();
assert!(worst.is_some_and(|w| w <= tolerance), "{what}: {worst:?}");
// Link previews and the checked-image path read the same pixels.
let handed = ImageBlob::new(format!("image/{f:?}").to_ascii_lowercase(), bytes.clone())
.checked_with_pixels(false)
.unwrap_or_else(|| panic!("{what}: checked"))
.1
.unwrap_or_else(|| panic!("{what}: checked past the allowance"));
assert_eq!(handed.color(), got.color(), "{what} checked");
assert_eq!(handed.as_bytes(), got.as_bytes(), "{what} checked");
checked += 1;
}
}
assert!(checked >= 20, "{checked}");
}
/// A BMP header that declares 30,000 × 30,000 pixels, with only one pixel of data, still
/// reports that size: Paste and Place can then say the image is too large to draw.
#[test]
fn a_truncated_bmp_header_still_gives_its_declared_size() {
let mut bmp = vec![];
image::RgbImage::from_pixel(1, 1, image::Rgb([200, 40, 40])).write_to(&mut Cursor::new(&mut bmp), image::ImageFormat::Bmp).unwrap();
bmp[18..22].copy_from_slice(&30_000i32.to_le_bytes());
bmp[22..26].copy_from_slice(&30_000i32.to_le_bytes());
assert_eq!(header_size(&bmp), Some((30_000, 30_000)));
let (w, h, _) = crate::decode::decoded_layout(&bmp, craft_image_codecs::Format::Bmp).expect("layout from the header");
assert_eq!((w, h), (30_000, 30_000));
}
}
+7 -7
View File
@@ -1,5 +1,5 @@
//! Placed documents: another VectorCraft file, or a page of a PDF or `.ai` file, placed linked
//! ([`PlacedDocument`]).
//! Placed documents: another VectorCraft file, a page of a PDF or `.ai` file, or an EPS file,
//! placed linked ([`PlacedDocument`]).
//!
//! The object keeps the link to the file and the file's bytes, stored like image data in
//! [`Document::images`] (with a small preview a save writes instead, as for linked images), so the
@@ -7,9 +7,9 @@
//! joins the object tree, so editing can't reach it: it is locked by design. Drawing and exporting
//! expand it like a live object ([`crate::live::expanded`]).
//!
//! The file is read by the engine's loader (native documents, PDF and `.ai` pages), which lives
//! above this crate and registers itself ([`set_loader`]); the art read is kept in a small cache
//! by content. Before exporting,
//! The file is read by the engine's loader (native documents, PDF and `.ai` pages, EPS files),
//! which lives above this crate and registers itself ([`set_loader`]); the art read is kept in a
//! small cache by content. Before exporting,
//! every exporter calls [`Document::with_placed_art`], which adds the resources the art uses
//! (images, symbols, patterns) under names of their own ([`RESOURCE_PREFIX`]) to a temporary copy
//! of the document, so they never meet the user's or show in panels. Placed documents inside a
@@ -27,8 +27,8 @@ use vectorcraft_color::Paint;
use crate::{AppearanceItem, Document, ImageBlob, ImageObject, LinkInfo, Node, NodeKind, PatternDef, PlacementOptions, Symbol};
/// A placed document: an artboard of another VectorCraft file, or a page of a PDF or `.ai` file,
/// shown as one locked object.
/// A placed document: an artboard of another VectorCraft file, a page of a PDF or `.ai` file, or
/// an EPS file's art, shown as one locked object.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PlacedDocument {
/// The file (its `page` is the artboard or page shown, 1-based).
+65 -18
View File
@@ -50,10 +50,10 @@ pub struct Selection {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_guide: Option<NodeId>,
/// The key anchor for Align: one of two or more anchor points selected with Direct Selection,
/// the last one a Shift-click added (path, anchor in [`Self::anchors`]). Align and Distribute
/// move the other selected points relative to it, and it stays in place. Never set with `key`
/// or `key_guide`; [`Self::prune`] clears it when the point is no longer a selected anchor, or
/// fewer than two points are selected.
/// designated by clicking an already-selected anchor point without modifiers (path, anchor in
/// [`Self::anchors`]). Align and Distribute move the other selected points relative to it, and
/// it stays in place. Never set with `key` or `key_guide`; [`Self::prune`] clears it when the
/// point is no longer a selected anchor, or fewer than two points are selected.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_anchor: Option<(NodeId, AnchorRef)>,
/// The new art on a locked artboard that this selection keeps editable
@@ -183,23 +183,69 @@ impl Selection {
self.key_anchor = None;
}
}
/// [`Self::add`] for each of `ids` in order, going through the selected objects once.
pub fn add_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
self.each(ids, false);
}
/// [`Self::toggle`] for each of `ids` in order, going through the selected objects once. An id
/// listed twice is removed and then added again at the end.
pub fn toggle_all(&mut self, ids: impl IntoIterator<Item = NodeId>) {
self.each(ids, true);
}
/// [`Self::add_all`], or [`Self::toggle_all`] when `toggle` is set. Each selected object slot
/// carries the number of the activation that made it; an id's slots are kept only when they
/// carry its current activation, so a removal drops every slot of the id at once.
fn each(&mut self, ids: impl IntoIterator<Item = NodeId>, toggle: bool) {
use std::collections::hash_map::{Entry, HashMap};
let mut ids = ids.into_iter().peekable();
if ids.peek().is_none() {
return;
}
self.target = None;
self.slices.clear();
self.symbol_part = None;
self.on_path_member = None;
let mut live: HashMap<NodeId, usize> = self.objects.iter().map(|id| (*id, 0)).collect();
let mut added: Vec<(NodeId, usize)> = Vec::new();
let mut removed = false;
for id in ids {
match live.entry(id) {
Entry::Vacant(e) => {
let activation = added.len() + 1;
e.insert(activation);
added.push((id, activation));
}
Entry::Occupied(e) if toggle => {
e.remove();
removed = true;
self.anchors.remove(&id);
self.segments.remove(&id);
if self.key == Some(id) {
self.key = None;
}
if self.key_anchor.is_some_and(|(k, _)| k == id) {
self.key_anchor = None;
}
}
Entry::Occupied(_) => {}
}
}
if removed {
self.objects.retain(|id| live.get(id) == Some(&0));
}
self.objects.extend(added.into_iter().filter(|(id, n)| live.get(id) == Some(n)).map(|(id, _)| id));
}
/// Select slices `ids` (see [`Selection::slices`]) and nothing else.
pub fn set_slices(&mut self, ids: impl IntoIterator<Item = NodeId>) {
self.clear();
for id in ids {
if !self.slices.contains(&id) {
self.slices.push(id);
}
}
let mut seen = HashSet::new();
self.slices.extend(ids.into_iter().filter(|id| seen.insert(*id)));
}
/// Select ruler guides `ids` (see [`Selection::guides`]) and nothing else.
pub fn set_guides(&mut self, ids: impl IntoIterator<Item = NodeId>) {
self.clear();
for i in ids {
if !self.guides.contains(&i) {
self.guides.push(i);
}
}
let mut seen = HashSet::new();
self.guides.extend(ids.into_iter().filter(|id| seen.insert(*id)));
}
/// Add ruler guide `i` to the selection, or take it out, keeping the selected objects (a
/// Shift-click on a guide).
@@ -311,7 +357,7 @@ impl Selection {
let anchor_kept = self.key_anchor.is_some_and(|(id, (si, ai))| {
self.objects.contains(&id)
&& !self.segments.contains_key(&id)
&& self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai)))
&& (self.anchors.get(&id).is_some_and(|set| set.contains(&(si, ai))) || !self.anchors.contains_key(&id))
&& found
.get(&id)
.and_then(|p| doc.node_at(p))
@@ -426,10 +472,11 @@ impl Selection {
};
let locks = doc.locked_artboards();
ids.retain(|i| !locks.holds_id(*i));
if ids.iter().all(|i| self.contains(*i)) {
ids.iter().for_each(|i| self.remove(*i));
let selected: HashSet<NodeId> = self.objects.iter().copied().collect();
if ids.iter().all(|i| selected.contains(i)) {
self.remove_all(ids);
} else {
ids.into_iter().for_each(|i| self.add(i));
self.add_all(ids);
}
self.target = None;
}
+168
View File
@@ -45,6 +45,174 @@ fn remove_all_does_what_removing_each_does() {
assert_eq!(none, s);
}
/// A selection with every field set: objects 1 to 6 with 3 listed twice, anchors, segments, a key,
/// a key anchor, a target, slices, guides, a key guide, new art, a symbol part and an on-path member.
fn seeded() -> Selection {
let mut s = Selection { objects: [1, 2, 3, 4, 5, 3, 6].map(NodeId).to_vec(), ..Selection::default() };
for i in [2, 3, 4, 5] {
s.anchors.insert(NodeId(i), BTreeSet::from([(0, 1)]));
s.segments.insert(NodeId(i), BTreeSet::from([(0, 0)]));
}
s.key = Some(NodeId(4));
s.key_anchor = Some((NodeId(5), (0, 1)));
s.target = Some(NodeId(3));
s.slices = vec![NodeId(9)];
s.guides = vec![NodeId(10)];
s.key_guide = Some(NodeId(10));
s.new_art = Arc::new(HashSet::from([NodeId(2)]));
s.symbol_part = Some(SymbolPart { instance: NodeId(1), path: vec![0] });
s.on_path_member = Some(NodeId(11));
s
}
/// Id lists with repeats, ids not selected, removals followed by additions, and the empty list.
fn id_streams() -> Vec<Vec<NodeId>> {
let mut streams: Vec<Vec<NodeId>> = [
vec![],
vec![4],
vec![7],
vec![3],
vec![4, 1, 4, 7],
vec![7, 8, 7, 7, 3, 3, 5],
vec![1, 2, 3, 4, 5, 6],
vec![6, 5, 4, 3, 2, 1, 1, 2, 3],
vec![8, 2, 8, 2, 9, 9, 9],
]
.into_iter()
.map(|ids| ids.into_iter().map(NodeId).collect())
.collect();
// Deterministic pseudo-random lists over ids 1 to 12, half of them selected to start with.
let mut x: u64 = 0x9e37_79b9_7f4a_7c15;
for len in [5, 17, 40, 120] {
let ids = (0..len)
.map(|_| {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
NodeId(x % 12 + 1)
})
.collect();
streams.push(ids);
}
streams
}
#[test]
fn add_all_does_what_adding_each_does() {
for ids in id_streams() {
let mut one_by_one = seeded();
for id in &ids {
one_by_one.add(*id);
}
let mut all = seeded();
all.add_all(ids.iter().copied());
assert_eq!(all, one_by_one, "add_all({ids:?})");
}
}
#[test]
fn toggle_all_does_what_toggling_each_does() {
for ids in id_streams() {
let mut one_by_one = seeded();
for id in &ids {
one_by_one.toggle(*id);
}
let mut all = seeded();
all.toggle_all(ids.iter().copied());
assert_eq!(all, one_by_one, "toggle_all({ids:?})");
}
// An id toggled twice is selected again, at the end, without the anchors it had.
let mut s = seeded();
s.toggle_all([NodeId(2), NodeId(2)]);
assert_eq!(s.objects, [1, 3, 4, 5, 3, 6, 2].map(NodeId));
assert!(!s.anchors.contains_key(&NodeId(2)) && !s.segments.contains_key(&NodeId(2)));
// A removed key and key anchor stay cleared.
let mut s = seeded();
s.toggle_all([NodeId(4), NodeId(5), NodeId(4), NodeId(5)]);
assert_eq!((s.key, s.key_anchor), (None, None));
}
#[test]
fn set_slices_and_set_guides_keep_the_first_of_each_id() {
let mut s = seeded();
s.set_slices([3, 1, 3, 2, 1].map(NodeId));
assert_eq!(s.slices, [3, 1, 2].map(NodeId));
assert!(s.objects.is_empty() && s.guides.is_empty());
s.set_guides([5, 5, 4, 6, 4].map(NodeId));
assert_eq!(s.guides, [5, 4, 6].map(NodeId));
assert!(s.slices.is_empty());
}
/// Shift-clicking a target circle does what removing or adding each of its art one by one does,
/// for a layer with art, an empty layer and an object.
#[test]
fn toggle_target_does_what_toggling_its_art_one_by_one_does() {
let rect = || vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
let mut d = Document::new(100.0, 100.0);
let l = d.layers[0].id;
let art: Vec<NodeId> = (0..4).map(|_| d.alloc_id()).collect();
for id in &art {
d.insert(Some(l), usize::MAX, Node::path(*id, rect(), crate::Appearance::default_art())).unwrap();
}
let empty = d.alloc_id();
d.insert(None, usize::MAX, Node::layer(empty, "Empty", crate::LayerColor::Preset(2))).unwrap();
let one_by_one = |s: &Selection, id: NodeId| {
let mut s = s.clone();
let ids = match d.node(id) {
Some(n) if n.is_layer() => n.layer_art(true),
_ => vec![id],
};
if ids.iter().all(|i| s.contains(*i)) {
ids.iter().for_each(|i| s.remove(*i));
} else {
ids.into_iter().for_each(|i| s.add(i));
}
s.target = None;
s
};
let mut starts = vec![Selection::default()];
for objects in [vec![art[1]], vec![art[3], art[0], art[1], art[2]], vec![art[2], art[2], NodeId(99)]] {
let mut s = seeded();
s.objects = objects;
s.key = s.objects.first().copied();
s.anchors.insert(art[1], BTreeSet::from([(0, 0)]));
starts.push(s);
}
for start in &starts {
for id in [l, empty, art[2], NodeId(99)] {
let mut s = start.clone();
s.toggle_target(&d, id);
assert_eq!(s, one_by_one(start, id), "toggle_target({id:?}) on {:?}", start.objects);
}
}
}
#[test]
fn remove_all_does_what_removing_each_does_to_a_key_anchor_and_symbol_part() {
for kept in [false, true] {
let mut s = Selection::default();
for i in 1..=4 {
s.add(NodeId(i));
}
s.anchors.insert(NodeId(2), BTreeSet::from([(0, 0), (0, 1)]));
s.anchors.insert(NodeId(3), BTreeSet::from([(0, 2)]));
s.key_anchor = Some((NodeId(2), (0, 0)));
s.symbol_part = Some(SymbolPart { instance: NodeId(1), path: vec![0] });
s.guides = vec![NodeId(10)];
s.key_guide = Some(NodeId(10));
let ids = if kept { [NodeId(3), NodeId(8), NodeId(3)] } else { [NodeId(2), NodeId(8), NodeId(2)] };
let mut one_by_one = s.clone();
for id in ids {
one_by_one.remove(id);
}
let mut all = s.clone();
all.remove_all(ids);
assert_eq!(all, one_by_one);
assert_eq!(all.key_anchor.is_some(), kept);
assert_eq!((all.symbol_part.clone(), all.guides.clone(), all.key_guide), (None, vec![NodeId(10)], Some(NodeId(10))));
}
}
#[test]
fn guides_are_selected_on_their_own() {
let mut s = Selection::default();
+34
View File
@@ -206,6 +206,13 @@ pub const LANGUAGES: &[(&str, &str, Quotes)] = &[
("Assamese", "as", Quotes::ENGLISH),
("Sanskrit", "sa", Quotes::ENGLISH),
("Urdu", "ur", Quotes::ENGLISH),
// “…” outside, ‘…’ inside: CLDR gives these no delimiters of their own (`↑↑↑`, inherited), so
// they take root's (https://github.com/unicode-org/cldr/blob/main/common/main/root.xml,
// `delimiters`): sa.xml, ne.xml, as.xml, kok.xml and sd.xml (Arabic script; sd_Deva.xml for
// Devanagari inherits too) in https://github.com/unicode-org/cldr/blob/main/common/main/.
("Nepali", "ne", Quotes::ENGLISH),
("Konkani", "kok", Quotes::ENGLISH),
("Sindhi", "sd", Quotes::ENGLISH),
];
/// The quotes of a [`LANGUAGES`] entry (case-insensitive).
@@ -213,6 +220,13 @@ pub fn language_quotes(language: &str) -> Option<Quotes> {
LANGUAGES.iter().find(|(l, _, _)| l.eq_ignore_ascii_case(language)).map(|(_, _, q)| *q)
}
/// The BCP 47 tag of the [`LANGUAGES`] entry named or tagged `language` (case-insensitive), the
/// default's included (`en-US`): what a document's language ([`DocSetup::language`]) is written
/// as in an exported file. `None` for a language not in the list.
pub fn language_tag(language: &str) -> Option<&'static str> {
LANGUAGES.iter().find(|(n, t, _)| n.eq_ignore_ascii_case(language) || t.eq_ignore_ascii_case(language)).map(|(_, t, _)| *t)
}
/// The [`LANGUAGES`] entry named or tagged `language` (case-insensitive) as a character's
/// language ([`crate::CharStyle::language`]) stores it: its tag, or `None` for the default (the
/// first entry); `Err` for a language not in the list.
@@ -397,6 +411,16 @@ impl DocSetup {
mod tests {
use super::*;
/// A document's language is written by its tag, the default's included (#3644).
#[test]
fn document_languages_have_their_tags() {
assert_eq!(language_tag(&DocSetup::default().language), Some("en-US"));
assert_eq!(language_tag("French"), Some("fr"));
assert_eq!(language_tag("german: swiss"), Some("de-CH"));
assert_eq!(language_tag("sr-latn"), Some("sr-Latn"));
assert_eq!((language_tag("Klingon"), language_tag("")), (None, None));
}
/// Characters store a language of the list by its tag, the default as none.
#[test]
fn char_languages_are_stored_by_tag() {
@@ -420,6 +444,11 @@ mod tests {
assert_eq!(char_language("BG"), Ok(Some("bg")));
assert_eq!(char_language_name(Some("bg")), Some("Bulgarian"));
assert_eq!(char_language_name(Some("sr-Cyrl")), Some("Serbian: Cyrillic"));
// Sanskrit, Nepali, Assamese, Konkani (a three-letter tag) and Sindhi, by name or tag.
for (name, tag) in [("Sanskrit", "sa"), ("Nepali", "ne"), ("Assamese", "as"), ("Konkani", "kok"), ("Sindhi", "sd")] {
assert_eq!((char_language(name), char_language(&tag.to_uppercase())), (Ok(Some(tag)), Ok(Some(tag))), "{name}");
assert_eq!(char_language_name(Some(tag)), Some(name));
}
// Every entry has a tag of its own, and a name of its own.
for (i, (n, t, _)) in LANGUAGES.iter().enumerate() {
assert!(LANGUAGES.iter().skip(i + 1).all(|(n2, t2, _)| n2 != n && t2 != t), "{n} {t}");
@@ -443,6 +472,11 @@ mod tests {
}
let mut prev = None;
assert_eq!(language_quotes("croatian").unwrap().apply("\"a 'b' c\"", &mut prev), "„a ‚b‘ c“");
// Sanskrit, Nepali, Assamese, Konkani and Sindhi take CLDR root's quotes.
for name in ["Sanskrit", "Nepali", "Assamese", "Konkani", "Sindhi"] {
let mut prev = None;
assert_eq!(language_quotes(name).unwrap().apply("\"a 'b' c\"", &mut prev), "“a ‘b’ c”", "{name}");
}
// Only a typed `”` stands for a straight quote; the other curly quotes stay as typed.
assert_eq!(Quotes::typed_as_straight('”'), Some('"'));
assert!(['“', '„', '‘', '’', '‚', '"', '\'', '«', '»', '「', 'a'].iter().all(|&c| Quotes::typed_as_straight(c).is_none()));
+329 -13
View File
@@ -8,6 +8,7 @@
//! change; [`Document::map_paints`] replaces whole paints of any kind in the same places.
use std::collections::{HashMap, HashSet};
use std::ops::ControlFlow;
use std::sync::Arc;
use vectorcraft_color::swatch::REGISTRATION;
@@ -186,8 +187,9 @@ impl Document {
/// [`Document::map_solid_paints`] limited to the art in the subtrees of `ids` (each paint
/// visited once even when an id is inside another).
pub fn map_solid_paints_in(&mut self, ids: &[NodeId], f: &mut LinkFn) -> usize {
let listed: HashSet<NodeId> = ids.iter().copied().collect();
let roots: Vec<NodeId> =
ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect();
ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect();
let mut n = 0;
let mut g = relink(f);
for id in roots {
@@ -340,18 +342,39 @@ fn map_style_paint(attrs: &mut serde_json::Map<String, serde_json::Value>, key:
/// and gradient stops (with their link), a dynamic symbol instance's own paints
/// ([`override_paints`]), then mesh points (unlinked), in paint order.
pub fn node_colors(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) {
n.walk(&mut |m| {
let _ = try_node_colors::<()>(n, &mut |c, s| {
f(c, s);
ControlFlow::Continue(())
});
}
/// Whether the subtree of `n` holds any color [`node_colors`] visits. It stops at the first one.
pub fn node_has_colors(n: &Node) -> bool {
try_node_colors(n, &mut |_, _| ControlFlow::Break(())).is_break()
}
/// [`node_colors`] that ends at the first color for which `f` returns [`ControlFlow::Break`]: no
/// paint or node after it is visited.
fn try_node_colors<B>(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>) -> ControlFlow<B>) -> ControlFlow<B> {
n.try_walk(&mut |m| {
for p in node_paints(m).chain(override_paints(m)) {
match p {
Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()),
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())),
Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref())?,
Paint::Gradient(g) => {
for s in &g.gradient.stops {
f(&s.color, s.swatch.as_deref())?;
}
}
_ => {}
}
}
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| f(&p.color, None));
for p in &mesh.points {
f(&p.color, None)?;
}
}
});
ControlFlow::Continue(())
})
}
fn item_paint(it: &AppearanceItem) -> &Paint {
@@ -384,14 +407,14 @@ pub fn override_paints(n: &Node) -> impl Iterator<Item = &Paint> {
n.extras().symbol_overrides.iter().flat_map(|o| [o.fill.as_ref(), o.stroke.as_ref()]).flatten()
}
/// The paints a graph keeps for its series and its labels ([`crate::graph::GraphSpec`]), which its
/// marks and labels take each time it is drawn again and which [`node_paints`] leaves out.
/// The paints a graph keeps for its series, its labels and its lines ([`crate::graph::GraphSpec`]), which
/// its marks, labels and lines take each time it is drawn again and which [`node_paints`] leaves out.
pub fn graph_paints(n: &Node) -> impl Iterator<Item = &Paint> {
let g = n.extras().graph.as_deref();
let series = g.into_iter().flat_map(|g| &g.series_paints).flat_map(|s| [s.fill.as_ref(), s.stroke.as_ref()]).flatten();
let labels = g.into_iter().flat_map(|g| [&g.label_styles.values, &g.label_styles.categories, &g.label_styles.legend]).flatten();
let l = g.map(|g| &g.label_styles);
let rows = l.into_iter().flat_map(|l| [&l.values_rows, &l.categories_rows, &l.legend_rows]).flatten();
let rows = l.into_iter().flat_map(|l| [&l.values_rows, &l.categories_rows, &l.legend_rows, &l.axis_rows, &l.ring_rows]).flatten();
series.chain(labels.flat_map(|st| [&st.fill, &st.stroke])).chain(rows.flat_map(|r| [r.paint.fill.as_ref(), r.paint.stroke.as_ref()]).flatten())
}
@@ -400,7 +423,7 @@ fn graph_paints_mut(g: &mut crate::graph::GraphSpec) -> impl Iterator<Item = &mu
let series = g.series_paints.iter_mut().flat_map(|s| [s.fill.as_mut(), s.stroke.as_mut()]).flatten();
let l = &mut g.label_styles;
let labels = [&mut l.values, &mut l.categories, &mut l.legend].into_iter().flatten();
let rows = [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows].into_iter().flatten();
let rows = [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows, &mut l.axis_rows, &mut l.ring_rows].into_iter().flatten();
series
.chain(labels.flat_map(|st| [&mut st.fill, &mut st.stroke]))
.chain(rows.flat_map(|r| [r.paint.fill.as_mut(), r.paint.stroke.as_mut()]).flatten())
@@ -718,6 +741,14 @@ mod tests {
paint: crate::SeriesPaint { fill: Some(red.clone()), ..Default::default() },
..Default::default()
}),
axis_rows: Some(crate::LabelRows {
paint: crate::SeriesPaint { stroke: Some(red.clone()), ..Default::default() },
..Default::default()
}),
ring_rows: Some(crate::LabelRows {
paint: crate::SeriesPaint { stroke: Some(red.clone()), ..Default::default() },
..Default::default()
}),
..Default::default()
},
..Default::default()
@@ -725,18 +756,20 @@ mod tests {
d.node_mut(a).unwrap().extras_mut().graph = Some(Box::new(spec));
let mut seen = 0;
d.visit_paints(&mut |p| seen += usize::from(*p == red));
assert_eq!(seen, 5, "the fill and the graph's series fill, series stroke, legend fill and value label fill row");
assert_eq!(seen, 7, "the fill and the graph's series fill, series stroke, legend fill, value label fill row and axis and ring stroke rows");
let blue = Color::rgb(0.0, 0.0, 1.0);
let mut to_blue = |c: &mut Color, s: &mut Option<String>, _: &mut f32| s.as_deref() == Some("Brand") && std::mem::replace(c, blue) != blue;
assert_eq!(d.map_solid_paints(&mut to_blue), 5);
assert_eq!(d.map_solid_paints(&mut to_blue), 7);
let g = d.node(a).unwrap().extras().graph.clone().unwrap();
assert_eq!(g.series_paints[0].fill, Some(linked(blue, "Brand")));
assert_eq!(g.series_paints[0].stroke, Some(linked(blue, "Brand")));
let legend = g.label_styles.legend.unwrap();
assert_eq!((legend.fill, legend.stroke), (linked(blue, "Brand"), Paint::None));
assert_eq!(g.label_styles.values_rows.unwrap().paint.fill, Some(linked(blue, "Brand")));
assert_eq!(g.label_styles.axis_rows.unwrap().paint.stroke, Some(linked(blue, "Brand")));
assert_eq!(g.label_styles.ring_rows.unwrap().paint.stroke, Some(linked(blue, "Brand")));
let mut cleared = |p: &Paint| (*p == linked(blue, "Brand")).then_some(Paint::None);
assert_eq!(d.map_paints(&mut cleared), 5, "the fill and the graph's four");
assert_eq!(d.map_paints(&mut cleared), 7, "the fill and the graph's six");
assert!(graph_paints(d.node(a).unwrap()).all(Paint::is_none));
}
@@ -811,4 +844,287 @@ mod tests {
node_colors(d.node(b).unwrap(), &mut |c, s| colors.push((*c, s.map(str::to_string))));
assert_eq!(colors, [(Color::rgb(1.0, 0.0, 0.0), None)]);
}
/// [`Document::map_solid_paints_in`] with each ancestor searched for in `ids` rather than looked up in a set.
fn map_solid_paints_in_by_search(d: &mut Document, ids: &[NodeId], f: &mut LinkFn) -> usize {
let roots: Vec<NodeId> =
ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect();
let mut n = 0;
let mut g = relink(f);
for id in roots {
let Some(node) = d.node(id) else { continue };
if let Some((new, count)) = map_node(node, &mut g)
&& let Some(slot) = d.node_mut(id)
{
*slot = new;
n += count;
}
}
n
}
#[test]
fn mapping_within_ids_matches_a_search_of_the_ids() {
// Two layers: the first holds group `outer` (group `inner` with two rectangles, and a
// rectangle) and a rectangle; the second holds a rectangle. Each rectangle has its own color.
let mut d = Document::new(100.0, 100.0);
let first = d.layers[0].id;
let second = d.alloc_id();
d.insert(None, usize::MAX, Node::layer(second, "Second", crate::LayerColor::Preset(1))).unwrap();
let rect = |d: &mut Document, i: u8| {
let id = d.alloc_id();
let r = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
let color = Color::rgb(f32::from(i) / 8.0, 0.0, 0.0);
(id, Arc::new(Node::path(id, r, Appearance::basic(Paint::solid(color), Paint::solid(color), 1.0))))
};
let (r1, n1) = rect(&mut d, 1);
let (r2, n2) = rect(&mut d, 2);
let (r3, n3) = rect(&mut d, 3);
let (r4, n4) = rect(&mut d, 4);
let (r5, n5) = rect(&mut d, 5);
let (inner, outer) = (d.alloc_id(), d.alloc_id());
let outer_node = Node::group(outer, vec![Arc::new(Node::group(inner, vec![n1, n2])), n3]);
d.insert(Some(first), usize::MAX, outer_node).unwrap();
d.insert(Some(first), usize::MAX, Arc::unwrap_or_clone(n4)).unwrap();
d.insert(Some(second), usize::MAX, Arc::unwrap_or_clone(n5)).unwrap();
let missing = NodeId(u64::MAX);
let all = [first, second, outer, inner, r1, r2, r3, r4, r5, missing];
// Every list of up to three of them: nested ids in both orders, duplicates, a missing id and none.
let mut lists: Vec<Vec<NodeId>> = vec![vec![]];
let mut shorter: Vec<Vec<NodeId>> = vec![vec![]];
for _ in 0..3 {
shorter = shorter.iter().flat_map(|l| all.map(|id| [l.as_slice(), &[id]].concat())).collect();
lists.extend(shorter.iter().cloned());
}
assert_eq!(lists.len(), 1 + 10 + 100 + 1000);
for ids in &lists {
// A callback that changes every paint it visits, so a paint visited twice counts twice.
let run = |map: &dyn Fn(&mut Document, &[NodeId], &mut LinkFn) -> usize| {
let mut d = d.clone();
let mut visits = vec![];
let n = map(&mut d, ids, &mut |c, s, t| {
visits.push((*c, s.clone(), *t));
*s = Some(format!("{}", visits.len()));
*t *= 0.5;
true
});
(n, visits, d.layers)
};
let by_set = run(&|d, ids, f| d.map_solid_paints_in(ids, f));
let by_search = run(&|d, ids, f| map_solid_paints_in_by_search(d, ids, f));
assert_eq!(by_set, by_search, "{ids:?}");
}
}
/// The colors [`node_colors`] visits, in its order, by a [`Node::walk`] that reads the whole subtree.
fn full_walk(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) {
n.walk(&mut |m| {
for p in node_paints(m).chain(override_paints(m)) {
match p {
Paint::Solid { color, swatch, .. } => f(color, swatch.as_deref()),
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| f(&s.color, s.swatch.as_deref())),
_ => {}
}
}
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| f(&p.color, None));
}
});
}
/// Whether [`full_walk`] finds a color in `n`.
fn full_walk_has_colors(n: &Node) -> bool {
let mut found = false;
full_walk(n, &mut |_, _| found = true);
found
}
/// The colors of `n` by [`full_walk`], in order.
fn full_walk_colors(n: &Node) -> Vec<(Color, Option<String>)> {
let mut out = vec![];
full_walk(n, &mut |c, s| out.push((*c, s.map(str::to_string))));
out
}
fn square(id: u64, fill: Paint, stroke: Paint) -> Node {
Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::basic(fill, stroke, 1.0))
}
fn holder(id: u64, kind: fn(Vec<Arc<Node>>) -> NodeKind, children: Vec<Node>) -> Node {
Node::new(NodeId(id), kind(children.into_iter().map(Arc::new).collect()))
}
/// One node of each kind of paint [`node_colors`] reads or skips, with whether it shows a color.
fn color_cases() -> Vec<(&'static str, Node, bool)> {
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let gradient = |stops: usize| {
let mut g = vectorcraft_color::Gradient::default();
g.stops.truncate(stops);
Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(g)))
};
let pattern = Paint::Pattern { pattern: "Dots".into(), xf: vectorcraft_geom::Affine::IDENTITY };
let area = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
let mesh = crate::GradientMesh::for_path_with(&area, 2, 2, &|_| (Color::BLACK, 1.0)).unwrap();
let mut empty_mesh = mesh.clone();
empty_mesh.points.clear();
let text = |fill: Paint| {
let style = crate::CharStyle { fill, stroke: Paint::None, ..Default::default() };
let mut n =
Node::new(NodeId(20), NodeKind::Text(Box::new(crate::TextObject::point(vectorcraft_geom::Point::new(0.0, 0.0), "Hi", style))));
n.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into();
n
};
let image = |colorize: Option<Paint>| {
let im = crate::ImageObject {
key: "k".into(),
width: 2,
height: 2,
xf: vectorcraft_geom::Affine::IDENTITY,
link: None,
placement: Default::default(),
pixels: None,
};
let mut n = Node::new(NodeId(21), NodeKind::Image(Box::new(im)));
n.appearance = Appearance::basic(Paint::None, Paint::None, 0.0).into();
n.extras_mut().colorize = colorize.map(Box::new);
n
};
let overridden = |fill: Option<Paint>| {
let mut n = square(22, Paint::None, Paint::None);
n.extras_mut().symbol_overrides = vec![crate::SymbolOverride { path: vec![0], fill, ..Default::default() }];
n
};
let masked = {
let mut n = square(23, Paint::None, Paint::None);
n.extras_mut().mask = Some(Box::new(crate::OpacityMask::new(square(24, red.clone(), Paint::None), true)));
n
};
let group = |children| NodeKind::Group { children, clip: false };
let clip = |children| NodeKind::Group { children, clip: true };
let compound = |children| NodeKind::Compound { children, rule: Default::default() };
let blend = |children| NodeKind::Blend { children, spec: Default::default() };
let blank = |id| square(id, Paint::None, Paint::None);
vec![
("no paint", blank(1), false),
("solid fill", square(2, red.clone(), Paint::None), true),
("solid stroke", square(3, Paint::None, red.clone()), true),
("pattern only", square(4, pattern.clone(), pattern.clone()), false),
("gradient without stops", square(5, gradient(0), Paint::None), false),
("gradient with stops", square(6, gradient(2), Paint::None), true),
("mesh with points", Node::new(NodeId(7), NodeKind::Mesh(mesh)), true),
("mesh without points", Node::new(NodeId(8), NodeKind::Mesh(empty_mesh)), false),
("text run fill", text(red.clone()), true),
("text without paint", text(Paint::None), false),
("image colorize", image(Some(red.clone())), true),
("image without colorize", image(None), false),
("image with a pattern colorize", image(Some(pattern.clone())), false),
("symbol override fill", overridden(Some(red.clone())), true),
("symbol override without paint", overridden(None), false),
("color only in the opacity mask", masked, false),
("group, color first", holder(30, group, vec![square(31, red.clone(), Paint::None), blank(32), blank(33)]), true),
("group, color last", holder(34, group, vec![blank(35), blank(36), square(37, red.clone(), Paint::None)]), true),
("group without color", holder(38, group, vec![blank(39), blank(40)]), false),
("clip group", holder(41, clip, vec![blank(42), square(43, red.clone(), Paint::None)]), true),
("compound shape", holder(44, compound, vec![blank(45), square(46, gradient(3), Paint::None)]), true),
("blend", holder(47, blend, vec![blank(48), blank(49)]), false),
(
"nested groups, color deepest",
holder(50, group, vec![blank(51), holder(52, group, vec![holder(53, group, vec![blank(54), square(55, red.clone(), Paint::None)])])]),
true,
),
]
}
#[test]
fn has_colors_matches_the_full_walk() {
for (label, n, expected) in color_cases() {
let all = full_walk_colors(&n);
assert_eq!(node_has_colors(&n), full_walk_has_colors(&n), "{label}");
assert_eq!(full_walk_has_colors(&n), !all.is_empty(), "{label}");
assert_eq!(node_has_colors(&n), expected, "{label}");
let mut listed = vec![];
node_colors(&n, &mut |c, s| listed.push((*c, s.map(str::to_string))));
assert_eq!(listed, all, "{label}: node_colors lists the same colors in the same order");
}
}
#[test]
fn has_colors_stops_at_the_first_color() {
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let mut stops = vectorcraft_color::Gradient::default();
stops.stops.push(stops.stops[0].clone());
let gradient = Paint::Gradient(Box::new(vectorcraft_color::GradientPaint::new(stops)));
let mut later = vec![square(2, gradient, red.clone())];
later.extend((3..100).map(|id| square(id, red.clone(), red.clone())));
let n = holder(1, |children| NodeKind::Group { children, clip: false }, later);
let (mut colors, mut nodes) = (0, 0);
let flow = try_node_colors(&n, &mut |_, _| {
colors += 1;
ControlFlow::Break(())
});
assert!(flow.is_break());
assert_eq!(colors, 1, "the first gradient stop ends the walk: no later stop, stroke or object is read");
let flow = n.try_walk(&mut |m| {
nodes += 1;
if node_paints(m).next().is_some() { ControlFlow::Break(()) } else { ControlFlow::Continue(()) }
});
assert!(flow.is_break());
assert_eq!(nodes, 2, "the group, then its first member: none of the 97 after it");
}
/// Times [`node_has_colors`] against the full walk it replaces on one group of 100,000 paths, alternating the two in
/// one process: `cargo test --release -p vectorcraft-doc --lib -- --ignored --nocapture has_colors_timing`.
#[test]
#[ignore = "a timing, not a check"]
fn has_colors_timing() {
/// This thread's CPU time in nanoseconds on Linux; the elapsed time since `start` elsewhere.
fn clock(start: std::time::Instant) -> u128 {
let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok();
cpu.and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or_else(|| start.elapsed().as_nanos())
}
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let count = 100_000u64;
let group = |colored: &dyn Fn(u64) -> bool| {
let children =
(0..count).map(|i| if colored(i) { square(i + 1, red.clone(), Paint::None) } else { square(i + 1, Paint::None, Paint::None) });
holder(0, |children| NodeKind::Group { children, clip: false }, children.collect())
};
let cases = [
("every path filled", group(&|_| true)),
("only the last path filled", group(&|i| i == count - 1)),
("no path filled", group(&|_| false)),
];
let start = std::time::Instant::now();
println!("clock: {}", if std::fs::metadata("/proc/thread-self/schedstat").is_ok() { "thread CPU time" } else { "wall clock" });
// The time per call of `f` on `n`: batches of calls double until one takes at least 100 ms.
let per_call = |f: fn(&Node) -> bool, n: &Node| {
let mut calls = 1u32;
loop {
let t = clock(start);
for _ in 0..calls {
std::hint::black_box(f(std::hint::black_box(n)));
}
let spent = clock(start) - t;
if spent >= 100_000_000 || calls >= 1 << 30 {
return (spent as f64 / f64::from(calls), calls);
}
calls *= 2;
}
};
for (label, n) in &cases {
assert_eq!(full_walk_has_colors(n), node_has_colors(n), "{label}");
let (mut old, mut new) = (vec![], vec![]);
for _ in 0..7 {
old.push(per_call(full_walk_has_colors, n));
new.push(per_call(node_has_colors, n));
}
old.sort_by(|a, b| a.0.total_cmp(&b.0));
new.sort_by(|a, b| a.0.total_cmp(&b.0));
let (o, nw) = (old[3], new[3]);
println!(
"{label}: full walk {:.1} ns per call ({} calls), node_has_colors {:.1} ns per call ({} calls), median of 7 runs",
o.0, o.1, nw.0, nw.1
);
}
}
}
+80
View File
@@ -0,0 +1,80 @@
//! Symbol Options › Align to Pixel Grid: a symbol whose instances stay on the pixel grid at their
//! actual size wherever they are placed
//! (<https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28>).
//!
//! Stored under [`SYMBOL_PIXEL_ALIGNED`] keyed by symbol name; a symbol that is not pixel-aligned
//! (the default) is left out of the map.
use std::collections::HashSet;
use crate::Document;
/// Document unknown key: `{ symbolName: true }` for each pixel-aligned symbol.
pub const SYMBOL_PIXEL_ALIGNED: &str = "symbolPixelAligned";
impl Document {
/// Whether symbol `name` has Symbol Options › Align to Pixel Grid on (default: off).
pub fn symbol_pixel_aligned(&self, name: &str) -> bool {
self.unknown.get(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.get(name)).and_then(serde_json::Value::as_bool).unwrap_or(false)
}
/// Turn Align to Pixel Grid on or off for symbol `name`. Off removes the symbol from the map,
/// and the map goes when it is empty.
pub fn set_symbol_pixel_aligned(&mut self, name: &str, on: bool) {
if on {
let m = self.unknown.entry(SYMBOL_PIXEL_ALIGNED.to_string()).or_insert_with(|| serde_json::json!({}));
if let Some(o) = m.as_object_mut() {
o.insert(name.into(), serde_json::json!(true));
}
return;
}
let Some(o) = self.unknown.get_mut(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.as_object_mut()) else { return };
o.remove(name);
if o.is_empty() {
self.unknown.remove(SYMBOL_PIXEL_ALIGNED);
}
}
/// Move the stored setting when a symbol is renamed.
pub fn rename_symbol_pixel_aligned(&mut self, from: &str, to: &str) {
if from == to {
return;
}
let on = self.symbol_pixel_aligned(from);
self.set_symbol_pixel_aligned(from, false);
self.set_symbol_pixel_aligned(to, on);
}
/// The names of the pixel-aligned symbols the document holds (empty for most documents).
pub fn pixel_aligned_symbols(&self) -> HashSet<String> {
let Some(o) = self.unknown.get(SYMBOL_PIXEL_ALIGNED).and_then(|m| m.as_object()) else { return HashSet::new() };
o.iter()
.filter(|(name, v)| v.as_bool() == Some(true) && self.symbols.iter().any(|s| &s.name == *name))
.map(|(name, _)| name.clone())
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_setting_is_off_by_default_and_follows_a_rename() {
let mut d = Document::new(100.0, 100.0);
let art = std::sync::Arc::new(crate::Node::group(d.alloc_id(), vec![]));
d.symbols.push(crate::Symbol { dynamic: false, name: "A".into(), art });
assert!(!d.symbol_pixel_aligned("A"));
assert!(d.unknown.get(SYMBOL_PIXEL_ALIGNED).is_none());
d.set_symbol_pixel_aligned("A", true);
assert!(d.symbol_pixel_aligned("A"));
assert_eq!(d.pixel_aligned_symbols(), HashSet::from(["A".to_string()]));
d.symbols[0].name = "B".into();
d.rename_symbol_pixel_aligned("A", "B");
assert!(!d.symbol_pixel_aligned("A"));
assert!(d.symbol_pixel_aligned("B"));
d.set_symbol_pixel_aligned("B", false);
assert!(d.unknown.get(SYMBOL_PIXEL_ALIGNED).is_none());
assert!(d.pixel_aligned_symbols().is_empty());
}
}
+455 -10
View File
@@ -9,7 +9,7 @@ use std::sync::Arc;
use vectorcraft_geom::{Affine, Rect};
use crate::symbol_nine_slice::transformed;
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF};
use crate::{AppearanceItem, Document, MAX_SYMBOL_NODES, NineSliceMap, Node, NodeKind, SYMBOL_HALF, Symbol};
/// The box a symbol instance is measured by when its symbol's art has no box
/// ([`SymbolBoxes::art`]), and in [`Node::geometric_bounds`]: the 20 × 20 square around the origin
@@ -107,6 +107,134 @@ pub struct SymbolBoxes<'a> {
consulted: RefCell<Option<HashSet<String>>>,
}
/// What the art boxes and nesting depths of a document's symbols depend on: each symbol's name and
/// art, the symbols' 9-slice guides (which symbols' art holds instances placed through guides), and
/// the inputs of the live geometry effects of clipping paths ([`crate::hit::set_clip_region`]).
/// Symbol sizes only move art placed through guides, which is measured on each call. Each symbol's
/// art is held by a weak pointer. While a weak pointer to an art's allocation is held, nothing else
/// can be at that address, and the art can't be changed in place (`Arc::make_mut` moves it), so art
/// changed in any way no longer matches, as in the cache of `Document::inline_cycles`.
struct KeptKey {
symbols: Vec<(String, std::sync::Weak<Node>)>,
guides: Option<serde_json::Value>,
inputs: (u64, bool),
}
impl KeptKey {
/// The key of the document's 9-slice guides.
const GUIDES: &str = crate::symbol_nine_slice::SYMBOL_NINE_SLICE;
fn of(doc: &Document, inputs: (u64, bool)) -> Self {
KeptKey {
symbols: doc.symbols.iter().map(|s| (s.name.clone(), Arc::downgrade(&s.art))).collect(),
guides: doc.unknown.get(Self::GUIDES).cloned(),
inputs,
}
}
/// Does this describe `doc`'s symbols as they are now, with inputs `inputs`?
fn is_of(&self, doc: &Document, inputs: (u64, bool)) -> bool {
self.inputs == inputs
&& self.symbols.len() == doc.symbols.len()
&& self.symbols.iter().zip(&doc.symbols).all(|((name, art), s)| std::ptr::eq(art.as_ptr(), Arc::as_ptr(&s.art)) && *name == s.name)
&& self.guides.as_ref() == doc.unknown.get(Self::GUIDES)
}
fn same(&self, other: &KeptKey) -> bool {
self.inputs == other.inputs
&& self.symbols.len() == other.symbols.len()
&& self.symbols.iter().zip(&other.symbols).all(|((n, a), (m, b))| a.ptr_eq(b) && n == m)
&& self.guides == other.guides
}
}
/// Art boxes, nesting depths and the name index measured by boxes made by
/// [`Document::kept_symbol_boxes`], kept for the next ones made for the same symbols.
struct Kept {
key: KeptKey,
names: Option<Arc<SymbolNames>>,
measured: HashMap<String, Option<ArtBox>>,
depths: HashMap<String, Option<usize>>,
}
/// How many sets of symbols [`Document::kept_symbol_boxes`] keeps measurements for on each thread:
/// clicks can alternate between two open documents.
const KEPT_SETS: usize = 2;
thread_local! {
/// The measurements [`Document::kept_symbol_boxes`] keeps, the latest first.
static KEPT: RefCell<Vec<Kept>> = const { RefCell::new(Vec::new()) };
}
/// [`SymbolBoxes`] made by [`Document::kept_symbol_boxes`], which keep their measurements for the
/// next ones when dropped.
pub(crate) struct KeptBoxes<'a> {
boxes: SymbolBoxes<'a>,
/// What the measurements depend on, under which they are kept.
key: Option<KeptKey>,
/// Other boxes of the same document whose measurements are kept with these
/// ([`Self::keeping`]).
also: Option<&'a SymbolBoxes<'a>>,
}
impl<'a> std::ops::Deref for KeptBoxes<'a> {
type Target = SymbolBoxes<'a>;
fn deref(&self) -> &SymbolBoxes<'a> {
&self.boxes
}
}
impl<'a> KeptBoxes<'a> {
/// These boxes, which also keep the art boxes and nesting depths `other` has measured when
/// dropped. `other` measures the same document, as the boxes of
/// [`Document::locked_artboards_kept`] do.
pub(crate) fn keeping(mut self, other: &'a SymbolBoxes<'a>) -> Self {
self.also = Some(other);
self
}
}
impl Drop for KeptBoxes<'_> {
/// Keeps the measurements, adding them to those kept for the same symbols by other boxes alive
/// at the same time. Art boxes of symbols whose art holds instances of symbols with 9-slice
/// guides are left out: measuring them places art within a budget the boxes share
/// ([`SymbolBoxes::sliced_visual`]).
fn drop(&mut self) {
let Some(key) = self.key.take() else { return };
let b = &self.boxes;
let mut measured = b.measured.take();
let mut depths = b.depths.take();
if let Some(other) = self.also {
for (name, a) in other.measured.borrow().iter() {
measured.entry(name.clone()).or_insert(*a);
}
for (name, d) in other.depths.borrow().iter() {
depths.entry(name.clone()).or_insert(*d);
}
}
measured.retain(|_, a| a.is_none_or(|a| !a.sliced));
let mut kept = Kept { key, names: b.names.get().cloned(), measured, depths };
// Nothing is kept while the thread ends or the list is in use.
let _ = KEPT.try_with(|k| {
if let Ok(mut k) = k.try_borrow_mut() {
if let Some(i) = k.iter().position(|e| e.key.same(&kept.key)) {
let other = k.remove(i);
kept.names = kept.names.or(other.names);
for (name, a) in other.measured {
kept.measured.entry(name).or_insert(a);
}
for (name, d) in other.depths {
kept.depths.entry(name).or_insert(d);
}
}
k.insert(0, kept);
k.truncate(KEPT_SETS);
}
});
}
}
impl Document {
/// [`SymbolBoxes`] for this document's symbols, none measured yet.
pub fn symbol_boxes(&self) -> SymbolBoxes<'_> {
@@ -131,10 +259,60 @@ impl Document {
}
}
/// [`Self::symbol_boxes`] that start with the art boxes, nesting depths and name index measured
/// by the last such boxes made on this thread for the same symbols, and keep theirs for the next
/// ones when dropped. The measurements are made again when a symbol's name or art, the symbols'
/// 9-slice guides, or the inputs of the live geometry effects of clipping paths have
/// changed since. Measurements for the last [`KEPT_SETS`] sets of symbols are kept.
pub(crate) fn kept_symbol_boxes(&self) -> KeptBoxes<'_> {
self.kept_boxes(false)
}
/// [`Self::symbol_boxes`] that start with a copy of the measurements
/// [`Self::kept_symbol_boxes`] would start with, and keep nothing themselves.
pub(crate) fn symbol_boxes_from_kept(&self) -> SymbolBoxes<'_> {
let mut kept = self.kept_boxes(true);
kept.key = None;
std::mem::replace(&mut kept.boxes, self.symbol_boxes())
}
/// [`Self::kept_symbol_boxes`], taking the kept measurements, or with `copy` copying them.
fn kept_boxes(&self, copy: bool) -> KeptBoxes<'_> {
let mut boxes = self.symbol_boxes();
let inputs = crate::hit::clip_region_inputs();
let found = KEPT
.try_with(|k| {
let mut k = k.try_borrow_mut().ok()?;
let i = k.iter().position(|e| e.key.is_of(self, inputs))?;
if copy {
let e = k.get(i)?;
let key = KeptKey { symbols: e.key.symbols.clone(), guides: e.key.guides.clone(), inputs };
Some(Kept { key, names: e.names.clone(), measured: e.measured.clone(), depths: e.depths.clone() })
} else {
Some(k.remove(i))
}
})
.ok()
.flatten();
let key = match found {
Some(e) => {
if let Some(names) = e.names {
// The boxes were just made, so no index is set yet.
let _ = boxes.names.set(names);
}
*boxes.measured.get_mut() = e.measured;
*boxes.depths.get_mut() = e.depths;
e.key
}
None => KeptKey::of(self, inputs),
};
KeptBoxes { boxes, key: Some(key), also: None }
}
/// Each symbol name of this document → the index of the first symbol of that name (the one a
/// name finds).
pub(crate) fn symbol_names(&self) -> SymbolNames {
#[cfg(test)]
#[cfg(any(test, feature = "symbol-read-count"))]
SYMBOLS_READ.with(|c| c.set(c.get() + self.symbols.len()));
let mut names = HashMap::with_capacity(self.symbols.len());
for (i, s) in self.symbols.iter().enumerate() {
@@ -144,10 +322,21 @@ impl Document {
}
}
#[cfg(test)]
#[cfg(any(test, feature = "symbol-read-count"))]
thread_local! {
/// How many symbols [`Document::symbol_names`] has read on this thread.
pub(crate) static SYMBOLS_READ: Cell<usize> = const { Cell::new(0) };
/// How many art boxes [`SymbolBoxes::art`] has measured on this thread.
static ART_BOXES_MEASURED: Cell<usize> = const { Cell::new(0) };
}
/// How many symbols [`Document::symbol_names`] has read on this thread, for other crates' tests
/// that count how often the symbol list is read to find symbols by name (the `symbol-read-count`
/// feature, dev-dependencies only).
#[cfg(any(test, feature = "symbol-read-count"))]
#[doc(hidden)]
pub fn symbols_read() -> usize {
SYMBOLS_READ.with(Cell::get)
}
impl<'a> SymbolBoxes<'a> {
@@ -156,6 +345,16 @@ impl<'a> SymbolBoxes<'a> {
self.doc
}
/// New boxes for the same document, none measured yet and with none of the options set, that
/// find symbols by name through the same index as these boxes ([`Self::symbol`]). Measuring
/// objects one at a time in boxes of their own made this way measures them as boxes made by
/// [`Document::symbol_boxes`] do, without reading the symbol list again.
pub fn unmeasured(&self) -> SymbolBoxes<'a> {
let doc: &'a Document = self.doc;
let names = self.names.get_or_init(|| Arc::new(doc.symbol_names()));
doc.symbol_boxes().with_names(names)
}
/// Makes these boxes find symbols by `names` ([`Document::symbol_names`]), made from the
/// document's symbols while they had the names and order they have now.
pub(crate) fn with_names(self, names: &Arc<SymbolNames>) -> Self {
@@ -163,19 +362,24 @@ impl<'a> SymbolBoxes<'a> {
self
}
/// The art of the first symbol of the document named `name`, found in time independent of the
/// number of symbols after the first lookup.
pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc<Node>> {
/// The first symbol of the document named `name`, found in time independent of the number of
/// symbols after the first lookup.
pub fn symbol(&self, name: &str) -> Option<&'a Symbol> {
let doc: &'a Document = self.doc;
let names = self.names.get_or_init(|| Arc::new(doc.symbol_names()));
let i = *names.get(name)?;
match doc.symbols.get(i) {
Some(s) if s.name == name => Some(&s.art),
Some(s) if s.name == name => Some(s),
// Names that no longer match the symbols: the first symbol of that name.
_ => doc.symbols.iter().find(|s| s.name == name).map(|s| &s.art),
_ => doc.symbols.iter().find(|s| s.name == name),
}
}
/// The art of the first symbol of the document named `name` ([`Self::symbol`]).
pub(crate) fn symbol_art(&self, name: &str) -> Option<&'a Arc<Node>> {
self.symbol(name).map(|s| &s.art)
}
/// Makes these boxes measure every symbol instance as [`Node::reach_bounds_with`] does, by its
/// art box alone. An instance that scales or turns stroked art then measures a little larger
/// than with [`Node::visual_bounds_with`], and its art is not transformed to measure it. The
@@ -218,6 +422,8 @@ impl<'a> SymbolBoxes<'a> {
pub(crate) fn art(&self, name: &str) -> Option<ArtBox> {
let cached = self.measured.borrow().get(name).copied();
let b = cached.unwrap_or_else(|| {
#[cfg(test)]
ART_BOXES_MEASURED.with(|c| c.set(c.get() + 1));
let b = self.measure_art(name, |art| self.in_art(|| art_box(art, self))).flatten();
self.measured.borrow_mut().insert(name.to_string(), b);
b
@@ -584,10 +790,10 @@ fn art_box(art: &Arc<Node>, symbols: &SymbolBoxes) -> Option<ArtBox> {
#[cfg(test)]
mod tests {
use vectorcraft_color::{Color, Paint};
use vectorcraft_geom::shapes;
use vectorcraft_geom::{Point, shapes};
use super::*;
use crate::{Appearance, Symbol};
use crate::{Appearance, NodeId, Symbol};
/// A rectangle filled black, with a `stroke` pt black stroke (0: none).
fn rect(d: &mut Document, r: Rect, stroke: f64) -> Node {
@@ -722,6 +928,57 @@ mod tests {
assert_eq!(s.sliced_placed.get(), 13);
}
#[test]
fn symbols_are_found_by_name_reading_the_list_once() {
// 2,000 symbols, then two named "Mark": a name finds the first.
let mut d = Document::new(200.0, 200.0);
for i in 0..2000 {
let r = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0);
symbol(&mut d, &format!("Filler {i}"), vec![r]);
}
let (first, second) = (rect(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0), 0.0), rect(&mut d, Rect::new(0.0, 0.0, 20.0, 20.0), 0.0));
symbol(&mut d, "Mark", vec![first]);
symbol(&mut d, "Mark", vec![second]);
let read = || SYMBOLS_READ.with(Cell::get);
let before = read();
let s = d.symbol_boxes();
for _ in 0..1000 {
assert!(s.symbol("Mark").is_some_and(|m| std::ptr::eq(m, &d.symbols[2000])));
assert!(s.symbol("Filler 7").is_some_and(|m| std::ptr::eq(m, &d.symbols[7])));
assert!(s.symbol("Nowhere").is_none());
}
assert_eq!(read() - before, d.symbols.len());
}
#[test]
fn unmeasured_boxes_share_the_index_and_nothing_measured() {
// 2,000 symbols, then a 9-slice frame held, scaled, by "Holder", whose instances spend
// the boxes' budget of placed objects.
let mut d = Document::new(200.0, 200.0);
for i in 0..2000 {
let r = rect(&mut d, Rect::new(0.0, 0.0, 1.0, 1.0), 0.0);
symbol(&mut d, &format!("Filler {i}"), vec![r]);
}
let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0);
symbol(&mut d, "Panel", vec![frame]);
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
let wide = instance(&mut d, "Panel", Affine::scale_non_uniform(2.0, 1.0));
symbol(&mut d, "Holder", vec![wide]);
let holder = instance(&mut d, "Holder", Affine::scale_non_uniform(1.5, 1.5));
let fresh = holder.visual_bounds_with(&d.symbol_boxes().quick());
let read = || SYMBOLS_READ.with(Cell::get);
let s = d.symbol_boxes().quick();
assert_eq!(holder.visual_bounds_with(&s), fresh);
assert!(s.sliced_placed.get() > 0);
let before = read();
let u = s.unmeasured();
assert_eq!(read(), before, "the index is shared");
assert!(u.measured.borrow().is_empty() && u.sliced.borrow().is_empty() && u.reaches.borrow().is_empty());
assert_eq!((u.sliced_placed.get(), u.holders.get(), u.quick.get()), (0, 0, false));
assert_eq!(holder.visual_bounds_with(&u.quick()), fresh);
assert_eq!(read(), before);
}
#[test]
fn measuring_9_slice_instances_reads_the_symbol_list_once() {
// 2,000 symbols, then a frame with guides and a symbol with guides holding the frame
@@ -911,4 +1168,192 @@ mod tests {
assert_eq!(s.effects_reach("Leaf", [2.0, 0.0, 0.0, 2.0], &measure(7.0)), 7.0);
assert_eq!(runs.get(), MAX_REACHES + 2);
}
/// How many art boxes `f` measures on this thread.
fn art_boxes_measured(f: impl FnOnce()) -> usize {
let before = ART_BOXES_MEASURED.with(Cell::get);
f();
ART_BOXES_MEASURED.with(Cell::get) - before
}
/// A document with symbols "S 0" to "S 9", each a 10 × 10 square around the origin, and an
/// instance of each at (40 i + 20, 20).
fn ten_symbols() -> Document {
let mut d = Document::new(400.0, 100.0);
let layer = d.layers.first().map(|l| l.id);
for i in 0..10 {
let square = rect(&mut d, Rect::new(-5.0, -5.0, 5.0, 5.0), 0.0);
symbol(&mut d, &format!("S {i}"), vec![square]);
let at = instance(&mut d, &format!("S {i}"), Affine::translate((40.0 * f64::from(i) + 20.0, 20.0)));
d.insert(layer, usize::MAX, at).unwrap();
}
d
}
#[test]
fn hit_tests_measure_each_symbols_art_once_while_the_symbols_stay_the_same() {
use crate::hit::{self, HitOptions};
let d = ten_symbols();
let clicks = || {
for i in 0..10 {
let p = Point::new(40.0 * f64::from(i) + 20.0, 20.0);
assert!(hit::hit_test(&d, p, HitOptions::default()).is_some(), "instance {i} is hit");
assert_eq!(hit::objects_at(&d, p, HitOptions::default(), None).len(), 1);
}
assert_eq!(hit::marquee(&d, Rect::new(0.0, 0.0, 400.0, 100.0), None, false).len(), 10);
};
let first = art_boxes_measured(clicks);
assert_eq!(first, 10, "each symbol's art box measured once");
assert_eq!(art_boxes_measured(clicks), 0, "art boxes measured again");
}
#[test]
fn hit_tests_measure_a_symbol_again_after_it_changes() {
use crate::hit::{self, HitOptions};
let mut d = ten_symbols();
// Past the square of "S 1" at (60, 20).
let past = Point::new(71.0, 20.0);
assert!(hit::hit_test(&d, past, HitOptions::default()).is_none());
// The art grows 3 times in place: no other copy of it is held in the document.
Arc::make_mut(&mut d.symbols[1].art).transform(Affine::scale(3.0), false);
let measured = art_boxes_measured(|| assert!(hit::hit_test(&d, past, HitOptions::default()).is_some(), "the grown art is hit"));
assert!(measured > 0);
// New art for "S 2", 40 wide.
let wide = rect(&mut d, Rect::new(-20.0, -5.0, 20.0, 5.0), 0.0);
d.symbols[2].art = Arc::new(wide);
assert!(hit::hit_test(&d, Point::new(115.0, 20.0), HitOptions::default()).is_some(), "the new art is hit");
// "S 3" renamed: its instance now shows the 20 × 20 square.
d.symbols[3].name = "Renamed".into();
assert!(hit::hit_test(&d, Point::new(148.0, 28.0), HitOptions::default()).is_some(), "the square is hit");
assert_eq!(hits(&d), fresh_hits(&d));
}
/// What clicks on a grid over `d` hit, and what a marquee over it selects.
fn hits(d: &Document) -> (Vec<Option<Vec<NodeId>>>, Vec<NodeId>) {
use crate::hit::{self, HitOptions};
let mut clicks = Vec::new();
for y in (0..400).step_by(5) {
for x in (0..400).step_by(5) {
let p = Point::new(f64::from(x), f64::from(y));
clicks.push(hit::hit_test(d, p, HitOptions::default()).map(|h| h.ancestry));
}
}
(clicks, hit::marquee(d, Rect::new(0.0, 0.0, 400.0, 400.0), None, false))
}
/// [`hits`] with no measurements kept from earlier hit tests.
fn fresh_hits(d: &Document) -> (Vec<Option<Vec<NodeId>>>, Vec<NodeId>) {
KEPT.with_borrow_mut(Vec::clear);
hits(d)
}
/// A bar in a panel with or without 9-slice guides, in a holder whose instance at (50, 50) is
/// scaled 2 times across. With the guides, the bar draws from x 30 to 210 and y 90 to 110; without
/// them, from x 70 to 190, inside the panel's frame from x 50 to 250 and y 50 to 150.
fn sliced_holder(guides: bool) -> Document {
let mut d = Document::new(400.0, 400.0);
let bar = rect(&mut d, Rect::new(10.0, 40.0, 70.0, 60.0), 0.0);
symbol(&mut d, "Bar", vec![bar]);
let frame = rect(&mut d, Rect::new(0.0, 0.0, 100.0, 100.0), 0.0);
let inner = instance(&mut d, "Bar", Affine::IDENTITY);
symbol(&mut d, "Panel", vec![frame, inner]);
if guides {
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
}
let panel = instance(&mut d, "Panel", Affine::IDENTITY);
symbol(&mut d, "Holder", vec![panel]);
let layer = d.layers.first().map(|l| l.id);
let holder = instance(&mut d, "Holder", Affine::translate((50.0, 50.0)) * Affine::scale_non_uniform(2.0, 1.0));
d.insert(layer, usize::MAX, holder).unwrap();
d
}
#[test]
fn hit_tests_follow_new_9_slice_guides_and_symbol_sizes() {
use crate::hit::{self, HitOptions};
let mut d = sliced_holder(false);
// Left of the frame, where only the bar placed through the guides draws.
let left = Point::new(40.0, 100.0);
assert!(hit::hit_test(&d, left, HitOptions::default()).is_none());
d.set_symbol_nine_slice("Panel", Some(crate::SymbolNineSlice::default()));
assert!(hit::hit_test(&d, left, HitOptions::default()).is_some(), "the bar placed through the guides is hit");
assert_eq!(hits(&d), fresh_hits(&d));
let before = hits(&d);
d.unknown.insert(crate::SYMBOL_SIZES.into(), serde_json::json!({ "Panel": [200.0, 100.0] }));
let after = hits(&d);
assert_ne!(after, before, "the size moves the guides");
assert_eq!(after, fresh_hits(&d));
}
#[test]
fn hit_tests_measure_symbols_holding_9_slice_instances_on_each_call() {
use crate::hit::{self, HitOptions};
let d = sliced_holder(true);
let left = Point::new(40.0, 100.0);
assert!(hit::hit_test(&d, left, HitOptions::default()).is_some());
// The holder's art holds an instance of a symbol with guides; the panel's art holds none.
KEPT.with_borrow(|k| {
let measured = &k[0].measured;
assert!(measured.contains_key("Panel") && !measured.contains_key("Holder"), "{:?}", measured.keys());
});
let again = art_boxes_measured(|| assert!(hit::hit_test(&d, left, HitOptions::default()).is_some()));
assert!(again > 0, "the holder's art box measured again");
}
#[test]
fn kept_measurements_depend_on_the_inputs_of_clipping_path_effects() {
let d = ten_symbols();
let key = KeptKey::of(&d, (0, false));
assert!(key.is_of(&d, (0, false)));
assert!(!key.is_of(&d, (1, false)), "live inputs changed");
assert!(!key.is_of(&d, (0, true)), "a clip region registered");
}
#[test]
fn hit_tests_with_a_locked_artboard_measure_each_symbols_art_once() {
use crate::hit::{self, HitOptions};
let mut d = ten_symbols();
d.artboards[0].locked = true;
let clicks = || {
for i in 0..10 {
let p = Point::new(40.0 * f64::from(i) + 20.0, 20.0);
assert!(hit::hit_test(&d, p, HitOptions::default()).is_none(), "instance {i} is on the locked artboard");
assert!(hit::objects_at(&d, p, HitOptions::default(), None).is_empty());
}
};
assert!(art_boxes_measured(clicks) >= 10, "each symbol's art box measured");
assert_eq!(art_boxes_measured(clicks), 0, "art boxes measured again");
// A marquee passes over the objects on a locked artboard without measuring them itself: only
// its locks measure their art.
let mut d = ten_symbols();
d.artboards[0].locked = true;
let marquee = || assert!(hit::marquee(&d, Rect::new(0.0, 0.0, 400.0, 100.0), None, false).is_empty());
assert_eq!(art_boxes_measured(marquee), 10, "each symbol's art box measured once");
assert_eq!(art_boxes_measured(marquee), 0, "art boxes measured again");
}
#[test]
fn hit_tests_hold_no_symbol_art() {
use crate::hit::{self, HitOptions};
let d = ten_symbols();
drop(hit::hit_test(&d, Point::new(20.0, 20.0), HitOptions::default()));
assert!(KEPT.with_borrow(|k| !k.is_empty()));
assert!(d.symbols.iter().all(|s| Arc::strong_count(&s.art) == 1), "only the document holds the symbols' art");
}
#[test]
fn hit_tests_keep_the_measurements_of_two_sets_of_symbols() {
use crate::hit::{self, HitOptions};
let docs = [ten_symbols(), ten_symbols(), ten_symbols()];
let p = Point::new(20.0, 20.0);
for d in &docs {
drop(hit::hit_test(d, p, HitOptions::default()));
}
assert_eq!(KEPT.with_borrow(Vec::len), KEPT_SETS);
// The last two are kept, the first is measured again.
let kept = art_boxes_measured(|| docs[1..].iter().for_each(|d| drop(hit::hit_test(d, p, HitOptions::default()))));
assert_eq!(kept, 0);
let first = art_boxes_measured(|| drop(hit::hit_test(&docs[0], p, HitOptions::default())));
assert!(first > 0);
}
}
+161
View File
@@ -157,6 +157,58 @@ fn cached_lookups_follow_any_edit_of_the_tree() {
}
}
/// Every node whose id is in `ids`, by walking the tree.
fn every_node(d: &Document, ids: &[NodeId]) -> Vec<*const Node> {
let mut out = vec![];
d.walk(|n| {
if ids.contains(&n.id) {
out.push(n as *const Node);
}
});
out
}
/// [`Document::nodes_in_order`] gives every node with each id in tree order, repeated ids
/// included, with the cache built and without it, for a few ids (cached paths) and for many (a
/// walk).
#[test]
fn nodes_in_order_match_a_walk() {
for seed in 1..40 {
let (d, ids) = tree(seed);
let few: Vec<NodeId> = ids.iter().copied().step_by(17).collect();
for cold in [true, false] {
if cold {
d.drop_lookup_cache();
} else {
d.node(ids[0]);
}
for list in [&ids[..], &few[..], &ids[ids.len() / 2..ids.len() / 2 + 1], &[]] {
let found: Vec<*const Node> = d.nodes_in_order(list.iter().copied()).into_iter().map(|n| n as *const Node).collect();
assert_eq!(found, every_node(&d, list), "seed {seed}, cold {cold}, {list:?}");
}
}
// An id that the tree repeats: every node with it.
let Some(dup) = ids.iter().enumerate().find(|(i, id)| ids[..*i].contains(id)).map(|(_, id)| *id) else { continue };
assert!(d.nodes_in_order([dup]).len() >= 2, "seed {seed}: {dup:?} is in the tree more than once");
// A second node given an id once held once, after the cache was built: the lookup finds the
// cached node, which has that id; with the cache built afresh, both.
let mut d = d;
let once = ids.iter().copied().find(|id| every_node(&d, &[*id]).len() == 1 && d.node(*id).is_some_and(|n| !n.is_layer()));
let Some(once) = once else { continue };
d.node(once);
let copy = Arc::new(Node::path(once, shapes::rectangle(Rect::new(0.0, 0.0, 2.0, 2.0)), Appearance::default_art()));
if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() {
ch.insert(0, copy);
}
let found = d.nodes_in_order([once]);
assert!(!found.is_empty() && found.iter().all(|n| n.id == once), "seed {seed}: {once:?}");
d.drop_lookup_cache();
d.node(once);
let found: Vec<*const Node> = d.nodes_in_order([once]).into_iter().map(|n| n as *const Node).collect();
assert_eq!(found, every_node(&d, &[once]), "seed {seed}: {once:?} cached afresh");
}
}
/// Nodes of `d` picked and ordered by `seed`. None lies inside another, and each of them, and each
/// node it is in, appears in the tree once.
fn picks(d: &Document, seed: u64) -> Vec<NodeId> {
@@ -282,3 +334,112 @@ fn edits_of_many_refuse_missing_repeated_and_nested_ids() {
assert_eq!(serde_json::to_string(&b).ok(), saved, "{what}: the document stays as it was");
}
}
/// The nearest node passing `pred` at or above `id`, as `ancestry` read from the end with `node`
/// for each id finds it.
fn nearest_by_ancestry(d: &Document, id: NodeId, pred: impl Fn(&Node) -> bool) -> Option<*const Node> {
d.ancestry(id).unwrap_or_default().into_iter().rev().find_map(|a| d.node(a).filter(|n| pred(n))).map(|n| n as *const Node)
}
/// [`Document::nearest_finder`] gives what [`nearest_by_ancestry`] gives for every id, on a clone
/// each, so both start from the same cache.
fn nearest_agrees(d: &Document, ids: &[NodeId], what: &str) {
type Pred = fn(&Node) -> bool;
let preds: [(&str, Pred); 5] = [
("group", |n| matches!(n.kind, NodeKind::Group { .. })),
("layer", |n| n.is_layer()),
("any", |_| true),
("none", |_| false),
("id divisible by 3", |n| n.id.0 % 3 == 0),
];
for (name, pred) in preds {
let (a, b) = (d.clone(), d.clone());
let want: Vec<_> = ids.iter().map(|id| nearest_by_ancestry(&a, *id, pred)).collect();
let mut find = b.nearest_finder();
let got: Vec<_> = ids.iter().map(|id| find.nearest(*id, pred).map(|n| n as *const Node)).collect();
assert_eq!(got, want, "{what}: {name}");
}
}
#[test]
fn nearest_finder_matches_the_ancestry_walk() {
for seed in 1..30 {
let (mut d, ids) = tree(seed);
nearest_agrees(&d, &ids, "no cache");
d.node(ids[0]);
nearest_agrees(&d, &ids, "cached");
// Every path in the first layer shifts: the cache is stale there.
let extra = d.alloc_id();
let leaf = Arc::new(Node::path(extra, shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()));
if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() {
ch.insert(0, leaf);
}
nearest_agrees(&d, &ids, "a stale cache");
// A group with the id of a node in the last layer, earlier in tree order than it, put in
// after the cache was built.
d.drop_lookup_cache();
d.node(ids[0]);
let last = d.layers.len() - 1;
let dup = d.layers[last].children().and_then(|c| c.last()).map(|n| n.id);
if let Some(dup) = dup
&& let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut()
{
ch.insert(0, Arc::new(Node::group(dup, vec![])));
}
nearest_agrees(&d, &ids, "a duplicate put in after the cache was built");
d.drop_lookup_cache();
nearest_agrees(&d, &ids, "a duplicate, cached afresh");
}
}
/// An id on the path that an earlier node of another kind also has: the earlier node is the one
/// tested, as `node` gives it.
#[test]
fn nearest_finder_tests_the_first_node_with_a_repeated_id() {
let mut d = Document::new(612.0, 792.0);
let layer = d.layers[0].id;
let leaf = |id: u64| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()));
d.insert(Some(layer), 0, Node::group(NodeId(500), vec![leaf(501)])).unwrap();
d.insert(Some(layer), 1, Node::path(NodeId(600), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())).unwrap();
// A group that has the path's id, after the path in tree order.
d.insert(Some(layer), 2, Node::group(NodeId(600), vec![leaf(601)])).unwrap();
let is_group = |n: &Node| matches!(n.kind, NodeKind::Group { .. });
for cached in [false, true] {
d.drop_lookup_cache();
if cached {
d.node(layer);
}
let mut find = d.nearest_finder();
assert_eq!(find.nearest(NodeId(501), is_group).map(|n| n.id), Some(NodeId(500)), "cached {cached}");
assert_eq!(find.nearest(NodeId(601), is_group).map(|n| n.id), None, "cached {cached}: id 600 is the path");
assert_eq!(find.nearest(NodeId(999_999), is_group).map(|n| n.id), None, "cached {cached}: not in the tree");
}
}
/// With the cache built, finding the nearest group of every object of a large tree looks no id up
/// and walks the tree no time.
#[test]
fn nearest_finder_reads_one_path_per_object() {
let mut d = Document::new(612.0, 792.0);
let layer = d.layers[0].id;
let mut leaves = vec![];
for g in 0..2_000 {
let kids: Vec<Arc<Node>> = (0..3)
.map(|_| {
let id = d.alloc_id();
leaves.push(id);
Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()))
})
.collect();
let gid = d.alloc_id();
d.insert(Some(layer), g, Node::group(gid, kids)).unwrap();
}
d.drop_lookup_cache();
d.node(layer);
let (lookups, walks) = (path_lookups(), tree_walks());
let mut find = d.nearest_finder();
let found = leaves.iter().filter(|id| find.nearest(**id, |n| matches!(n.kind, NodeKind::Group { .. })).is_some()).count();
assert_eq!(found, leaves.len());
assert_eq!(path_lookups() - lookups, 0, "lookups by id");
assert_eq!(tree_walks() - walks, 0, "walks of the tree");
}
+49 -1
View File
@@ -94,11 +94,59 @@ fn a_very_long_expression_reads_as_nothing() {
}
}
/// `x`, `X` and `×` multiply as `*` does (#8435), units and percentages included; a lowercase `x`
/// right after a `p` stays the `px` unit.
#[test]
fn x_is_a_multiplication_sign() {
let (mm, cm) = (72.0 / 25.4, 72.0 / 2.54);
for (u, s, want) in [
(Unit::Points, "10x2", 20.0),
(Unit::Points, "10 x 2", 20.0),
(Unit::Points, "10X2", 20.0),
(Unit::Points, "10×2", 20.0),
(Unit::Points, "10x-2", -20.0),
(Unit::Points, "10/2x5", 25.0),
(Unit::Points, "1+2x3", 7.0),
(Unit::Millimeters, "2x3 mm", 6.0 * mm),
(Unit::Points, "2x3mm", 6.0 * mm),
(Unit::Points, "3mm x 2", 6.0 * mm),
(Unit::Centimeters, "3cmx50%", 1.5 * cm),
(Unit::Points, "2p x 2", 48.0),
(Unit::Points, "10px", 10.0),
(Unit::Points, "2px x 3", 6.0),
(Unit::Points, "2pxx3", 6.0),
(Unit::Millimeters, "4x3 px", 12.0),
// Only a lowercase x after a p is the px suffix.
(Unit::Points, "2pX3", 72.0),
(Unit::Points, "2p×3", 72.0),
// Text that used to be refused now reads as a product.
(Unit::Points, "8.5x11 in", 93.5 * 72.0),
(Unit::Points, "0x10", 0.0),
] {
let got = u.parse(s).unwrap_or_else(|| panic!("{u:?} can't read `{s}`"));
assert!((got - want).abs() < 1e-9, "{u:?}: `{s}` → {got}, want {want}");
}
for s in ["x", "x2", "5x", "5 x x 2", "xx", "2px3"] {
assert_eq!(Unit::Points.parse(s), None, "{s}");
}
assert_eq!(crate::parse_number("45x2"), Some(90.0));
assert_eq!(crate::parse_number(" 45 X 2 "), Some(90.0));
assert_eq!(crate::parse_number("45×2"), Some(90.0));
assert_eq!(crate::parse_number("90x-1"), Some(-90.0));
assert_eq!(crate::parse_number("x"), None);
// Each sign counts toward the 128-sign limit as a `*` would.
assert_eq!(Unit::Points.parse(&format!("1{}", "x1".repeat(128))), Some(1.0));
assert_eq!(Unit::Points.parse(&format!("1{}", "x1".repeat(129))), None);
assert_eq!(crate::parse_number(&format!("1{}", "×1".repeat(129))), None);
assert_eq!(crate::arithmetic_signs("1+2x3X4×5*6/7-8"), 7);
assert_eq!(crate::arithmetic_signs("2px x 3"), 1);
}
proptest! {
/// Field text made of digits, operators, `%`, spaces and unit letters reads as a finite value
/// or as nothing and does not panic.
#[test]
fn arithmetic_text_reads_as_a_finite_value_or_nothing(s in "[0-9.+*/% ptxinmcfyd-]{0,24}") {
fn arithmetic_text_reads_as_a_finite_value_or_nothing(s in "[0-9.+*/% ptxXinmcfyd×-]{0,24}") {
for u in Unit::ALL {
if let Some(v) = u.parse(&s) {
prop_assert!(v.is_finite(), "{u:?}: `{s}` → {v}");
+9 -3
View File
@@ -32,10 +32,10 @@ pub use para_style::{
pub use runs::PATH_LEAD_MAX;
pub use runs::{INLINE_CHAR, INLINE_MAX_SCALE, InlineArt, RubyAlign, RubyPosition, RubySpan, TextKind, TextRun, TextStyleDef, TypeAntiAlias};
pub use tabs_lists::{
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, NumberStyle, ParaList, TabAlign,
TabStop,
Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList,
TabAlign, TabStop,
};
pub use wrap::{resolve_wrap, wrap_work};
pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work};
/// A text object. `runs` split into paragraphs at `\n`.
///
@@ -67,6 +67,12 @@ pub struct TextObject {
/// it on a frame that leaves its thread and on a copy. Not saved.
#[serde(skip)]
pub first_para_continues: bool,
/// Threaded text whose first paragraph continues ([`TextObject::first_para_continues`]): the
/// last character of that paragraph in the frames before that a repeat mark could stand for
/// (Kurikaeshi Moji Shori), or None. The engine sets it with `first_para_continues`; layout
/// reads it only while `first_para_continues` is on. Not saved.
#[serde(skip)]
pub first_para_lead: Option<char>,
/// Area Type Options (area type only).
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
pub area: AreaOptions,
+55 -11
View File
@@ -27,7 +27,11 @@ impl TextObject {
/// Character attributes as presented by controls (stored runs stay local for layout
/// and rich-text clipboard operations). Explicit vertical character scale stays separate.
pub fn effective_char_style(&self, style: &CharStyle) -> Option<CharStyle> {
let scale = self.style_scale()?;
Self::scaled_char_style(style, self.style_scale()?)
}
/// `style` with `scale` taken into its attributes ([`Self::effective_char_style`]).
fn scaled_char_style(style: &CharStyle, scale: TextStyleScale) -> Option<CharStyle> {
let mut style = style.clone();
style.size *= scale.points;
style.leading = style.leading.map(|v| v * scale.points);
@@ -57,19 +61,27 @@ impl TextObject {
/// scale from `xf`, so panels show document-point sizes without a separate transform factor.
/// Returns `false` when there is nothing to bake (identity scale or an unrepresentable
/// transform).
///
/// Type on a path bakes only the uniform part of the scale (the vertical one) and keeps any
/// stretch in `xf`: its brackets and glyphs sit at fractions of the path's length, which a
/// non-uniform scale of the path would move, and a uniform one keeps.
pub fn scale_text_attributes(&mut self) -> bool {
let Some(scale) = self.style_scale() else { return false };
if (scale.points - 1.0).abs() <= 1e-12 && (scale.horizontal - 1.0).abs() <= 1e-12 {
let Some(mut scale) = self.style_scale() else { return false };
let [a, b, c, d, _, _] = self.xf.as_coeffs();
let (mut sx, sy) = (a.hypot(b), c.hypot(d));
if sx <= 1e-12 || sy <= 1e-12 {
return false;
}
let [a, b, c, d, _, _] = self.xf.as_coeffs();
let (sx, sy) = (a.hypot(b), c.hypot(d));
if sx <= 1e-12 || sy <= 1e-12 {
if matches!(self.kind, TextKind::OnPath { .. }) {
scale.horizontal = 1.0;
sx = sy;
}
if (scale.points - 1.0).abs() <= 1e-12 && (scale.horizontal - 1.0).abs() <= 1e-12 {
return false;
}
let mut baked = Vec::with_capacity(self.runs.len());
for run in &self.runs {
let Some(eff) = self.effective_char_style(&run.style) else { return false };
let Some(eff) = Self::scaled_char_style(&run.style, scale) else { return false };
baked.push(eff);
}
for (run, style) in self.runs.iter_mut().zip(baked) {
@@ -78,6 +90,14 @@ impl TextObject {
// Character strokes are drawn in text space: widen them by the vertical scale we remove.
self.scale_char_strokes(1.0 / sy);
self.xf *= Affine::scale_non_uniform(1.0 / sx, 1.0 / sy);
// An area's frame and a path type's path are drawn through `xf` too: give them the scale
// `xf` loses, so the frame (and so the line breaks) and the path stay where they were.
let grow = Affine::scale_non_uniform(sx, sy);
match &mut self.kind {
TextKind::Area { frame } => frame.transform(grow),
TextKind::OnPath { path, .. } => path.transform(grow),
TextKind::Point => {}
}
self.cached_bounds = None;
self.cached_baselines.clear();
self.cached_ink = None;
@@ -94,6 +114,7 @@ impl TextObject {
para: ParaStyle::default(),
paras: Vec::new(),
first_para_continues: false,
first_para_lead: None,
area: AreaOptions::default(),
path_effect: PathEffect::default(),
path_align: PathAlign::default(),
@@ -283,17 +304,40 @@ impl TextObject {
/// Update the paragraph styles for replacing bytes `start..end` of the current plain text by
/// `insert` (call before changing the runs). The paragraph the range starts in keeps its
/// style (merging paragraphs: the first one's wins); paragraphs the insertion starts take that
/// style too (Return continues the paragraph it splits); later paragraphs keep theirs.
/// style too (Return continues the paragraph it splits), without the number its list gives it
/// ([`ParaList::start`]); later paragraphs keep theirs. When an insertion that starts new
/// paragraphs is made at the start of a paragraph and some of that paragraph's text stays
/// after it, that number moves with the text to the last paragraph the insertion starts.
pub fn splice_paras(&mut self, start: usize, end: usize, insert: &str) {
if self.paras.is_empty() {
let added = insert.bytes().filter(|&b| b == b'\n').count();
let numbered = |p: &ParaStyle| p.list.is_some_and(|l| l.start.is_some());
// With one style for every paragraph, the new paragraphs take it as it is unless its list
// gives the paragraph a number.
if self.paras.is_empty() && (added == 0 || !numbered(&self.para)) {
return;
}
let r = self.paragraphs_in(start, end);
let v = self.paragraph_styles();
let Some(keep) = v.get(r.start).cloned() else { return };
let added = insert.bytes().filter(|&b| b == b'\n').count();
let Some(mut keep) = v.get(r.start).cloned() else { return };
let given = keep.list.and_then(|l| l.start);
if let Some(l) = keep.list.as_mut() {
l.start = None;
}
let mut out: Vec<ParaStyle> = v.iter().take(r.start + 1).cloned().collect();
out.extend(std::iter::repeat_n(keep, added));
let text = self.plain_text();
let (at, to) = (start.min(end).min(text.len()), start.max(end).min(text.len()));
let at_para_start = text.as_bytes().get(..at).is_some_and(|b| b.last().is_none_or(|&c| c == b'\n'));
// The paragraph's text after the replaced bytes, which the last new paragraph then holds.
let text_kept = r.len() == 1 && text.as_bytes().get(to).is_some_and(|&c| c != b'\n');
if given.is_some() && added > 0 && at_para_start && text_kept {
if let Some(l) = out.get_mut(r.start).and_then(|p| p.list.as_mut()) {
l.start = None;
}
if let Some(l) = out.last_mut().and_then(|p| p.list.as_mut()) {
l.start = given;
}
}
out.extend(v.iter().skip(r.end).cloned());
self.paras = out;
if let Some(first) = self.paras.first() {
+11
View File
@@ -271,6 +271,9 @@ pub struct ParaStyle {
/// dashes, two ellipses, two two-dot leaders, a vertical kana repeat mark's two halves). Kept
/// with kinsoku None, where it has no effect. Off by default.
pub bunri_kinshi: bool,
/// Kurikaeshi Moji Shori (Paragraph panel menu): a repeat mark (々, ゝ, ゞ, ヽ or ヾ) that starts
/// a line is drawn as the character it repeats, and the text keeps the mark. Off by default.
pub kurikaeshi_moji_shori: bool,
/// Roman Hanging Punctuation (Paragraph panel menu): quotation marks, hyphens, full stops and
/// commas starting or ending a line hang outside the margin, and asterisks, tildes, ellipses,
/// dashes, colons and semicolons hang by half. East Asian punctuation hangs by burasagari.
@@ -375,6 +378,8 @@ struct ParaStyleFile {
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
bunri_kinshi: bool,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
kurikaeshi_moji_shori: bool,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
roman_hanging: bool,
#[serde(default, skip_serializing_if = "crate::skip::is_default")]
kashida: Kashida,
@@ -412,6 +417,7 @@ impl From<ParaStyle> for ParaStyleFile {
kinsoku,
kinsoku_type,
bunri_kinshi,
kurikaeshi_moji_shori,
roman_hanging,
kashida,
korean_line_break_anywhere,
@@ -439,6 +445,7 @@ impl From<ParaStyle> for ParaStyleFile {
kinsoku,
kinsoku_type,
bunri_kinshi,
kurikaeshi_moji_shori,
roman_hanging,
kashida,
korean_line_break_anywhere,
@@ -470,6 +477,7 @@ impl From<ParaStyleFile> for ParaStyle {
kinsoku,
kinsoku_type,
bunri_kinshi,
kurikaeshi_moji_shori,
roman_hanging,
kashida,
korean_line_break_anywhere,
@@ -496,6 +504,7 @@ impl From<ParaStyleFile> for ParaStyle {
kinsoku,
kinsoku_type,
bunri_kinshi,
kurikaeshi_moji_shori,
roman_hanging,
kashida,
korean_line_break_anywhere,
@@ -622,6 +631,8 @@ pub enum FirstBaseline {
XHeight,
/// The first line's leading.
Leading,
/// The top of the first line's ideographic em box touches the frame top.
EmBoxHeight,
/// Exactly `first_baseline_min` below the top.
Fixed,
}
+38 -5
View File
@@ -206,15 +206,41 @@ pub struct ParaList {
/// ([`Self::depth`]). The file saves it only when it is not 1.
#[serde(skip_serializing_if = "is_first_level", deserialize_with = "read_level")]
pub level: u8,
/// The number a numbered paragraph is given, 1 to [`MAX_LIST_START`]: the numbered paragraphs
/// after it at its level count on from it ([`Self::next_marker`]). None: it counts on from the
/// numbered paragraph before it. A bulleted paragraph does not use it. A paragraph made
/// with Return in a paragraph that has one does not take it, and a paragraph style does not
/// keep it. A saved number outside the range is read as the nearest one. The file saves it
/// only when it is set.
#[serde(skip_serializing_if = "Option::is_none", deserialize_with = "read_start")]
pub start: Option<u32>,
}
impl Default for ParaList {
/// A bulleted list with a dot, its marker aligned left, at level 1.
/// A bulleted list with a dot, its marker aligned left, at level 1, numbered on from the
/// paragraph before.
fn default() -> Self {
Self { bullet: Bullet::default(), number: None, align: ListAlign::default(), level: 1 }
Self { bullet: Bullet::default(), number: None, align: ListAlign::default(), level: 1, start: None }
}
}
/// The largest number a numbered paragraph can be given ([`ParaList::start`]).
pub const MAX_LIST_START: u32 = 999_999_999;
/// Reads a saved list start, a whole number or null, as the nearest of 1 to [`MAX_LIST_START`],
/// so a start such as 0 or 5000000000 opens the file at 1 or [`MAX_LIST_START`]. Anything else
/// is an error.
fn read_start<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u32>, D::Error> {
let start = match serde_json::Value::deserialize(d)? {
serde_json::Value::Null => return Ok(None),
serde_json::Value::Number(n) if n.is_i64() || n.is_u64() => {
n.as_i64().map_or(i64::from(MAX_LIST_START), |n| n.clamp(1, i64::from(MAX_LIST_START)))
}
_ => return Err(serde::de::Error::custom("a list start must be a whole number")),
};
Ok(u32::try_from(start).ok())
}
/// Is `level` the first list level, which the file does not save?
fn is_first_level(level: &u8) -> bool {
*level == 1
@@ -307,6 +333,12 @@ impl ParaList {
Self { level, ..self }
}
/// This list with the paragraph numbered `start` (1 to [`MAX_LIST_START`]; None: on from the
/// paragraph before).
pub fn starting_at(self, start: Option<u32>) -> Self {
Self { start, ..self }
}
/// The list's level, 1 to [`LIST_LEVELS`]: [`Self::level`], a value outside the range taken
/// as the nearest level.
pub fn depth(&self) -> usize {
@@ -334,8 +366,9 @@ impl ParaList {
/// paragraph has none and leaves the counts as they are. A paragraph with text sets the counts
/// of the levels deeper than its own back to 0, so a deeper paragraph after it counts from 1
/// again; a bulleted one has its bullet and leaves the count of its level as it is, and a
/// numbered one adds one to the count of its level and is numbered with it. A paragraph back
/// at a shallower level then goes on with that level's count.
/// numbered one adds one to the count of its level and is numbered with it, or with the number
/// it is given ([`Self::start`]), which becomes the count of its level. A paragraph back at a
/// shallower level then goes on with that level's count.
pub fn next_marker(list: Option<ParaList>, empty: bool, counts: &mut ListCounts) -> Option<String> {
let Some(list) = list else {
*counts = ListCounts::default();
@@ -350,7 +383,7 @@ impl ParaList {
}
let count = &mut counts.0[level];
if list.number.is_some() {
*count = count.saturating_add(1);
*count = list.start.map_or_else(|| count.saturating_add(1), |s| s.clamp(1, MAX_LIST_START));
}
Some(list.marker(*count))
}
+107
View File
@@ -456,6 +456,99 @@ fn list_levels_count_their_own_numbers_and_save_only_past_the_first() {
assert_eq!(opened.list_level_counts, (1..=8).collect::<Vec<u32>>(), "a file keeps only the counts of levels 2 to 9");
}
/// A numbered paragraph given a number shows it, and the numbered paragraphs after it at its level
/// count on from it; deeper levels still count from 1 after it, a bulleted or empty paragraph does
/// not use the number, and a paragraph in no list still starts the count again. The file saves the
/// number only when it is set, and a saved number outside 1 to 999999999 reads as the nearest one.
#[test]
fn a_numbered_paragraph_given_a_number_starts_its_level_count_there() {
let num = |level, start| Some(ParaList::numbered(NumberStyle::Arabic).at_level(level).starting_at(start));
let dot = Some(ParaList::bulleted(Bullet::Dot).starting_at(Some(7)));
let mut counts = ListCounts::default();
let markers: Vec<Option<String>> = [
(num(1, None), false),
(num(1, Some(5)), false),
(num(1, None), false),
(num(2, None), false),
(num(2, Some(1)), false),
(num(2, None), false),
(num(1, None), false),
(num(1, Some(9)), true),
(num(1, None), false),
(dot, false),
(num(1, Some(1)), false),
(None, false),
(num(1, None), false),
]
.iter()
.map(|&(l, empty)| ParaList::next_marker(l, empty, &mut counts))
.collect();
let want = ["1.", "5.", "6.", "1.", "1.", "2.", "7.", "", "8.", "\u{2022}", "1.", "", "1."];
assert_eq!(markers.iter().map(|m| m.as_deref().unwrap_or("")).collect::<Vec<_>>(), want);
let mut counts = ListCounts::default();
let roman = Some(ParaList::numbered(NumberStyle::UpperRoman).starting_at(Some(MAX_LIST_START)));
assert_eq!(ParaList::next_marker(roman, false, &mut counts).as_deref(), Some("999999999."));
let zero = Some(ParaList::numbered(NumberStyle::Arabic).starting_at(Some(0)));
assert_eq!(ParaList::next_marker(zero, false, &mut counts).as_deref(), Some("1."), "a number below 1 counts as 1");
assert_eq!(serde_json::to_value(num(1, None)).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic"}));
assert_eq!(serde_json::to_value(num(1, Some(5))).unwrap(), serde_json::json!({"bullet": "dot", "number": "arabic", "start": 5}));
let read = |v: serde_json::Value| serde_json::from_value::<ParaList>(v).unwrap().start;
assert_eq!(read(serde_json::json!({"number": "arabic", "start": 5})), Some(5));
assert_eq!(read(serde_json::json!({"number": "arabic"})), None);
assert_eq!(read(serde_json::json!({"number": "arabic", "start": null})), None);
let starts = [serde_json::json!(0), serde_json::json!(-3), serde_json::json!(5_000_000_000_u64), serde_json::json!(u64::MAX)];
assert_eq!(
starts.map(|s| read(serde_json::json!({ "number": "arabic", "start": s }))),
[Some(1), Some(1), Some(MAX_LIST_START), Some(MAX_LIST_START)],
"a saved number outside 1 to 999999999 reads as the nearest one"
);
for bad in [serde_json::json!(2.5), serde_json::json!("5"), serde_json::json!(true)] {
assert!(serde_json::from_value::<ParaList>(serde_json::json!({ "start": bad })).is_err(), "{bad}");
}
}
/// Return in a paragraph that its list gives a number makes paragraphs without it, also while
/// every paragraph shares one style; Return at the start of its text moves the number with the
/// text, and Return elsewhere leaves it where it was.
#[test]
fn return_does_not_copy_a_paragraphs_number() {
let five = ParaStyle { list: Some(ParaList::numbered(NumberStyle::Arabic).starting_at(Some(5))), ..ParaStyle::default() };
let starts = |t: &TextObject| t.paragraph_styles().iter().map(|p| p.list.and_then(|l| l.start)).collect::<Vec<_>>();
// One style for the whole text: Return after "one" splits it.
let mut t = TextObject::point(Point::ZERO, "onetwo", CharStyle::default());
t.set_all_paras(five);
t.splice_paras(3, 3, "\n");
t.runs[0].text.insert(3, '\n');
t.normalize_paras();
assert_eq!(starts(&t), [Some(5), None]);
assert!(t.para_at(1).list.is_some_and(|l| l.number == Some(NumberStyle::Arabic)), "the new paragraph stays in the list");
// Return at the start of "two" (a paragraph with a number of its own): the number moves on
// with the text, and the empty paragraph left before it has none.
t.edit_paras(Some(1..2), |p| p.list = p.list.map(|l| l.starting_at(Some(8))));
t.splice_paras(4, 4, "\n\n");
t.runs[0].text.insert_str(4, "\n\n");
t.normalize_paras();
assert_eq!(t.plain_text(), "one\n\n\ntwo");
assert_eq!(starts(&t), [Some(5), None, None, Some(8)]);
// A whole paragraph pasted at the start of "two": the number stays with "two".
t.splice_paras(6, 6, "Pasted\n");
t.runs[0].text.insert_str(6, "Pasted\n");
t.normalize_paras();
assert_eq!(t.plain_text(), "one\n\n\nPasted\ntwo");
assert_eq!(starts(&t), [Some(5), None, None, None, Some(8)]);
// "two" replaced by two paragraphs: none of its text is left, so the first new one keeps it.
t.splice_paras(13, 16, "A\nB");
t.runs[0].text.replace_range(13..16, "A\nB");
t.normalize_paras();
assert_eq!(t.plain_text(), "one\n\n\nPasted\nA\nB");
assert_eq!(starts(&t), [Some(5), None, None, None, Some(8), None]);
// Text without a number keeps one style for every paragraph.
let mut t = TextObject::point(Point::ZERO, "onetwo", CharStyle::default());
t.set_all_paras(ParaStyle { list: Some(ParaList::numbered(NumberStyle::Arabic)), ..ParaStyle::default() });
t.splice_paras(3, 3, "\n");
assert!(t.paras.is_empty());
}
/// In a threaded frame whose first paragraph continues from the frame before, the text at the
/// frame's start is not the start of a paragraph, so typing a list's start there starts nothing.
/// The paragraphs after it still start lists.
@@ -554,6 +647,20 @@ fn text_flow_is_saved_only_when_by_rows() {
assert!(serde_json::from_value::<AreaOptions>(serde_json::json!({"flow": "diagonal"})).is_err());
}
/// First Baseline Em Box Height saves as `emBoxHeight` with its minimum and reads back; files from
/// before it read their own first baseline as they did, Ascent when they have none.
#[test]
fn em_box_height_first_baseline_is_saved_and_read_back() {
let set = AreaOptions { first_baseline: FirstBaseline::EmBoxHeight, first_baseline_min: 9.0, ..AreaOptions::default() };
let saved = serde_json::to_value(&set).unwrap();
assert_eq!((saved["firstBaseline"].as_str(), saved["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(9.0)));
assert_eq!(serde_json::from_value::<AreaOptions>(saved).unwrap(), set);
let old = serde_json::json!({"firstBaseline": "leading", "firstBaselineMin": 3.0});
assert_eq!(serde_json::from_value::<AreaOptions>(old).unwrap().first_baseline, FirstBaseline::Leading);
assert_eq!(serde_json::from_value::<AreaOptions>(serde_json::json!({})).unwrap().first_baseline, FirstBaseline::Ascent);
assert!(serde_json::from_value::<AreaOptions>(serde_json::json!({"firstBaseline": "emBox"})).is_err());
}
/// 120 × 40 area type at (40, 40), its text drawn at twice its size.
fn area_type() -> TextObject {
let mut t = TextObject::point(Point::ZERO, "Some text", CharStyle::default());
+68 -34
View File
@@ -4,7 +4,7 @@ use std::sync::Arc;
use vectorcraft_geom::{PathData, shapes};
use super::{TextKind, WrapShape};
use super::{TextKind, TextObject, WrapShape};
use crate::{Document, Node, NodeId, NodeKind};
/// Outline of a wrap object in document coordinates: its paths, or its bounds for other art.
@@ -32,6 +32,16 @@ fn outline(n: &Node, out: &mut PathData) {
}
}
/// The outline area type wraps around for wrap object `n`, in document coordinates, as
/// [`resolve_wrap`] makes it: a path's subpaths that are closed or have more than two anchors, those
/// of the shown members of a group or compound path, a clip group's clipping object's, and the
/// bounds of other art. Empty when `n` has none.
pub fn wrap_outline(n: &Node) -> PathData {
let mut pd = PathData::default();
outline(n, &mut pd);
pd
}
enum Item<'a> {
Wrap(&'a Node),
Text(&'a Node),
@@ -82,6 +92,57 @@ pub fn wrap_work(doc: &Document) -> usize {
total
}
/// Each area text object of `layer`, from the top down, with the wrap objects above it in the
/// layer whose outlines aren't empty, topmost first, each with the shape its outline makes in
/// document coordinates. Each wrap object's outline is made once.
fn each_text<'a>(layer: &'a Node, mut f: impl FnMut(&'a Node, &[(&'a Node, WrapShape)])) {
let mut items = vec![];
collect(layer, &mut items);
let mut above: Vec<(&Node, WrapShape)> = vec![];
for it in items.iter().rev() {
match it {
Item::Wrap(n) => {
let mut pd = PathData::default();
outline(n, &mut pd);
if !pd.is_empty() {
above.push((n, WrapShape { path: pd, wrap: n.extras().wrap.unwrap_or_default() }));
}
}
Item::Text(n) => f(n, &above),
}
}
}
/// The wrap shapes of text object `t` (text space) from `above`, the wrap objects above it as
/// [`each_text`] gives them: bottom first.
fn shapes_of(t: &TextObject, above: &[(&Node, WrapShape)]) -> Vec<WrapShape> {
let inv = t.xf.inverse();
above
.iter()
.rev()
.map(|(_, s)| {
let mut path = s.path.clone();
path.transform(inv);
WrapShape { path, wrap: s.wrap }
})
.collect()
}
/// Each area text object on `doc`'s layers that [`resolve_wrap`] gives wrap shapes, with the wrap
/// objects whose outlines make them, bottom first, and those shapes (text space), as
/// [`resolve_wrap`] works them out. The copying is [`wrap_work`].
pub fn wrap_sources<'a>(doc: &'a Document, mut f: impl FnMut(&'a Node, Vec<&'a Node>, Vec<WrapShape>)) {
for layer in &doc.layers {
each_text(layer, |n, above| {
if let NodeKind::Text(t) = &n.kind
&& !above.is_empty()
{
f(n, above.iter().rev().map(|(s, _)| *s).collect(), shapes_of(t, above));
}
});
}
}
/// Resolve the wrap shapes (`TextObject::wrap`, text space) of each area text object from the
/// outlines of the wrap objects above it in its layer. With `before`, the layers it holds unchanged
/// are skipped; without it, every layer is resolved. Returns the area text objects whose shapes
@@ -95,41 +156,14 @@ pub fn resolve_wrap(before: Option<&Document>, doc: &mut Document) -> Vec<NodeId
{
continue;
}
let mut items = vec![];
collect(layer, &mut items);
if items.is_empty() {
continue;
}
// From the top down, each wrap object's outline is made once; each area text object takes
// those above it, bottom first.
let mut above: Vec<WrapShape> = vec![];
for it in items.iter().rev() {
match it {
Item::Wrap(n) => {
let mut pd = PathData::default();
outline(n, &mut pd);
if !pd.is_empty() {
above.push(WrapShape { path: pd, wrap: n.extras().wrap.unwrap_or_default() });
}
}
Item::Text(n) => {
let NodeKind::Text(t) = &n.kind else { continue };
let inv = t.xf.inverse();
let shapes: Vec<WrapShape> = above
.iter()
.rev()
.map(|s| {
let mut path = s.path.clone();
path.transform(inv);
WrapShape { path, wrap: s.wrap }
})
.collect();
if shapes != t.wrap {
updates.push((n.id, shapes));
}
each_text(layer, |n, above| {
if let NodeKind::Text(t) = &n.kind {
let shapes = shapes_of(t, above);
if shapes != t.wrap {
updates.push((n.id, shapes));
}
}
}
});
}
let mut changed = Vec::with_capacity(updates.len());
for (id, shapes) in updates {
+97 -5
View File
@@ -81,6 +81,21 @@ impl Unit {
Unit::Ha => "H",
}
}
/// Whether this unit is a physical measurement unit (not points or pixels).
pub fn is_physical(self) -> bool {
self.svg_suffix().is_some() || matches!(self, Unit::FeetInches | Unit::Meters | Unit::Yards | Unit::Feet | Unit::Q | Unit::Ha)
}
/// The standard SVG length unit suffix, if this unit is a physical unit supported in SVG
/// (`mm`, `cm`, `in`, `pc`).
pub fn svg_suffix(self) -> Option<&'static str> {
match self {
Unit::Millimeters => Some("mm"),
Unit::Centimeters => Some("cm"),
Unit::Inches => Some("in"),
Unit::Picas => Some("pc"),
_ => None,
}
}
pub const fn label(self) -> &'static str {
match self {
Unit::Points => "Points",
@@ -157,12 +172,17 @@ impl Unit {
/// that share of everything before it (`50pt+25%` is 62.5 pt, `100pt+20pt-50%` is 60 pt). A
/// percentage on its own (`50%`) reads as nothing.
///
/// Text with more than 128 `+ - * /` signs reads as nothing.
/// `x`, `X` and `×` multiply as `*` does (`10x2` is 20, `2x3 mm` is 6 mm), except a lowercase
/// `x` right after a `p`, which is the `px` suffix (`2px x 3` is 6 px, and `2px3` reads as
/// nothing; write `2p x 3` for picas). `X` and `×` after a `p` multiply (`2pX3` is 6 picas).
///
/// Text with more than 128 `+ - * /` signs ([`arithmetic_signs`], a multiplication sign counted
/// as `*`) reads as nothing.
pub fn parse(self, s: &str) -> Option<f64> {
if s.chars().filter(|c| matches!(c, '+' | '-' | '*' | '/')).count() > MAX_MEASURE_OPERATORS {
if arithmetic_signs(s) > MAX_MEASURE_OPERATORS {
return None;
}
parse_measure(s, self).filter(|v| v.is_finite())
parse_measure(&times_as_asterisks(s), self).filter(|v| v.is_finite())
}
/// The value naming this unit in the Units preferences (`points`, `millimeters`,
/// `feetInches`).
@@ -215,6 +235,46 @@ impl Unit {
/// The most `+ - * /` signs [`Unit::parse`] reads in one text.
const MAX_MEASURE_OPERATORS: usize = 128;
/// The number of `+ - * /` signs in `s`, each multiplication sign typed as `x`, `X` or `×`
/// ([`Unit::parse`]) counted as a `*`.
pub fn arithmetic_signs(s: &str) -> usize {
let mut prev = None;
s.chars()
.filter(|&c| {
let sign = matches!(c, '+' | '-' | '*' | '/') || is_times(c, prev);
prev = Some(c);
sign
})
.count()
}
/// Is `c`, after `prev`, a multiplication sign typed as `x`, `X` or `×`? A lowercase `x` right
/// after a `p` is the `px` suffix (`2px x 3`), also where a number follows it (`2px3`).
fn is_times(c: char, prev: Option<char>) -> bool {
matches!(c, 'X' | '×') || (c == 'x' && prev != Some('p'))
}
/// `s` with each multiplication sign ([`is_times`]) written as `*` (`10 x 2` is `10 * 2`); text
/// without one is not copied.
fn times_as_asterisks(s: &str) -> std::borrow::Cow<'_, str> {
let mut prev = None;
let any = s.chars().any(|c| {
let times = is_times(c, prev);
prev = Some(c);
times
});
if !any {
return s.into();
}
let mut out = String::with_capacity(s.len());
let mut prev = None;
for c in s.chars() {
out.push(if is_times(c, prev) { '*' } else { c });
prev = Some(c);
}
out.into()
}
fn parse_measure(s: &str, default: Unit) -> Option<f64> {
let s = s.trim();
// Simple arithmetic on the right (Illustrator fields accept "10+5", "100/2", "3in*2").
@@ -316,10 +376,42 @@ fn percent(s: &str) -> Option<f64> {
}
}
/// `text` typed in a numeric field, with a decimal comma read as a point: `0,1 mm` is `0.1 mm`
/// (#3837), and each number of a sum reads its own separator, so `100.5 mm-0,5` (a comma typed
/// after the value the field shows) is 100 mm (#5684). A number written with both separators has
/// two points once read, so `1,000.5` and `1.234,5` are refused rather than guessed at; so is a
/// number that reads as thousands ([`thousands`]).
pub fn decimal_point(text: &str) -> std::borrow::Cow<'_, str> {
if text.contains(',') && !thousands(text) { text.replace(',', ".").into() } else { text.into() }
}
/// Is `text` a number written with a thousands comma, as `1,000`, `+1,000`, `12,500 mm` or
/// `1,000"`: a sign, one to three digits (not a lone 0), a comma, exactly three digits, then at
/// most a unit? Read as a decimal it would be a thousand times too small, so the field refuses it
/// instead (`0,125` and `1,25` are decimals).
fn thousands(text: &str) -> bool {
let number = text.trim();
let number = number.strip_prefix(['+', '-']).unwrap_or(number);
let Some((whole, rest)) = number.split_once(',') else { return false };
let (part, unit) = rest.split_at(rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len()));
(1..=3).contains(&whole.len())
&& whole.bytes().all(|b| b.is_ascii_digit())
&& !whole.starts_with('0')
&& part.len() == 3
&& unit.trim().chars().all(|c| c.is_alphabetic() || c == '"' || c == '\'')
}
/// Is the length `pt` (points) a finite number in every unit of [`Unit::EAST_ASIAN`]? A length
/// near the largest number in points is too large in Q and Ha.
pub fn finite_in_every_unit(pt: f64) -> bool {
pt.is_finite() && Unit::EAST_ASIAN.iter().all(|u| u.from_pt(pt).is_finite())
}
/// A unitless field value (percent, degrees, counts) with the same `+ - * /` arithmetic as
/// [`Unit::parse`] (`45*2`, `100/3`); text other than digits, `.` and operators reads as nothing.
/// [`Unit::parse`] (`45*2`, `45x2`, `100/3`); text other than digits, `.` and operators reads as
/// nothing.
pub fn parse_number(s: &str) -> Option<f64> {
if !s.chars().all(|c| c.is_ascii_digit() || " .+-*/".contains(c)) {
if !s.chars().all(|c| c.is_ascii_digit() || " .+-*/xX×".contains(c)) {
return None;
}
// A leading `+` is a sign (`+5`), as a plain number read it.
+3 -3
View File
@@ -17,10 +17,10 @@ vectorcraft-text = { workspace = true }
vectorcraft-plugins = { workspace = true }
vectorcraft-trace = { workspace = true }
image = { workspace = true }
craft-image-codecs = { workspace = true }
kurbo = { workspace = true }
# Effect › SVG Filters draws its filters with resvg (MIT OR Apache-2.0), at the usvg version the
# workspace reads SVG with; raster-images decodes the object's pixels it hands the filter as a PNG.
resvg = { version = "0.48", default-features = false, features = ["raster-images"] }
# Effect › SVG Filters draws its filters with craft-svg's resvg (`tree-render`).
craft-svg = { workspace = true, features = ["tree-render"] }
# The number lists of filter attributes, read as usvg reads them (MIT OR Apache-2.0; already used by usvg).
svgtypes = "0.16"
serde_json = { workspace = true }
+31 -23
View File
@@ -28,7 +28,8 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Vec2};
use crate::distort::{transform_move, transform_offsets};
use crate::group::{has_own_paint, paints};
use crate::reshape::{
as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, paint_type_clip, reshape_leaves,
as_art, clip_region_path, clipping_text_outline, dressed, geometry_effects, glyph_outlines, knockout_inside, outline_nested_text,
paint_type_clip, reshape_leaves,
};
use crate::{
GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry,
@@ -167,7 +168,7 @@ struct Placing {
layers: WrittenLayers,
}
/// The layers an exporter writes besides the shown, printing ones
/// The layers and objects an exporter writes besides the shown, printing ones
/// ([`bake_document_placing_symbols`]). Template layers are never written.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct WrittenLayers {
@@ -175,16 +176,19 @@ pub struct WrittenLayers {
pub hidden: bool,
/// Layers that do not print.
pub non_printing: bool,
/// Hidden objects other than layers (written hidden, as SVG writes them when it keeps hidden
/// layers).
pub hidden_objects: bool,
}
/// Does the export leave `n` and everything in it out, while [`bake_document_placing_symbols`]
/// bakes? A hidden object other than a layer, a template layer, and a hidden layer or a layer
/// bakes? A template layer, and a hidden object other than a layer, a hidden layer or a layer
/// that does not print when the export leaves those out ([`WrittenLayers`]).
fn unwritten(n: &Node) -> bool {
PLACING.with(|p| {
p.borrow().as_ref().is_some_and(|p| match n.kind {
NodeKind::Layer { template, printable, .. } => template || !(printable || p.layers.non_printing) || !(n.visible || p.layers.hidden),
_ => !n.visible,
_ => !(n.visible || p.layers.hidden_objects),
})
})
}
@@ -499,13 +503,7 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option<Node> {
{
return None;
}
let (bp, rule) = crate::clip_outline(first)?;
let mut clip = Node::path(first.id, PathData::from_bezpath(&bp), Appearance::default());
if let NodeKind::Path { rule: r, clipping, .. } = &mut clip.kind {
(*r, *clipping) = (rule, true);
}
clip.name = first.name.clone();
clip.visible = first.visible;
let clip = clip_region_path(first)?;
let paint = first.clip_paint();
// The type's fills and strokes as art: baked with the type's id, as the renderer draws them,
// then given ids of their own.
@@ -529,7 +527,8 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option<Node> {
return Some(m);
};
// `n` keeps its id, name and transparency, and holds the clip group and the strokes over it.
let inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true });
let mut inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true });
knockout_inside(&mut m, &mut inner);
match &mut m.kind {
NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } => {
*children = vec![Arc::new(inner), stroke];
@@ -680,9 +679,11 @@ fn apart(offsets: &[Vec2], b: Rect) -> bool {
/// Type `n` whose own geometry effects only move it ([`transform_moves`]) as a group of the moved
/// type ([`moved_type`]). The group keeps `n`'s id, name, visibility, transparency, opacity mask and
/// remaining (raster) effects, and the type in it has none of them. `None` otherwise.
/// remaining (raster) effects, and the type in it has none of them. `None` otherwise, and for type
/// whose copies each carry the raster effects listed before their Transform effect
/// ([`crate::outer_effects`]), which is baked through its outlines as the canvas draws it.
fn moved_type_group(n: &Node) -> Option<Node> {
if !matches!(n.kind, NodeKind::Text(_)) {
if !matches!(n.kind, NodeKind::Text(_)) || crate::reshape::copied_raster_at(n).is_some() {
return None;
}
let moves = transform_moves(&geometry_effects(n))?;
@@ -715,7 +716,9 @@ fn moved_type_group(n: &Node) -> Option<Node> {
/// Type in a clipping path, other type that [`moved_type`] doesn't copy, and type inside live
/// objects or inside groups with Pathfinder or geometry effects or fills and strokes that paint, is
/// outlined as [`evaluate_container`] outlines it, and the other members become what it makes of
/// them. `None` when no type stays type.
/// them. `None` when no type stays type, and for a group or layer whose copies each carry the raster
/// effects listed before their Transform effect ([`crate::outer_effects`]), which is baked as the
/// canvas draws it ([`evaluate_container`]).
fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
fn keep(d: &Document, n: &mut Node, moves: &[serde_json::Value], clipping: bool, kept: &mut bool) {
if !clipping {
@@ -751,7 +754,11 @@ fn container_keeping_type(d: &Document, n: &Node) -> Option<Node> {
}
}
}
if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) || has_pathfinder(n) || has_own_paint(n) {
if !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })
|| has_pathfinder(n)
|| has_own_paint(n)
|| crate::reshape::copied_container_raster_at(n).is_some()
{
return None;
}
let fx = geometry_effects(n);
@@ -1041,13 +1048,14 @@ pub fn bake_document(doc: &Document) -> Option<Document> {
/// (live geometry effects, color adjustments and the rest [`needs_bake`] counts, in its own art or
/// in the art of the symbols it places) replaced by that art as the instance places it, baked
/// ([`placed_symbol_art`]), so the art draws as on the canvas wherever the instance is. For
/// exporters that write each instance's art in its place (PDF, print, EPS, DXF), rather than
/// writing each symbol once. `clip_slices`: whether 9-slice cells are clipped
/// ([`Document::place_symbol_art`]) or not ([`Document::place_symbol_art_unclipped`]), as the
/// exporter places other instances. `layers`: the hidden layers and layers that do not print
/// that the exporter writes. Instances the export does not write (hidden ones, those in hidden
/// objects, on template layers, and on the layers `layers` leaves out) stay as they are. The
/// symbols' own art is left as it is.
/// exporters that write each instance's art in its place (PDF, print, EPS, DXF, EMF, WMF), and
/// for SVG, which writes the instances of other symbols as one shared definition. `clip_slices`:
/// whether 9-slice cells are clipped ([`Document::place_symbol_art`]) or not
/// ([`Document::place_symbol_art_unclipped`]), as the exporter places other instances. `layers`:
/// the hidden layers, layers that do not print and hidden objects that the exporter writes.
/// Instances the export does not write (template layers, and the hidden objects and layers
/// `layers` leaves out, with what is in them) stay as they are. The symbols' own art is left as
/// it is.
pub fn bake_document_placing_symbols(doc: &Document, clip_slices: bool, layers: WrittenLayers) -> Option<Document> {
bake(doc, Some((clip_slices, vectorcraft_doc::MAX_SYMBOL_NODES, layers)))
}
+17 -4
View File
@@ -776,7 +776,7 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() {
let mut shadowed = type_node(55);
shadowed.opacity = 0.5;
shadowed.appearance.effects.push(fx("stylize.dropShadow", json!({})));
// Type that clips a group is outlined as the plain outlines it clips by.
// Type that clips a group is outlined as a plain path of the region it clips by.
let square = Node::path(NodeId(57), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art());
let clip = Node::new(NodeId(58), NodeKind::Group { children: vec![Arc::new(type_node(56)), Arc::new(square)], clip: true });
g.children_mut().unwrap().extend([Arc::new(shadowed), Arc::new(clip)]);
@@ -789,7 +789,10 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() {
let b = o.geometric_bounds().unwrap();
assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}");
let clipped = d.node(NodeId(58)).and_then(|n| n.children()).and_then(|c| c.first()).unwrap();
assert!(matches!(clipped.kind, NodeKind::Group { .. }) && clipped.opacity == 1.0, "{clipped:?}");
assert!(matches!(clipped.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && clipped.opacity == 1.0, "{clipped:?}");
// The region is copied with the type.
let b = clipped.geometric_bounds().unwrap();
assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}");
}
#[test]
@@ -1328,7 +1331,7 @@ fn placing_symbols_keeps_the_instances_stain() {
}
/// Every layer written, as DXF writes them (template layers are never written).
const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true };
const ALL: WrittenLayers = WrittenLayers { hidden: true, non_printing: true, hidden_objects: false };
fn is_instance(d: &Document, id: u64) -> bool {
d.node(NodeId(id)).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }))
@@ -1455,10 +1458,20 @@ fn placing_symbols_skips_instances_the_export_leaves_out() {
}
// An export that writes the layers that do not print, or the hidden layers, places that
// layer's instance first; the template layer's instance is never placed.
for (layers, first) in [(WrittenLayers { non_printing: true, hidden: false }, 921), (WrittenLayers { non_printing: false, hidden: true }, 931)] {
for (layers, first) in
[(WrittenLayers { non_printing: true, ..WrittenLayers::default() }, 921), (WrittenLayers { hidden: true, ..WrittenLayers::default() }, 931)]
{
let out = bake(&d, Some((true, each, layers))).unwrap();
assert!(!is_instance(&out, first) && is_instance(&out, 900) && is_instance(&out, 911), "{layers:?}");
}
// An export that writes hidden objects (SVG keeping hidden layers) places the hidden instance
// first, and the instance in the hidden group would come next; the hidden layer's instance
// stays, since that layer is still left out.
let out = bake(&d, Some((true, each, WrittenLayers { hidden_objects: true, ..WrittenLayers::default() }))).unwrap();
assert!(!is_instance(&out, 901), "the hidden instance is placed");
for id in [900, 903, 911, 921, 931] {
assert!(is_instance(&out, id), "{id} stays as it is");
}
}
/// `leaf` in `levels` groups, with ids from `id` up.
+14 -8
View File
@@ -182,49 +182,49 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
REVOLVE,
"Revolve…",
&["Effect", "3D and Materials"],
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true, close circular ends of open profiles; partial-sweep cut sides stay open), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"render":{"mode":"shaded"}}),
),
g(
EXTRUDE,
"Extrude & Bevel…",
&["Effect", "3D and Materials"],
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
),
g(
INFLATE,
"Inflate…",
&["Effect", "3D and Materials"],
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).",
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).",
json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"render":{"mode":"shaded"}}),
),
g(
ROTATE,
"Rotate…",
&["Effect", "3D and Materials"],
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
),
g(
CLASSIC_EXTRUDE,
"Extrude & Bevel (Classic)…",
&["Effect", "3D and Materials", "3D (Classic)"],
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.",
"{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults are VectorCraft's own.",
json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false}),
),
g(
CLASSIC_REVOLVE,
"Revolve (Classic)…",
&["Effect", "3D and Materials", "3D (Classic)"],
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none (black; the color the faces darken toward; none keeps the paint and adds only the highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
"{angle: degrees (0..360, 360; how far the profile sweeps round the axis), cap: bool (true: solid, the open ends and a partial sweep's cut sides closed; false: hollow), offset: pt (0..1000, 0; the axis's distance from the profile, a ring past 0), edge: left|right (left; the axis is at the left or the right edge of the profile's bounds), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off)}. The profile sweeps round a vertical axis, as Revolve's does, painted with the top fill (else the top stroke); every face is drawn, back to front. The defaults are VectorCraft's own.",
json!({"angle":360.0,"cap":true,"offset":0.0,"edge":"left","rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}),
),
g(
CLASSIC_ROTATE,
"Rotate (Classic)…",
&["Effect", "3D and Materials", "3D (Classic)"],
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none (black; the color the art darkens toward; none keeps the paint), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.",
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: none|diffuse (diffuse; none keeps the paint unlit; diffuse lights the art softly), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, the art whichever way it faces), blendSteps: integer (1..256, 25; how many levels the shading is rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the art darkens toward; none keeps the paint; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, with black multiplied and overprinting where the art darkens, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint the art keeps its paint and swatch link whether it is on or off)}. Every fill and stroke turns as one flat plane about the center of the object's bounds, as Rotate's do, each in its own paint, and is seen from either side. The defaults are VectorCraft's own.",
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"diffuse","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false}),
),
g(
@@ -277,7 +277,13 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
"{h: amount (10), v: amount (10), relative: bool (true: % of size), anchors: bool (true), in: bool (true), out: bool (true), seed: int (0)}",
json!({"h": 10.0, "v": 10.0, "relative": true, "anchors": true, "in": true, "out": true, "seed": 0}),
),
g("distort.twist", "Twist…", DT, "{angle: deg (-3600..3600, 10)}", json!({"angle": 10.0})),
g(
"distort.twist",
"Twist…",
DT,
"{angle: deg (-3600..3600, 10)} Outer-circle anchors stay fixed; their handles follow the inward tangent.",
json!({"angle": 10.0}),
),
g(
"distort.zigZag",
"Zig Zag…",
+37 -5
View File
@@ -5,7 +5,9 @@ use vectorcraft_geom::kurbo::ParamCurveArclen;
use vectorcraft_geom::{Affine, Anchor, ParamCurve, PathData, Point, Rect, SubPath, Vec2};
use vectorcraft_pathops::addons::pathtools::insert_at;
use crate::util::{catmull_rom, fit_piece, flag, map_nonlinear_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points};
use crate::util::{
catmull_rom, fit_piece, flag, map_handles_within, map_nonlinear_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points,
};
fn diag(b: Rect) -> f64 {
b.width().hypot(b.height()).max(1e-6)
@@ -325,8 +327,8 @@ pub fn tweak(path: &PathData, b: Rect, p: &Value) -> PathData {
}
/// Twist: rotation that is strongest at the centre and fades to zero at the bounding circle,
/// clockwise on the page for a positive `angle`, making at most `max` anchors
/// ([`map_nonlinear_within`]).
/// clockwise on the page for a positive `angle`, making at most `max` anchors. Its handles follow
/// the rotation's directional derivative, including each side of the outer circle.
pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData {
let ang = angle.clamp(-3600.0, 3600.0).to_radians();
if ang == 0.0 {
@@ -334,16 +336,46 @@ pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData {
}
let c = b.center();
let r = diag(b) / 2.0;
let half = Vec2::new(b.width() * 0.5, b.height() * 0.5);
let boundary = move |p: Point, length: f64| {
if length == r {
return true;
}
if !r.is_finite() || (length - r).abs() > 8.0 * f64::EPSILON * r {
return false;
}
// A bounds-relative distance identifies boundary points affected by center rounding.
(Vec2::new(p.x - b.x0, p.y - b.y0) - half).hypot() == r
};
let f = move |q: Point| {
let d = q - c;
let t = (1.0 - d.hypot() / r).max(0.0);
let length = d.hypot();
let t = (1.0 - length / r).max(0.0);
// y runs down, so a positive turn is clockwise on the page.
let a = ang * t;
if a == 0.0 {
return q;
}
let (s, co) = a.sin_cos();
c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co)
};
let piece = (r / 8.0).min(r / (1.0 + ang.abs() * 2.0));
map_nonlinear_within(path, piece, max, f)
map_handles_within(path, piece, max, f, |p, h| {
let v = h - p;
if !v.hypot().is_finite() {
return f(p);
}
let d = p - c;
let length = d.hypot();
let radial = if length > 0.0 { (d / length).dot(v) } else { 0.0 };
// The clamped rotation has different inward and outward derivatives at the circle.
let inside = if boundary(p, length) { radial < 0.0 } else { length < r };
let gradient = if inside { -ang / r * radial } else { 0.0 };
let tangent = if gradient == 0.0 { v } else { v + Vec2::new(-d.y, d.x) * gradient };
let a = ang * (1.0 - length / r).max(0.0);
let (s, co) = a.sin_cos();
f(p) + Vec2::new(tangent.x * co - tangent.y * s, tangent.x * s + tangent.y * co)
})
}
const ZIGZAG_ARCLEN_ACCURACY: f64 = 1e-4;
+30
View File
@@ -312,6 +312,36 @@ impl Carry {
}
}
/// Undo the actual maps of already placed gradients. Failure only changes this temporary
/// appearance; callers retain the stored row unchanged when a map cannot be inverted.
pub(crate) fn unapply_placed(&self, ap: &mut Appearance) -> Option<()> {
for step in self.0.iter().rev() {
for item in &mut ap.items {
if !matches!(item.paint(), vectorcraft_doc::color::Paint::Gradient(_)) {
continue;
}
let map = match *step {
CarryStep::Affine { m, .. } => m,
CarryStep::Boxes { from, to } => match item {
AppearanceItem::Fill(_) => crate::reshape::box_map(from, to),
AppearanceItem::Stroke(s) => crate::reshape::box_map(s.paint_bounds(from), s.paint_bounds(to)),
},
};
if vectorcraft_doc::node::flattens(map) {
return None;
}
let inverse = map.inverse();
if !inverse.is_finite() {
return None;
}
if let vectorcraft_doc::color::Paint::Gradient(g) = item.paint_mut() {
g.transform(inverse);
}
}
}
Some(())
}
pub(crate) fn push(&mut self, more: Carry) {
self.0.extend(more.0);
self.1.extend(more.1);
+177 -24
View File
@@ -110,13 +110,15 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nodes: &S
// Every path of the outline art, at any depth, is drawn inside the object's opacity
// and blend mode. A symbol's art comes with the live objects and the instances of
// other symbols inside it given as their art, and the type inside it outlined, so the
// art has nothing left for `hook` to give.
// art has nothing left for `hook` to give. Its fills and strokes carry the geometry
// effects of the instance's active fill and stroke, as the canvas draws them.
if let Some(h) = hook
&& let Some(art) = h(n)
{
let art = match &n.kind {
NodeKind::SymbolInstance { symbol, .. } if nodes.charge(&art) => {
let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
let mut art = instance_art(doc, &art, h, nodes, symbol);
crate::reshape::add_instance_row_effects(doc, n, &mut art);
crate::reshape::outline_nested_text(doc, &mut art, false);
transparency_into_members(&mut art);
art
@@ -134,6 +136,19 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nodes: &S
}
}
/// `art`, the art `hook` gave an instance of the symbol named `symbol`, with the live objects and
/// the instances of other symbols inside it given as their art
/// ([`crate::reshape::symbol_art_with`]). The art of each of those instances carries the geometry
/// effects of its own active fill and stroke ([`crate::reshape::add_instance_row_effects`]).
fn instance_art(doc: Option<&Document>, art: &Node, hook: OutlineHook, nodes: &SymbolNodes, symbol: &str) -> Node {
let drawn = |m: &Node| {
let mut a = hook(m)?;
crate::reshape::add_instance_row_effects(doc, m, &mut a);
Some(a)
};
crate::reshape::symbol_art_with(art, &drawn, nodes, symbol)
}
/// `l`, a path drawn inside `n`: its opacity multiplied by `n`'s, and `n`'s blend mode when it is
/// not Normal.
fn within(l: &mut Node, n: &Node) {
@@ -221,13 +236,15 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option<OutlineHook>, nod
}
},
// A symbol instance with a warp: its symbol's art placed by the instance, with the type
// inside it outlined, reshaped as one piece, as the renderer draws it.
// inside it outlined, reshaped as one piece, as the renderer draws it. The fills and strokes
// of the art then carry the geometry effects of the instance's active fill and stroke.
NodeKind::SymbolInstance { symbol, .. } if !fx.is_empty() => {
let h = hook?;
let art = h(n).filter(|art| nodes.charge(art))?;
let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol);
let mut art = instance_art(doc, &art, h, nodes, symbol);
crate::reshape::outline_nested_text(doc, &mut art, false);
members_as_drawn(doc, &mut art);
crate::reshape::add_instance_row_effects(doc, n, &mut art);
let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc);
// The art's own fills and strokes follow the effects as its members do.
if carry.moves(&art.appearance) {
@@ -367,9 +384,14 @@ fn compound_shape_art_in(doc: Option<&Document>, n: &Node, hook: Option<OutlineH
fn styled(src: &Node, path: PathData, outline: bool) -> Node {
let mut appearance = Appearance { items: src.appearance.items.clone(), ..Default::default() };
if outline {
let fill = src.appearance.fill_paint();
let paint = if fill.is_none() { src.appearance.stroke_paint() } else { fill };
appearance = Appearance { items: vec![AppearanceItem::Stroke(StrokeLayer::new(paint, 1.0))], ..Default::default() };
// The edges take the paint, opacity, blend mode and overprint of the top fill that paints,
// or of the top stroke that paints when no fill does.
let layer = top_painting_fill(&src.appearance).or_else(|| src.appearance.items.iter().rev().find(|i| paints(i)));
let mut stroke = StrokeLayer::new(layer.map_or(Paint::None, |i| i.paint().clone()), 1.0);
if let Some(i) = layer {
(stroke.opacity, stroke.blend, stroke.overprint) = (i.opacity(), i.blend(), i.overprint());
}
appearance = Appearance { items: vec![AppearanceItem::Stroke(stroke)], ..Default::default() };
}
let mut n = Node::path(src.id, path, appearance);
n.opacity = src.opacity;
@@ -504,7 +526,8 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option<Ou
.iter()
.filter_map(|l| {
let (path, rule) = geometry(l)?;
Some((l.id, crate::trap::TrapSource { path, rule, fill: l.appearance.fill_paint() }))
let fill = top_painting_fill(&l.appearance).map_or(Paint::None, |i| i.paint().clone());
Some((l.id, crate::trap::TrapSource { path, rule, fill }))
})
.unzip();
let made = crate::trap::traps(&srcs, &crate::trap::TrapOptions::from_params(&e.params));
@@ -580,7 +603,8 @@ fn mixing_rate(params: &Value) -> f64 {
}
fn fill_cmyk(src: &Node) -> Option<[f32; 4]> {
let paint = src.appearance.fill_paint();
// The top fill that paints: a hidden fill adds no color.
let paint = top_painting_fill(&src.appearance)?.paint().clone();
let color = paint.color()?;
let tinted = match paint {
Paint::Solid { tint, .. } => color.tinted(tint),
@@ -637,6 +661,11 @@ fn is_container(n: &Node) -> bool {
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. })
}
/// The top fill of `a` that paints: hidden fills and fills of no paint are skipped.
fn top_painting_fill(a: &Appearance) -> Option<&AppearanceItem> {
a.items.iter().rev().find(|i| i.is_fill() && paints(i))
}
/// Does `item` paint anything?
pub fn paints(item: &AppearanceItem) -> bool {
item.visible()
@@ -691,6 +720,11 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul
}
}
fn members(doc: Option<&Document>, n: &Node, out: &mut Vec<(PathData, FillRule)>) {
// A clip group whose clipping type's strokes paint around it is outlined as that clip
// group: the strokes outside the clip add nothing.
if let Some(inner) = crate::reshape::painted_clip_inner(n) {
return members(doc, inner, out);
}
// A clip group shows its members only inside its clipping path: its outline is that
// region, not the clipped members' own shapes, which may reach far outside it (#7289).
if n.clips() {
@@ -812,16 +846,16 @@ fn take_sublayer_guides(n: &mut Node, out: &mut Vec<Arc<Node>>, is_guide: &impl
take_held_guides(n, held, out, false, false);
}
/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects
/// reshaping all its members as one piece (the whole art's bounds as their reference box) after
/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its
/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below
/// the members (after a clipping path) or above them, as its contents slot says. Its
/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live
/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and
/// a Pathfinder operation or compound shape takes the symbol instances among its members as their
/// symbols' art from `doc`.
pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
struct PreparedContainer {
m: Node,
guides: Vec<Arc<Node>>,
paint: bool,
carry: crate::Carry,
}
/// The existing container pass up to its own rows becoming art. Keep its carried appearance for
/// rendering, and retain the same Carry for freezing only missing stored placements separately.
fn prepare_container(doc: Option<&Document>, n: &Node) -> Option<PreparedContainer> {
if !is_container(n) {
return None;
}
@@ -832,6 +866,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
return None;
}
let mut m = n.clone();
let mut carry = crate::Carry::default();
// Its ruler guides take no part: they go back above the evaluated art at the end. With effects
// that replace or copy the art, so do its guides among the art and those in its sublayers and
// groups, which would otherwise go with that art: they stay on `n`, in order, hidden and
@@ -858,7 +893,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
let _later = crate::raster::LaterGroups::enter(&n.appearance.effects);
members_as_drawn(doc, &mut m);
}
let carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
carry = crate::reshape::reshape_leaves_carrying(&mut m, &fx, &n.appearance.effects, doc);
// The group's own fills and strokes paint the members as a whole: their gradients follow
// the effects as the members' do.
if paint && carry.moves(&m.appearance) {
@@ -867,15 +902,40 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
}
m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects);
m.appearance.effects.retain(|e| !is_pathfinder(&e.id));
Some(PreparedContainer { m, guides, paint, carry })
}
/// `n`, a group or layer, as plain art: its Pathfinder effects evaluated, its geometry effects
/// reshaping all its members as one piece (the whole art's bounds as their reference box) after
/// the members' own geometry and Pathfinder effects ([`members_as_drawn`]), and its
/// own fills and strokes turned into art painting the members' geometry ([`member_shapes`]) below
/// the members (after a clipping path) or above them, as its contents slot says. Its
/// transparency, opacity mask and raster effects stay. `None` when it has none of these. Live
/// objects among the members are evaluated with the symbols of `doc` (see [`member_shapes`]), and
/// a Pathfinder operation or compound shape takes the symbol instances among its members as their
/// symbols' art from `doc`. A Transform effect that makes copies with raster effects listed before
/// it gives each copy those raster effects ([`copied_container`]).
pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
if !is_container(n) {
return None;
}
if let Some(t) = crate::reshape::copied_container_raster_at(n) {
return Some(copied_container(doc, n, t));
}
let PreparedContainer { mut m, guides, paint, .. } = prepare_container(doc, n)?;
if paint {
let shapes = member_shapes(doc, &m);
let bounds = m.geometric_bounds();
// A clip group whose clipping type paints strokes is now a group of a clip group and those
// strokes ([`crate::reshape::paint_type_clip`]): its own fills and strokes paint inside
// that clip group. Such groups among the members are measured as their clip groups.
let wrapped = n.clips() && crate::reshape::painted_clip_inner(&m).is_some();
let (shapes, bounds) = (member_shapes(doc, &m), crate::reshape::clip_bounds(&m));
let art =
|items: &[AppearanceItem]| -> Vec<Arc<Node>> { items.iter().filter_map(|i| item_art(n.id, i, &shapes, bounds)).map(Arc::new).collect() };
let (below, above) = m.appearance.split_contents();
let (below, above) = (art(below), art(above));
let at = usize::from(m.clips());
if let Some(ch) = m.children_mut() {
let at = usize::from(wrapped || m.clips());
let target = if wrapped { m.children_mut().and_then(|ch| ch.first_mut()).map(Arc::make_mut) } else { Some(&mut m) };
if let Some(ch) = target.and_then(Node::children_mut) {
let at = at.min(ch.len());
ch.splice(at..at, below);
ch.extend(above);
@@ -889,6 +949,99 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option<Node> {
Some(m)
}
/// The exact pre-copy source shared by rendering and stored gradient placement.
fn copied_container_source(doc: Option<&Document>, n: &Node, t: usize) -> (Node, Vec<Arc<Node>>, Node) {
let mut m = n.clone();
let mut guides = vec![];
take_sublayer_guides(&mut m, &mut guides, &Node::is_ruler_guide);
let mut source = m.clone();
source.appearance.effects = n.appearance.effects.get(..t).unwrap_or_default().to_vec();
// With no geometry effect before the Transform effect, `evaluate_container` leaves the members'
// own effects live (it only paints the group's own fills and strokes): the members are drawn
// first, so their effects apply before the copies are made.
if crate::reshape::geometry_effects(&source).is_empty() {
source = crate::reshape::outlined_members(doc, &source);
// The members' raster effects follow the group's own Transform effects as well.
let _later = crate::raster::LaterGroups::enter(&n.appearance.effects);
members_as_drawn(doc, &mut source);
}
(m, guides, source)
}
/// `n`, a group or layer whose own effects split at `t` ([`crate::reshape::copied_container_raster_at`]),
/// as plain art: the effects before the Transform effect at `t` evaluated on its members as one
/// piece ([`evaluate_container`]), with the raster effects among them, and that piece copied by the
/// Transform effect, each copy a group of its own carrying those raster effects moved, turned,
/// reflected and scaled with it ([`crate::reshape::copied_container_art`]). The art keeps the kind,
/// transparency and opacity mask of `n` and the raster effects from `t` on, which paint once around
/// all the copies; a clip group's or clipping layer's copies each clip, and the art itself does not.
/// Its ruler guides, those in its sublayers and groups included, go once above the copies, hidden
/// and locked as their containers were.
fn copied_container(doc: Option<&Document>, n: &Node, t: usize) -> Node {
let (mut m, guides, source) = copied_container_source(doc, n, t);
let mut piece = evaluate_container(doc, &source).unwrap_or_else(|| {
let mut p = source.clone();
p.appearance.effects = crate::raster::without_geometry(&p.appearance.effects);
p
});
// The piece is one copy: the transparency, opacity mask and guides stay on the art.
piece.name = None;
piece.visible = true;
piece.locked = false;
(piece.opacity, piece.blend, piece.isolate) = (1.0, Default::default(), false);
piece.extras_mut().mask = None;
// The copies are made about the piece's bounds, measured first: a layer leaves its hidden
// members out of them, and a group does not.
let bounds = piece.geometric_bounds();
// A layer's copies are groups in it.
if let NodeKind::Layer { children, clip, .. } = &mut piece.kind {
piece.kind = NodeKind::Group { children: std::mem::take(children), clip: *clip };
}
let (art, effects) = crate::reshape::copied_container_art(doc, n, t, piece, bounds);
let copies = art.children().cloned().unwrap_or_default();
if let NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } = &mut m.kind {
*children = copies;
*clip = false;
}
m.appearance.items.clear();
m.appearance.contents_index = None;
m.appearance.effects = effects;
if let Some(ch) = m.children_mut() {
ch.extend(guides);
}
m
}
/// Freeze representable fitted own paints to the box the container pass gives them, retaining
/// every live effect and already explicit placement. Hidden-only containers the pass does not
/// evaluate stay unchanged; this does not add a different fallback to `evaluate_container`.
pub fn pinned_container_appearance(doc: &Document, n: &Node) -> Option<Appearance> {
if !n.appearance.has_unplaced_gradient() {
return None;
}
if let Some(t) = crate::reshape::copied_container_raster_at(n) {
let (_, _, source) = copied_container_source(Some(doc), n, t);
let pinned = pinned_container_appearance(doc, &source)?;
let mut out = (*n.appearance).clone();
out.items = pinned.items;
return Some(out);
}
let PreparedContainer { m, carry, .. } = prepare_container(Some(doc), n)?;
let bounds = m.geometric_bounds()?;
let mut out = (*n.appearance).clone();
let mut changed = false;
for (item, original) in out.items.iter_mut().zip(&n.appearance.items) {
if paints(original)
&& matches!(original.paint(), Paint::Gradient(g) if !g.is_placed())
&& let Some(pinned) = crate::pinned_gradient_item(original, bounds, &[&carry])
{
*item = pinned;
changed = true;
}
}
changed.then_some(out)
}
/// Replace each visible member of `n` with geometry or Pathfinder effects of its own, at every
/// depth of its groups and layers, by the art it draws ([`evaluate_container`],
/// [`crate::reshape::own_effects_art`]), so the geometry effects of `n` reshape what its members
+94 -1
View File
@@ -1,6 +1,6 @@
use super::*;
use vectorcraft_color::{BlendMode, Color, Paint};
use vectorcraft_doc::{CharStyle, Effect, NodeId, TextObject};
use vectorcraft_doc::{CharStyle, Effect, FillLayer, NodeId, TextObject};
use vectorcraft_geom::{Point, Rect, shapes};
/// Type tests need glyph outlines, which only the optional craft-fonts build input provides.
@@ -71,6 +71,33 @@ fn trap_effect_adds_an_overprinting_strip_above_the_members() {
assert_eq!(fill.paint.color(), Some(yellow));
}
/// Trap takes each member's top fill that paints: a hidden fill on top is skipped, and a member
/// whose only fill is hidden does not take part.
#[test]
fn trap_skips_a_hidden_fill() {
let yellow = Color::cmyk(0.0, 0.0, 1.0, 0.0);
let blue = Color::cmyk(1.0, 0.6, 0.0, 0.0);
let mut hidden = FillLayer::new(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
hidden.visible = false;
let trap = |members: Vec<Arc<Node>>| {
let mut g = Node::group(NodeId(10), members);
let params = serde_json::json!({"thickness": 1.0, "tintReduction": 100});
g.appearance.effects.push(Effect { id: crate::trap::TRAP.into(), params, visible: true });
pathfinder_children(None, &g, None).unwrap()
};
let mut covered = (*sq(1, 0.0, yellow)).clone();
covered.appearance.items.push(AppearanceItem::Fill(hidden.clone()));
let out = trap(vec![Arc::new(covered), sq(2, 10.0, blue)]);
assert_eq!(out.len(), 3, "both squares and one trap");
assert_eq!(out[2].appearance.fill().unwrap().paint.color(), Some(yellow));
let only_hidden = Node::path(
NodeId(1),
shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)),
Appearance { items: vec![AppearanceItem::Fill(hidden)], ..Default::default() },
);
assert_eq!(trap(vec![Arc::new(only_hidden), sq(2, 10.0, blue)]).len(), 2, "no trap");
}
#[test]
fn hard_mix_takes_the_highest_of_each_cmyk_channel_and_drops_strokes() {
let mut g = two_overlapping_cmyk_squares();
@@ -87,6 +114,72 @@ fn soft_mix_blends_cmyk_bottom_to_top_and_drops_strokes() {
assert!((c - 0.3).abs() < 0.02 && (m - 0.43).abs() < 0.02 && (y - 0.35).abs() < 0.02 && (k - 0.05).abs() < 0.02, "{c} {m} {y} {k}");
}
/// Soft Mix and Hard Mix mix the top fill that paints: a hidden fill above it adds no color.
#[test]
fn mixes_skip_a_hidden_fill() {
for effect in ["pathfinder.softMix", "pathfinder.hardMix"] {
let mut plain = two_overlapping_cmyk_squares();
plain.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"mixingRate": 50.0}), visible: true });
let mut covered = plain.clone();
let NodeKind::Group { children, .. } = &mut covered.kind else { panic!("group") };
let mut hidden = FillLayer::new(Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
hidden.visible = false;
for c in children.iter_mut() {
Arc::make_mut(c).appearance.items.push(AppearanceItem::Fill(hidden.clone()));
}
assert_eq!(overlap_cmyk(&covered), overlap_cmyk(&plain), "{effect}");
}
}
/// Outline strokes each edge with the top fill that paints, keeping that fill's opacity, blend
/// mode and overprint. A hidden fill or a fill of no paint gives the edges nothing; with no fill
/// that paints, the edges take the top stroke that paints, which skips hidden and 0 pt strokes.
#[test]
fn outline_edges_keep_the_fill_layers_opacity_blend_and_overprint() {
use vectorcraft_doc::StrokeLayer;
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0));
let mut fill = FillLayer::new(red.clone());
(fill.opacity, fill.blend, fill.overprint) = (0.5, BlendMode::Multiply, true);
let mut hidden = FillLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
hidden.visible = false;
let mut stroke = StrokeLayer::new(blue.clone(), 2.0);
(stroke.opacity, stroke.blend, stroke.overprint) = (0.5, BlendMode::Multiply, true);
let mut hidden_stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 2.0);
hidden_stroke.visible = false;
let zero_stroke = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 0.0);
let look = |items: Vec<AppearanceItem>| Appearance { items, ..Default::default() };
let (f, s) = (AppearanceItem::Fill, AppearanceItem::Stroke);
let cases = [
(look(vec![f(fill.clone())]), Some(red.clone())),
(look(vec![f(fill.clone()), f(hidden.clone())]), Some(red.clone())),
(look(vec![f(fill.clone()), f(FillLayer::new(Paint::None))]), Some(red.clone())),
(look(vec![f(hidden.clone())]), None),
(look(vec![s(stroke.clone())]), Some(blue.clone())),
(look(vec![f(hidden.clone()), s(stroke.clone())]), Some(blue.clone())),
(look(vec![s(stroke.clone()), s(hidden_stroke), s(zero_stroke.clone())]), Some(blue.clone())),
(look(vec![s(zero_stroke)]), None),
];
for (appearance, want) in cases {
let member = Arc::new(Node::path(NodeId(1), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), appearance));
let mut g = Node::group(NodeId(10), vec![member, sq(2, 5.0, Color::rgb(0.0, 0.0, 1.0))]);
g.appearance.effects.push(Effect { id: "pathfinder.outline".into(), params: serde_json::json!({}), visible: true });
let out = pathfinder_children(None, &g, None).unwrap();
let edges: Vec<_> = out.iter().filter(|n| n.id == NodeId(1)).collect();
assert!(!edges.is_empty(), "{out:#?}");
for n in edges {
let [AppearanceItem::Stroke(s)] = n.appearance.items.as_slice() else { panic!("one stroke: {n:#?}") };
match &want {
Some(paint) => {
assert_eq!(&s.paint, paint);
assert_eq!((s.opacity, s.blend, s.overprint), (0.5, BlendMode::Multiply, true), "{s:#?}");
}
None => assert!(s.paint.is_none() && s.opacity == 1.0, "{s:#?}"),
}
}
}
}
#[test]
fn shape_modes_follow_the_pathfinder_panel() {
let add = pathfinder_children(None, &group_with("pathfinder.add"), None).unwrap();
+16 -14
View File
@@ -45,6 +45,7 @@ mod lighting_presets;
mod live;
mod marks;
pub mod pixel;
mod placement;
pub mod preview;
mod raster;
mod reshape;
@@ -75,36 +76,37 @@ 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, shape_art,
is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, pinned_container_appearance, shape_art,
};
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};
pub use marks::{CROP_MARKS, crop_marks_art, has_crop_marks};
pub use pixel::{PIXEL_EFFECTS, PixelFx, PixelSpace};
pub use placement::pinned_gradient_item;
pub use raster::{
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_map, staged_effects,
RASTERIZE, RasterFx, Rasterize, color_param, follow_items, item_effects_in, outset, raster_effects, rasterize_stage, stage_maps, staged_effects,
without_geometry,
};
pub use reshape::{
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry,
has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outer_effects, outline_art,
outline_text, paint_type_piece, reshape,
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, has_gradient_copies,
has_instance_row_raster, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint,
instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape,
};
pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
};
pub use solids::{
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, RENDER, RENDER_MODES, ROTATE,
ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, extrude_options,
graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, missing_symbol,
names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art, solid_art_in, takes_graphics,
three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid,
validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options,
with_graphic,
CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, MeshGraphics, RENDER, RENDER_MODES,
ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading,
extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics,
mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art,
solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as,
three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in,
validate_three_d_params, view_options, with_graphic,
};
pub use solids::{
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, graphic_frame_at, graphics_reshaped_after,
rename_appearance_graphic_symbol,
GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_fitting_scale,
graphic_frame_at, graphic_side_size, graphics_reshaped_after, rename_appearance_graphic_symbol,
};
pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
pub use svg_filter::SVG_FILTER;
+148 -5
View File
@@ -168,6 +168,62 @@ pub(crate) fn footprint(path: &vectorcraft_geom::BezPath, seam: f64) -> vectorcr
if sign < 0.0 { footprint.reverse_subpaths() } else { footprint }
}
/// The most edges a facet may have for [`seamed_fill`] to test it for crossing edges.
const SEAMED_FILL_EDGES: usize = 256;
/// Facet `path` and its round seam `seam` wide as one path to fill ([`footprint`]), so that at an
/// edge pixel the facet and its seam cover it once between them, not a fill's coverage and then a
/// stroke's over it. `None` unless `path` is one closed polygon of up to [`SEAMED_FILL_EDGES`]
/// finite edges, with an area, and with no two edges that are not neighbors touching: only there
/// does the footprint's nonzero fill cover the facet and its seam and nothing more. `None` too for
/// a seam that is not a positive finite width, or a footprint with no finite bounds or less area
/// than the facet.
pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Option<vectorcraft_geom::PathData> {
use kurbo::{PathEl, Point, Shape};
if !(seam.is_finite() && seam > 0.0) {
return None;
}
let bez = path.to_bezpath();
let mut elements = bez.elements().iter();
let Some(PathEl::MoveTo(first)) = elements.next() else { return None };
let mut points = vec![*first];
let mut closed = false;
for el in elements {
match el {
PathEl::LineTo(p) if !closed => points.push(*p),
PathEl::ClosePath if !closed => closed = true,
_ => return None,
}
}
if points.len() > 1 && points.first() == points.last() {
points.pop();
}
let area = bez.area().abs();
if !closed || !(3..=SEAMED_FILL_EDGES).contains(&points.len()) || points.iter().any(|p| !p.is_finite()) || !area.is_finite() || area <= 1e-9 {
return None;
}
let side = |a: Point, b: Point, c: Point| (b - a).cross(c - a);
let touch = |a: Point, b: Point, c: Point, d: Point| {
let boxes = a.x.min(b.x) <= c.x.max(d.x) && c.x.min(d.x) <= a.x.max(b.x) && a.y.min(b.y) <= c.y.max(d.y) && c.y.min(d.y) <= a.y.max(b.y);
boxes && side(a, b, c) * side(a, b, d) <= 0.0 && side(c, d, a) * side(c, d, b) <= 0.0
};
let n = points.len();
let edge = |i: usize| (points[i], points[(i + 1) % n]);
for i in 0..n {
for j in i + 2..n {
if i == 0 && j == n - 1 {
continue;
}
let ((a, b), (c, d)) = (edge(i), edge(j));
if touch(a, b, c, d) {
return None;
}
}
}
let fill = footprint(&bez, seam);
(fill.bounding_box().is_finite() && fill.area().abs() >= area).then(|| vectorcraft_geom::PathData::from_bezpath(&fill))
}
/// Colored-light facets `faces` (in drawing order) drawn over an underlay of themselves, the same
/// facets grown to seams [`UNDERLAY_SEAM`] wide, all clipped once to the union of the facets'
/// footprints. Where two facets' antialiased edges meet, the underlay fills what they leave
@@ -175,6 +231,20 @@ pub(crate) fn footprint(path: &vectorcraft_geom::BezPath, seam: f64) -> vectorcr
/// every face is a facet a surface draws: a path filled and stroked by its seam, or a facet composed
/// in a clip of its footprint, neither with an opacity mask.
pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc<vectorcraft_doc::Node>]) -> Option<vectorcraft_doc::Node> {
use std::sync::Arc;
use vectorcraft_doc::{Node, NodeKind};
let (clip, mut underlay) = underlay(id, faces)?;
underlay.extend(faces.iter().cloned());
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true }))
}
/// The parts of [`sealed`] for `faces`: a path of the union of the facets' footprints, to clip to,
/// and the facets grown to seams [`UNDERLAY_SEAM`] wide, in the same order. `None` under the same
/// conditions as [`sealed`].
pub(crate) fn underlay(
id: vectorcraft_doc::NodeId,
faces: &[std::sync::Arc<vectorcraft_doc::Node>],
) -> Option<(vectorcraft_doc::Node, Vec<std::sync::Arc<vectorcraft_doc::Node>>)> {
use std::sync::Arc;
use vectorcraft_doc::{Appearance, Node, NodeKind};
let mut outline = vectorcraft_geom::BezPath::new();
@@ -207,15 +277,15 @@ pub(crate) fn sealed(id: vectorcraft_doc::NodeId, faces: &[std::sync::Arc<vector
_ => return None,
}
}
let clip = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&outline), Appearance::default());
underlay.extend(faces.iter().cloned());
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true }))
Some((Node::path(id, vectorcraft_geom::PathData::from_bezpath(&outline), Appearance::default()), underlay))
}
/// Composite smooth solid-fill facets with one clip and three channel groups per surface. In each
/// channel, an underlay of the facets with wide seams lies under the facets themselves, so a
/// shared edge is opaque in that channel's own light before the channels are screened together;
/// the black backdrop shows only outside the surface, which the clip removes.
/// the black backdrop shows only outside the surface, which the clip removes. Each facet over the
/// underlay is one fill of the facet and its seam together ([`seamed_fill`]), or a fill and a seam
/// stroke where that is `None`.
pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_three_d::Facet], paint: &Paint) -> vectorcraft_doc::Node {
use kurbo::Shape;
use std::sync::Arc;
@@ -239,6 +309,8 @@ pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_t
let clip = Node::path(id, PathData::from_bezpath(&boundary), Appearance::default());
let bounds = bounds.unwrap_or(Rect::ZERO).inflate(1.0, 1.0);
let cover = |paint| Node::path(id, shapes::rectangle(bounds), Appearance::basic(paint, Paint::None, 0.0));
let seam = |face: &vectorcraft_three_d::Facet| (face.thickness() / 2.0).clamp(0.05, 0.75);
let exact: Vec<Option<PathData>> = facets.iter().map(|face| seamed_fill(&face.path(), seam(face))).collect();
let channels = (0..3)
.map(|channel| {
let mut color = [0.0; 3];
@@ -274,7 +346,17 @@ pub(crate) fn solid_surface(id: vectorcraft_doc::NodeId, facets: &[vectorcraft_t
};
let mut children = vec![Arc::new(cover(Paint::solid(Color::BLACK)))];
children.extend(draw(|_| UNDERLAY_SEAM));
children.extend(draw(|face| (face.thickness() / 2.0).clamp(0.05, 0.75)));
children.extend(facets.iter().zip(&exact).zip(&paints).map(|((face, fill), paint)| {
let mut items = vec![AppearanceItem::Fill(FillLayer::new(paint.clone()))];
let path = match fill {
Some(fill) => fill.clone(),
None => {
items.push(AppearanceItem::Stroke(seam_stroke(paint.clone(), seam(face))));
face.path()
}
};
Arc::new(Node::path(id, path, Appearance { items, ..Default::default() }))
}));
let mut group = Node::group(id, children);
group.isolate = true;
group.blend = BlendMode::Screen;
@@ -517,4 +599,65 @@ mod tests {
}
}
}
/// A simple polygon facet and its 0.75 pt round seam are one nonzero-filled path: it covers the
/// facet and the 0.375 pt the seam reaches past each edge and corner, and nothing more, wound
/// either way and in a concave notch. A facet whose footprint would gain or lose area under a
/// nonzero fill (no area, crossing edges, a hole, curves) or a seam with no width has none.
#[test]
fn seamed_fill_covers_a_polygon_and_its_seam_once() {
use kurbo::Shape;
use vectorcraft_geom::BezPath;
let polygon = |points: &[(f64, f64)]| {
let mut bp = BezPath::new();
bp.move_to(points[0]);
for p in &points[1..] {
bp.line_to(*p);
}
bp.close_path();
bp
};
let covers = |fill: &vectorcraft_geom::PathData, x: f64, y: f64| fill.to_bezpath().winding(Point::new(x, y)) != 0;
let notched = [(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (6.0, 10.0), (6.0, 4.0), (4.0, 4.0), (4.0, 10.0), (0.0, 10.0)];
let mut reversed = notched;
reversed.reverse();
for points in [&notched[..], &reversed[..], &[(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)][..]] {
let fill = seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&polygon(points)), 0.75).expect("a simple polygon");
let contours = fill.to_bezpath().elements().iter().filter(|el| matches!(el, kurbo::PathEl::MoveTo(_))).count();
assert!(contours >= 2, "{points:?}: the seam's outline and the facet, {contours} contours");
for (x, y) in [(1.0, 1.0), (2.0, 0.5), (5.0, -0.3), (-0.3, 5.0), (-0.2, -0.2)] {
assert!(covers(&fill, x, y), "{points:?} covers ({x},{y})");
}
for (x, y) in [(5.0, -0.5), (-0.5, 5.0), (-0.3, -0.3), (12.0, 12.0)] {
assert!(!covers(&fill, x, y), "{points:?} leaves ({x},{y})");
}
}
let fill = seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&polygon(&notched)), 0.75).unwrap();
assert!(covers(&fill, 4.3, 8.0) && covers(&fill, 5.0, 4.3), "the notch's edges carry the seam");
assert!(!covers(&fill, 5.0, 8.0), "the notch stays open");
let square = polygon(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]);
let mut holed = square.clone();
holed.extend(polygon(&[(3.0, 3.0), (3.0, 7.0), (7.0, 7.0), (7.0, 3.0)]).iter());
let mut curved = BezPath::new();
curved.move_to((0.0, 0.0));
curved.quad_to((5.0, -5.0), (10.0, 0.0));
curved.line_to((5.0, 10.0));
curved.close_path();
let mut open = BezPath::new();
open.move_to((0.0, 0.0));
open.line_to((10.0, 0.0));
open.line_to((10.0, 10.0));
for (name, path, seam) in [
("sliver", polygon(&[(0.0, 0.0), (10.0, 0.0), (5.0, 0.0)]), 0.75),
("bow tie", polygon(&[(0.0, 0.0), (10.0, 10.0), (10.0, 0.0), (0.0, 10.0)]), 0.75),
("a vertex visited twice", polygon(&[(0.0, 0.0), (10.0, 0.0), (5.0, 5.0), (10.0, 10.0), (0.0, 10.0), (5.0, 5.0)]), 0.75),
("hole", holed, 0.75),
("curve", curved, 0.75),
("open", open, 0.75),
("no seam", square.clone(), 0.0),
("endless seam", square, f64::INFINITY),
] {
assert!(seamed_fill(&vectorcraft_geom::PathData::from_bezpath(&path), seam).is_none(), "{name}");
}
}
}
+36 -14
View File
@@ -6,7 +6,6 @@
//! lies one pixel per point at 100 %, centered on the object's center and repeated in both
//! directions.
use std::io::Cursor;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
@@ -85,9 +84,15 @@ impl LoadedTexture {
/// Its [`TEXTURE_IMAGE`] value: the gray levels as a grayscale PNG, base64; `None` when the
/// PNG can't be written.
pub fn to_stored(&self) -> Option<String> {
let img = image::GrayImage::from_raw(self.width, self.height, self.gray.clone())?;
let mut png = Vec::new();
img.write_to(&mut Cursor::new(&mut png), image::ImageFormat::Png).ok()?;
let img = craft_image_codecs::Image::from_raw(
self.width,
self.height,
craft_image_codecs::ChannelLayout::Gray,
craft_image_codecs::SampleType::U8,
self.gray.clone(),
)
.ok()?;
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).ok()?;
Some(base64_encode(&png))
}
@@ -95,21 +100,38 @@ impl LoadedTexture {
/// `None` when `png` isn't a PNG or holds no pixels.
/// `None` too when its gray levels would take the live textures past [`MAX_LIVE`].
fn from_png(png: &[u8]) -> Option<Self> {
let reader = || {
let mut reader = image::ImageReader::with_format(Cursor::new(png), image::ImageFormat::Png);
let mut limits = image::Limits::default();
limits.max_alloc = Some(vectorcraft_doc::MAX_RASTER_ALLOC);
reader.limits(limits);
reader
};
let (w, h) = reader().into_dimensions().ok()?;
let (w, h) = Self::png_ihdr_size(png)?;
let gray = (w as usize).checked_mul(h as usize)?;
if LIVE.load(Ordering::Relaxed).saturating_add(gray) > MAX_LIVE {
return None;
}
let img = reader().decode().ok()?.to_luma8();
let mut opts = craft_image_codecs::DecodeOptions::default();
opts.limits.max_alloc = vectorcraft_doc::MAX_RASTER_ALLOC;
// The codec default caps each side at 2^18; a stored texture can be longer than that and
// still fit the live and allocation budgets.
opts.limits.max_width = u32::MAX;
opts.limits.max_height = u32::MAX;
let img = craft_image_codecs::decode_as_with(craft_image_codecs::Format::Png, png, &opts).ok()?;
let (width, height) = img.dimensions();
(width > 0 && height > 0).then(|| Self::new(width, height, img.into_raw()))
if width == 0 || height == 0 {
return None;
}
use craft_image_codecs::{ChannelLayout as L, SampleType as S};
let luma = match (img.layout(), img.sample_type()) {
(L::Gray, S::U8) => img.into_data(),
_ => image::RgbaImage::from_raw(width, height, img.to_rgba8()).map(image::DynamicImage::ImageRgba8)?.into_luma8().into_raw(),
};
Some(Self::new(width, height, luma))
}
/// Read `(width, height)` from a PNG's IHDR chunk without decoding pixels.
fn png_ihdr_size(png: &[u8]) -> Option<(u32, u32)> {
if png.len() < 24 || &png[..8] != b"\x89PNG\r\n\x1a\n" || &png[12..16] != b"IHDR" {
return None;
}
let w = u32::from_be_bytes(png[16..20].try_into().ok()?);
let h = u32::from_be_bytes(png[20..24].try_into().ok()?);
Some((w, h))
}
/// The surface's height (points) at `p` (points at 100 %, from the object's center): the gray
Loaded 100 of 1266 files, more files were not shown because too many files have changed in this diff. Show more