Merge main into feat/retype-near-matches

This commit is contained in:
dotCooCoo committed 2026-11-20 06:02:09 -08:00
commit 3e4e4e255f
193 files changed
+13157 -1253

No files matched your search

+15
View File
@@ -24,6 +24,21 @@ jobs:
# Same craft-fonts commit as release.yml.
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
timeout-minutes: 90
# The gate's test binaries carry no debug info and no symbols (CARGO_PROFILE_TEST_DEBUG=0,
# CARGO_PROFILE_TEST_STRIP=symbols), as photocraft's do: linking ~100 test binaries with line
# tables ran the hosted runner out of resources, and it stopped mid-link with "received a
# shutdown signal" (exit 143). Panics still name file and line; local builds keep Cargo.toml's
# line tables.
dev-strip: true
# The workspace crates also build without line tables. A panic still names its file and line.
dev-debug: "0"
# Five legs instead of one: shards 1 to 4 each build and run the tests of their own crates,
# and shard 5 runs the other `cargo xtask ci` steps (xtask/src/shards.rs). `gate (<os>)`
# passes only when all five did. On pushes to main, a `cache warm` leg builds what every
# shard builds and saves the dependency cache.
test-shards: 5
shard-command: cargo xtask ci shard
warm-command: cargo xtask ci warm
packages: >-
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev
libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers
+1
View File
@@ -155,6 +155,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-draw-inside.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-draw-normal.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-ellipse.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-fill-area.svg` | VectorCraft contributors | Original work, drawn for VectorCraft: three crossing lines with the triangle they enclose filled | MIT OR Apache-2.0 | |
| `assets/icons/dc-fill-none.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-filter.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-flare.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
Generated
+52 -40
View File
@@ -1001,7 +1001,7 @@ dependencies = [
[[package]]
name = "craft-affinity"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"crc32fast",
"flate2",
@@ -1012,7 +1012,7 @@ dependencies = [
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"md-5",
"rayon",
@@ -1021,12 +1021,12 @@ dependencies = [
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"rayon",
]
@@ -1034,12 +1034,12 @@ dependencies = [
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
[[package]]
name = "craft-dxf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"craft-codepage",
"encoding_rs",
@@ -1051,7 +1051,12 @@ dependencies = [
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec#cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec"
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
[[package]]
name = "craft-font-catalog"
@@ -1070,12 +1075,12 @@ dependencies = [
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
[[package]]
name = "craft-gif"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"gif",
]
@@ -1083,7 +1088,7 @@ dependencies = [
[[package]]
name = "craft-gzip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"flate2",
]
@@ -1091,7 +1096,7 @@ dependencies = [
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -1114,7 +1119,7 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"craft-dds",
"craft-jpeg",
@@ -1141,7 +1146,7 @@ dependencies = [
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"thiserror 2.0.21",
]
@@ -1149,7 +1154,7 @@ dependencies = [
[[package]]
name = "craft-jxl"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"brotli-decompressor 5.0.3",
"jixel",
@@ -1160,7 +1165,7 @@ dependencies = [
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"egui",
"serde",
@@ -1170,7 +1175,7 @@ dependencies = [
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"brotli-decompressor 6.3.2",
"chrono",
@@ -1182,7 +1187,7 @@ dependencies = [
[[package]]
name = "craft-metafile"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"encoding_rs",
"image",
@@ -1193,7 +1198,7 @@ dependencies = [
[[package]]
name = "craft-mime"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"chrono",
"craft-codepage",
@@ -1203,7 +1208,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"hayro-interpret",
"hayro-syntax",
@@ -1214,7 +1219,7 @@ dependencies = [
[[package]]
name = "craft-plotter"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"kurbo 0.13.1",
"thiserror 2.0.21",
@@ -1223,7 +1228,7 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"craft-winprint-gdi",
"log",
@@ -1237,7 +1242,7 @@ dependencies = [
[[package]]
name = "craft-proof"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"log",
"miniz_oxide 0.9.1",
@@ -1248,16 +1253,21 @@ dependencies = [
[[package]]
name = "craft-ps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec#cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec"
dependencies = [
"craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec)",
"flate2",
"kurbo 0.13.1",
"miniz_oxide 0.8.9",
"pdf-writer",
"skrifa 0.47.0",
"weezl 0.1.12",
]
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"encoding_rs",
"flate2",
@@ -1268,7 +1278,7 @@ dependencies = [
[[package]]
name = "craft-stream-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"fax",
"hayro-ccitt",
@@ -1279,7 +1289,7 @@ dependencies = [
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"craft-image-codecs",
"craft-xml",
@@ -1300,7 +1310,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1309,7 +1319,7 @@ dependencies = [
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -1330,7 +1340,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"chrono",
"dunce",
@@ -1357,7 +1367,7 @@ dependencies = [
[[package]]
name = "craft-vectorcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"flate2",
"serde",
@@ -1379,7 +1389,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"egui",
"objc2 0.6.5",
@@ -1398,7 +1408,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -2505,7 +2515,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"brotli",
"hayro-postscript",
@@ -2514,7 +2524,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -2532,7 +2542,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -2550,12 +2560,12 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -3355,7 +3365,7 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"base64 0.22.1",
"bumpalo",
@@ -3464,7 +3474,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46"
source = "git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0#d7c9632bfb3040cf45db394e7500cc93c81c49e0"
dependencies = [
"arrayvec",
"kurbo 0.13.1",
@@ -6673,6 +6683,7 @@ dependencies = [
"craft-image-codecs",
"crc32fast",
"proptest",
"vectorcraft-affinity",
]
[[package]]
@@ -6866,7 +6877,7 @@ dependencies = [
name = "vectorcraft-eps"
version = "0.24.1"
dependencies = [
"craft-eps",
"craft-eps 0.1.0 (git+https://github.com/storytold/craft-libs?rev=d7c9632bfb3040cf45db394e7500cc93c81c49e0)",
"craft-image-codecs",
"craft-pdf",
"craft-ps",
@@ -7034,6 +7045,7 @@ dependencies = [
"vectorcraft-doc",
"vectorcraft-effects",
"vectorcraft-geom 0.24.1",
"vectorcraft-pdf",
"vectorcraft-testkit",
"vectorcraft-text",
]
+33 -33
View File
@@ -11,41 +11,41 @@ rust-version = "1.95"
repository = "https://github.com/storytold/vectorcraft"
[workspace.dependencies]
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", default-features = false, features = ["interpret", "write"] }
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["serde"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
# 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 = "50b0ee7bf811e363b5f238382b5c77318cf33e46", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", 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 = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
# 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 = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
# WMF, EMF and EMF+ reader (craft-libs#778).
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false, features = ["write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", features = ["egui"] }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "cfcc86242d56fe68117cd5dc2e5dd3b7a0e5b0ec", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0", features = ["egui"] }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -186,13 +186,13 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "d7c9632bfb3040cf45db394e7500cc93c81c49e0" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
+2
View File
@@ -146,7 +146,9 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged.
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
- 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged.
- 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged.
- 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged.
- 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
+3 -1
View File
@@ -46,6 +46,8 @@ 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.
# It also lists each monitor's work area for floating panels (src/window.rs), so a build without
# the `wgpu` feature keeps the panels to the monitors' whole rects.
winsafe = { version = "0.0.29", default-features = false, features = ["user"], optional = true }
# Waits for Direct3D 12's adapter list before the window starts (src/gpu.rs, #4150). MIT OR
# Apache-2.0, already in the build through eframe.
@@ -73,7 +75,7 @@ vectorcraft-render = { workspace = true }
# with default features off). Pinned exactly: review the diff before bumping.
muda = { version = "=0.21.2", default-features = false }
objc2 = "0.6"
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSampler", "NSColorSpace", "NSControl", "NSMenu", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-core-foundation", "objc2-quartz-core", "NSApplication", "NSCursor", "NSImage", "NSImageRep", "NSBitmapImageRep", "NSButton", "NSColor", "NSColorSampler", "NSColorSpace", "NSControl", "NSMenu", "NSEvent", "NSPasteboard", "NSPopUpButton", "NSResponder", "NSSavePanel", "NSScreen", "NSTextField", "NSTextInputContext", "NSView", "NSWindow"] }
# Files opened from Finder and the Dock (src/open_documents.rs), pasted bitmaps (src/clipboard.rs) and the control channel's App Nap activity (src/control_server.rs); both already come with winit, muda and rfd.
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSGeometry", "NSNotification", "NSOperation", "NSProcessInfo", "NSString", "NSURL"] }
block2 = "0.6"
+213 -13
View File
@@ -11,26 +11,51 @@ use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize};
pub const DEFAULT_SIZE: [f32; 2] = [1440.0, 900.0];
/// The smallest window, in points.
pub const MIN_SIZE: [f32; 2] = [800.0, 500.0];
/// Room the first window leaves around itself for a taskbar, Dock or menu bar (the system doesn't
/// say how much of the screen they take): a monitor with less room opens it maximized.
/// Room the first window leaves around itself for a taskbar, Dock or menu bar when it decides
/// whether to open maximized: a monitor with less room opens it maximized. This check uses the
/// fixed allowance on every platform, including where the system reports a work area.
const SCREEN_ROOM: [f32; 2] = [64.0, 128.0];
/// Seconds between readings of the monitor list, which picks up a monitor connected while the app runs.
const MONITORS_EVERY: f64 = 1.0;
/// A monitor: its top-left corner and size in physical pixels, and its scale factor.
/// A monitor: its top-left corner and size in physical pixels, its scale factor, and the part
/// windows may use where the system reports one.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Monitor {
pos: [i64; 2],
size: [i64; 2],
scale: f32,
/// `[x, y, width, height]` in physical pixels, without the taskbar, Dock or menu bar.
work: Option<[i64; 4]>,
}
/// A monitor's rect and its work area as the system lists them, `[x, y, width, height]` in
/// physical pixels. Only Windows and macOS list them.
#[derive(Clone, Copy, Debug, PartialEq)]
#[cfg_attr(not(any(all(windows, feature = "wgpu"), target_os = "macos")), allow(dead_code))]
pub struct WorkArea {
monitor: [i64; 4],
work: [i64; 4],
}
impl Monitor {
pub fn new(pos: PhysicalPosition<i32>, size: PhysicalSize<u32>, scale: f64) -> Self {
let scale = scale as f32;
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
Self { pos: [pos.x.into(), pos.y.into()], size: [size.width.into(), size.height.into()], scale }
Self { pos: [pos.x.into(), pos.y.into()], size: [size.width.into(), size.height.into()], scale, work: None }
}
/// This monitor with the work area of the entry in `areas` whose monitor rect matches its own,
/// to the pixel either way to allow for rounding. Without a match, or when the matching work
/// area has no width or height, it has none.
fn with_work_area(self, areas: &[WorkArea]) -> Self {
let [x, y] = self.pos;
let [w, h] = self.size;
let rect = [x, y, w, h];
let work =
areas.iter().find(|a| a.monitor.iter().zip(rect).all(|(a, b)| a.abs_diff(b) <= 1)).map(|a| a.work).filter(|&[_, _, w, h]| w > 0 && h > 0);
Self { work, ..self }
}
/// Its size in points.
@@ -38,6 +63,19 @@ impl Monitor {
self.size.map(|s| s as f32 / self.scale)
}
/// This monitor with its work area made smaller by a window frame of `frame` physical pixels
/// (outer size less inner size), so a window whose inner size fits the result fits the work area
/// with its frame.
fn less_frame(self, frame: [i64; 2]) -> Self {
let work = self.work.map(|[x, y, w, h]| [x, y, (w - frame[0].max(0)).max(1), (h - frame[1].max(0)).max(1)]);
Self { work, ..self }
}
/// The size of its work area in points, or of the whole monitor when it has none.
fn work_points(&self) -> [f32; 2] {
self.work.map_or_else(|| self.points(), |[_, _, w, h]| [w, h].map(|s| s as f32 / self.scale))
}
/// Its size in points less room for a taskbar, Dock or menu bar.
fn usable(&self) -> [f32; 2] {
let points = self.points();
@@ -61,24 +99,31 @@ impl Monitor {
}
/// The top-left corner nearest to `pos` (centred when none) that keeps a window of `size`
/// points on this monitor.
/// points on this monitor, inside its work area when it has one. A window bigger than the area
/// gets the area's top-left corner.
fn keep_on(&self, pos: Option<[i32; 2]>, size: [f32; 2]) -> [i32; 2] {
let px = self.pixels(size);
let [x, y] = self.pos;
let [w, h] = self.size;
let [ax, ay, aw, ah] = self.work.unwrap_or([x, y, w, h]);
let (start, extent) = ([ax, ay], [aw, ah]);
std::array::from_fn(|i| {
let lo = self.pos[i];
let hi = lo + self.size[i].saturating_sub(px[i]).max(0);
let lo = start[i];
let hi = lo + extent[i].saturating_sub(px[i]).max(0);
let want = pos.map_or(lo + (hi - lo) / 2, |p| i64::from(p[i]));
i32::try_from(want.max(lo).min(hi)).unwrap_or_default()
})
}
/// This monitor for floating panels, in the points egui reports for a window on it: physical
/// pixels divided by the monitor's scale factor and the UI zoom.
/// pixels divided by the monitor's scale factor and the UI zoom. The work area is converted the
/// same way.
fn docking(&self, name: Option<String>, zoom: f32) -> DockMonitor {
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, work_area: None }
let points = |rect: [i64; 4]| rect.map(|v| v as f32 / scale);
DockMonitor { name, rect: points([x, y, w, h]), scale, work_area: self.work.map(points) }
}
}
@@ -108,7 +153,10 @@ pub fn place(saved: Option<WindowGeometry>, monitors: &[Monitor], home: Option<u
// Bigger than its monitor (a smaller screen than last time): maximized, like the first window.
let room = m.points();
let too_big = (0..2).any(|i| saved.size[i] > room[i]);
let size = fit(saved.size, if too_big { m.usable() } else { room });
// No bigger than the work area either, so the window fits below or beside the taskbar.
let work = m.work_points();
let room = if too_big { m.usable() } else { room };
let size = fit(saved.size, std::array::from_fn(|i| room[i].min(work[i])));
WindowGeometry {
// Moved fully onto its monitor, or centred on the home monitor.
pos: saved.pos.map(|p| m.keep_on(shown.map(|_| p), size)),
@@ -128,12 +176,94 @@ pub fn monitors_due(listed: Option<(f64, f32)>, now: f64, zoom: f32) -> bool {
listed.is_none_or(|(at, listed_zoom)| listed_zoom != zoom || now - at >= MONITORS_EVERY)
}
/// The connected monitors for floating panels (`Services::dock_monitors`).
/// The connected monitors for floating panels (`Services::dock_monitors`), with the work area the
/// system reports for each (Windows and macOS).
pub fn dock_monitors(window: &winit::window::Window, zoom: f32) -> Vec<DockMonitor> {
let monitors: Vec<_> = window.available_monitors().map(|m| (Monitor::new(m.position(), m.size(), m.scale_factor()), m.name())).collect();
let areas = work_areas::list();
let monitors: Vec<_> =
window.available_monitors().map(|m| (Monitor::new(m.position(), m.size(), m.scale_factor()).with_work_area(&areas), m.name())).collect();
docking_list(&monitors, zoom, cfg!(target_os = "macos"))
}
/// A rect in macOS screen coordinates (points, origin at the bottom-left of the primary screen,
/// y up) in the physical pixels winit gives a monitor's position and size: points from the top-left
/// of the primary screen, `primary_height` points tall, times `scale`.
#[cfg(any(target_os = "macos", test))]
fn from_bottom_left([x, y, w, h]: [f64; 4], primary_height: f64, scale: f64) -> Option<[i64; 4]> {
let rect = [x, primary_height - (y + h), w, h].map(|v| (v * scale).round());
// `as` saturates; a coordinate of 1e12 pixels or more is not a monitor's.
rect.iter().all(|v| v.is_finite() && v.abs() < 1e12).then(|| rect.map(|v| v as i64))
}
/// Each monitor's rect and work area as the system reports them.
mod work_areas {
pub use platform::list;
/// `GetMonitorInfo` for every monitor: `rcMonitor` and `rcWork`, in the physical pixels winit
/// reports for a per-monitor DPI aware process.
#[cfg(all(windows, feature = "wgpu"))]
mod platform {
use super::super::WorkArea;
use winsafe::prelude::Handle;
use winsafe::{HDC, RECT};
pub fn list() -> Vec<WorkArea> {
let rect = |r: RECT| {
let [left, top, right, bottom] = [r.left, r.top, r.right, r.bottom].map(i64::from);
[left, top, right - left, bottom - top]
};
let mut areas = Vec::new();
// Without a list the panels keep to the monitors' whole rects, as before.
let _ = HDC::NULL.EnumDisplayMonitors(None, |monitor, _, _| {
if let Ok(info) = monitor.GetMonitorInfo() {
areas.push(WorkArea { monitor: rect(info.rcMonitor), work: rect(info.rcWork) });
}
true
});
areas
}
}
/// `NSScreen`'s `frame` and `visibleFrame` for every screen, turned into the top-left origin
/// and physical pixels winit uses for its monitors.
#[cfg(target_os = "macos")]
mod platform {
use super::super::{WorkArea, from_bottom_left};
use objc2_app_kit::NSScreen;
use objc2_foundation::{MainThreadMarker, NSRect};
pub fn list() -> Vec<WorkArea> {
// `NSScreen::screens` needs the main thread, where the UI frame runs.
let Some(mtm) = MainThreadMarker::new() else {
return Vec::new();
};
let screens: Vec<_> = NSScreen::screens(mtm).iter().collect();
// The first screen holds the menu bar and is the origin of the screen coordinates.
let Some(primary) = screens.first().map(|s| s.frame().size.height) else {
return Vec::new();
};
let rect = |r: NSRect| [r.origin.x, r.origin.y, r.size.width, r.size.height];
screens
.iter()
.filter_map(|s| {
let scale = s.backingScaleFactor();
let monitor = from_bottom_left(rect(s.frame()), primary, scale)?;
let work = from_bottom_left(rect(s.visibleFrame()), primary, scale)?;
Some(WorkArea { monitor, work })
})
.collect()
}
}
/// No work areas: the panels keep to the monitors' whole rects.
#[cfg(not(any(all(windows, feature = "wgpu"), target_os = "macos")))]
mod platform {
pub fn list() -> Vec<super::super::WorkArea> {
Vec::new()
}
}
}
/// The list for floating panels, empty when `monitors` have different scales and `shared_points` is
/// false. macOS has one desktop of points. Elsewhere a new window multiplies its saved position by the
/// scale of the monitor it is created on, which can put a window saved on another scale off every
@@ -154,7 +284,19 @@ fn docking_list(monitors: &[(Monitor, Option<String>)], zoom: f32, shared_points
/// until the host reports maximized (fixes #3635).
pub fn restore(window: &winit::window::Window, saved: Option<WindowGeometry>) -> WindowGeometry {
let handles: Vec<_> = window.available_monitors().collect();
let monitors: Vec<Monitor> = handles.iter().map(|m| Monitor::new(m.position(), m.size(), m.scale_factor())).collect();
let areas = work_areas::list();
// The system title bar and border, which the inner size leaves out, in points: each monitor
// draws them at its own scale.
let (outer, inner, scale) = (window.outer_size(), window.inner_size(), window.scale_factor());
let scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
let frame = [outer.width.saturating_sub(inner.width), outer.height.saturating_sub(inner.height)].map(|px| f64::from(px) / scale);
let monitors: Vec<Monitor> = handles
.iter()
.map(|m| {
let px = frame.map(|f| (f * m.scale_factor()).ceil().min(1e6) as i64);
Monitor::new(m.position(), m.size(), m.scale_factor()).with_work_area(&areas).less_frame(px)
})
.collect();
let home = window.current_monitor().or_else(|| window.primary_monitor()).and_then(|c| handles.iter().position(|m| *m == c));
let g = place(saved, &monitors, home);
if let Some([x, y]) = g.pos {
@@ -257,6 +399,64 @@ mod tests {
assert_eq!(zoomed, DockMonitor { name: Some("m".into()), rect: [-2048.0, 0.0, 2048.0, 1152.0], scale: 1.25, work_area: None });
}
#[test]
fn floating_panels_get_each_monitors_work_area_in_the_same_points() {
// A 4K monitor at 200% with a 96-pixel taskbar along its bottom, and one at 100% to its
// right with a 48-pixel taskbar along its left edge.
let areas = [
WorkArea { monitor: [0, 0, 3840, 2160], work: [0, 0, 3840, 2064] },
WorkArea { monitor: [3840, 0, 1920, 1080], work: [3888, 0, 1872, 1080] },
];
let left = monitor(0, 0, 3840, 2160, 2.0).with_work_area(&areas);
assert_eq!(left.docking(None, 1.0).work_area, Some([0.0, 0.0, 1920.0, 1032.0]));
// The UI zoom divides the work area as it divides the rect.
assert_eq!(left.docking(None, 1.25).work_area, Some([0.0, 0.0, 1536.0, 825.6]));
// Rounding of a fractional scale can move a rect by a pixel.
let right = monitor(3841, 0, 1919, 1080, 1.0).with_work_area(&areas);
assert_eq!(right.docking(None, 1.0).work_area, Some([3888.0, 0.0, 1872.0, 1080.0]));
// A monitor the system did not list keeps to its whole rect.
let other = monitor(5760, 0, 1920, 1080, 1.0).with_work_area(&areas);
assert_eq!(other.docking(None, 1.0).work_area, None);
assert_eq!(monitor(0, 0, 3840, 2160, 2.0).with_work_area(&[]).docking(None, 1.0).work_area, None);
// A work area with no height is left out, so the monitor keeps to its whole rect.
let flat = [WorkArea { monitor: [0, 0, 1920, 1080], work: [0, 1080, 1920, 0] }];
assert_eq!(monitor(0, 0, 1920, 1080, 1.0).with_work_area(&flat).docking(None, 1.0).work_area, None);
}
#[test]
fn a_restored_window_keeps_its_title_bar_out_of_a_taskbar_along_the_top() {
// A 1920 × 1080 monitor with a 48-pixel taskbar along its top edge.
let areas = [WorkArea { monitor: [0, 0, 1920, 1080], work: [0, 48, 1920, 1032] }];
let m = [monitor(0, 0, 1920, 1080, 1.0).with_work_area(&areas)];
// A window saved at the top edge moves down below the taskbar.
let g = place(saved(Some([100, 0]), [1000.0, 700.0], false), &m, Some(0));
assert_eq!(g.pos, Some([100, 48]));
// A window that fits below the taskbar keeps its place.
assert_eq!(place(saved(Some([100, 200]), [1000.0, 700.0], false), &m, Some(0)).pos, Some([100, 200]));
// A window taller than the work area is made as tall as the work area and placed in it.
let tall = place(saved(Some([0, 0]), [1900.0, 1060.0], false), &m, Some(0));
assert_eq!((tall.pos, tall.size), (Some([0, 48]), [1900.0, 1032.0]));
// With a system frame of 16 × 39 pixels the inner size leaves room for it.
let framed = [m[0].less_frame([16, 39])];
let tall = place(saved(Some([0, 0]), [1900.0, 1060.0], false), &framed, Some(0));
assert_eq!((tall.pos, tall.size), (Some([0, 48]), [1900.0, 993.0]));
// Without a work area the frame leaves the monitor's rect as it was.
assert_eq!(monitor(0, 0, 1920, 1080, 1.0).less_frame([16, 39]).work, None);
}
#[test]
fn macos_screen_rects_turn_into_winits_top_left_pixels() {
// A 1512 × 982 point primary screen at 2× with a 37-point menu bar and an 80-point Dock,
// and a 1920 × 1080 screen at 1× above it, its bottom-left 200 points right of the
// primary's top-left.
let primary = 982.0;
assert_eq!(from_bottom_left([0.0, 0.0, 1512.0, 982.0], primary, 2.0), Some([0, 0, 3024, 1964]));
assert_eq!(from_bottom_left([0.0, 80.0, 1512.0, 865.0], primary, 2.0), Some([0, 74, 3024, 1730]));
assert_eq!(from_bottom_left([200.0, 982.0, 1920.0, 1080.0], primary, 1.0), Some([200, -1080, 1920, 1080]));
assert_eq!(from_bottom_left([f64::NAN, 0.0, 1.0, 1.0], primary, 1.0), None);
assert_eq!(from_bottom_left([0.0, 0.0, 1e300, 1.0], primary, 1.0), None);
}
#[test]
fn monitors_of_different_scales_are_listed_only_on_a_desktop_of_shared_points() {
let named = |m: Monitor, name: &str| (m, Some(name.to_string()));
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 9h10l-5 8.7z" fill="currentColor" stroke="none"/><path d="M3 9h18"/><path d="M5 5.5 14.5 22"/><path d="M19 5.5 9.5 22"/></svg>

After

Width:  |  Height:  |  Size: 321 B

+3
View File
@@ -21,3 +21,6 @@ proptest = { workspace = true }
# The tests build containers and decode previews.
crc32fast = { workspace = true }
craft-image-codecs = { workspace = true }
# tests/it's `import_limits`, `outline_limits` and `text` modules need `synth`, also when this crate
# is tested without vectorcraft-engine (`cargo xtask ci shard`).
vectorcraft-affinity = { path = ".", features = ["synth"] }
+3 -53
View File
@@ -639,8 +639,7 @@ fn jpeg_icc(bytes: &[u8]) -> Option<Vec<u8>> {
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
/// the count of segments.
#[cfg(test)]
const ICC_SEGMENT: &[u8; 12] = b"ICC_PROFILE\0";
/// JPEG `bytes` carrying `icc` in place of the ICC profile they carry, if any: every
@@ -649,63 +648,14 @@ const ICC_SEGMENT: &[u8; 12] = b"ICC_PROFILE\0";
/// for bytes whose segments before the scan can't be read, an empty `icc`, and one longer than 255
/// segments hold.
pub fn jpeg_with_icc(bytes: &[u8], icc: &[u8]) -> Option<Vec<u8>> {
// A segment's length counts itself (2 bytes) and the name, number and count (14).
const CHUNK: usize = 0xFFFF - 2 - ICC_SEGMENT.len() - 2;
let chunks: Vec<&[u8]> = icc.chunks(CHUNK).collect();
let count = u8::try_from(chunks.len()).ok().filter(|n| *n > 0)?;
let mut segments = Vec::with_capacity(icc.len() + 18 * chunks.len());
for (i, chunk) in chunks.iter().enumerate() {
let len = u16::try_from(chunk.len() + 2 + ICC_SEGMENT.len() + 2).ok()?;
segments.extend_from_slice(&[0xFF, 0xE2]);
segments.extend_from_slice(&len.to_be_bytes());
segments.extend_from_slice(ICC_SEGMENT);
segments.extend_from_slice(&[u8::try_from(i + 1).ok()?, count]);
segments.extend_from_slice(chunk);
}
with_icc_segments(bytes, segments)
craft_image_codecs::jpeg_inks::jpeg_with_icc(bytes, icc)
}
/// JPEG `bytes` without the ICC profile they carry: every `ICC_PROFILE` APP2 segment before the
/// scan taken out, and the other segments and the scan as they are. `None` for bytes whose
/// segments before the scan can't be read.
pub fn jpeg_without_icc(bytes: &[u8]) -> Option<Vec<u8>> {
with_icc_segments(bytes, vec![])
}
/// JPEG `bytes` with every `ICC_PROFILE` APP2 segment before the scan taken out and `segments`
/// written after the leading application segments; `None` when the bytes don't start a JPEG or
/// their segments before the scan can't be read.
fn with_icc_segments(bytes: &[u8], segments: Vec<u8>) -> Option<Vec<u8>> {
if !bytes.starts_with(&[0xFF, 0xD8]) {
return None;
}
let mut out = Vec::with_capacity(bytes.len() + segments.len());
out.extend_from_slice(&[0xFF, 0xD8]);
let mut icc_segments = Some(segments);
let mut at = 2;
// The segments before the scan (SOS), each with its length; a marker without one ends them.
// Fill bytes (0xFF) before a marker are left out.
loop {
while bytes.get(at..at + 2) == Some(&[0xFF, 0xFF]) {
at += 1;
}
let (Some(&0xFF), Some(&marker)) = (bytes.get(at), bytes.get(at + 1)) else { return None };
let app = (0xE0..=0xEF).contains(&marker);
if !app && let Some(s) = icc_segments.take() {
out.extend_from_slice(&s);
}
if matches!(marker, 0xDA | 0xD8 | 0xD9 | 0x01 | 0xD0..=0xD7) {
break;
}
let len = usize::from(u16::from_be_bytes(bytes.get(at + 2..at + 4)?.try_into().ok()?));
let segment = bytes.get(at..(at + 2).checked_add(len)?).filter(|_| len >= 2)?;
if !(marker == 0xE2 && segment.get(4..16) == Some(ICC_SEGMENT.as_slice())) {
out.extend_from_slice(segment);
}
at += segment.len();
}
out.extend_from_slice(bytes.get(at..)?);
Some(out)
craft_image_codecs::jpeg_inks::jpeg_without_icc(bytes)
}
/// `icc` when it is a profile of CMYK colors, which the samples of a CMYK image are in.
+2 -2
View File
@@ -198,8 +198,8 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
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, 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"}}),
"{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), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the puffed front and back, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind and takes graphics with bothSides and cap on), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the art's plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); carried straight out from the art's plane onto the puffed face, twist and taper turning and shrinking the back's with it, shaded with the surface and drawn only where its outside faces the viewer), 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,"graphics":[],"render":{"mode":"shaded"}}),
),
g(
ROTATE,
+11 -2
View File
@@ -229,11 +229,20 @@ pub(crate) fn seamed_fill(path: &vectorcraft_geom::PathData, seam: f64) -> Optio
/// footprints. Where two facets' antialiased edges meet, the underlay fills what they leave
/// uncovered with the neighbors' own colors, so the background does not show through. `None` unless
/// 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.
/// in a clip of its footprint, neither with an opacity mask. A face drawn with the parts of Inflate's
/// graphics on it, a group of the facet and those parts, takes its facet's underlay and stays in the
/// order with its parts, which are cut to the facet's outline, so the clip keeps them.
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)?;
let facets: Vec<Arc<Node>> = faces
.iter()
.map(|face| match &face.kind {
NodeKind::Group { children, clip: false } if face.extras().mask.is_none() => children.first().cloned(),
_ => Some(face.clone()),
})
.collect::<Option<_>>()?;
let (clip, mut underlay) = underlay(id, &facets)?;
underlay.extend(faces.iter().cloned());
Some(Node::new(id, NodeKind::Group { children: vec![Arc::new(clip), Arc::new(Node::group(id, underlay))], clip: true }))
}
+2 -1
View File
@@ -382,7 +382,8 @@ fn revolve_takes_graphics_on_its_side_only() {
let kept = three_d_params_as(crate::EXTRUDE, &both, REVOLVE);
assert_eq!(kept["graphics"].as_array().map(Vec::len), Some(1));
assert_eq!(kept["graphics"][0]["symbol"], "Red");
assert_eq!(three_d_params_as(REVOLVE, &front, crate::INFLATE).get("graphics"), None);
// Inflate keeps them, and its front takes them.
assert_eq!(three_d_params_as(REVOLVE, &front, crate::INFLATE)["graphics"], front["graphics"]);
}
#[test]
+136 -35
View File
@@ -98,13 +98,15 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value {
}
}
// A plane has only a front, and Revolve's graphics go on its side, named the front, so graphics
// on the back cap and on Extrude & Bevel's side are dropped.
if (to == ROTATE || to == crate::REVOLVE)
// on the back cap and on Extrude & Bevel's side are dropped. Inflate takes graphics on its front
// and back, so it drops those on the side.
if (to == ROTATE || to == crate::REVOLVE || to == INFLATE)
&& let Some(Value::Array(list)) = out.get_mut(GRAPHICS)
{
let back = to != INFLATE;
list.retain(|g| {
let face = g.get("face").and_then(Value::as_str);
face != Some(PlanarFace::Back.id()) && face != Some(PlanarFace::Side.id())
!(back && face == Some(PlanarFace::Back.id())) && face != Some(PlanarFace::Side.id())
});
}
Value::Object(out)
@@ -259,6 +261,7 @@ pub fn inflate_options(p: &Value) -> Inflate {
twist: num(p, "twist", 0.0),
taper: num(p, "taper", 100.0) / 100.0,
cap: flag(p, "cap", true),
map_surface: false,
}
}
@@ -444,7 +447,8 @@ pub fn validate_solid_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value)
/// Inflate or Rotate, as drawn, or a new one after its other effects when it has none.
fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: (Option<usize>, Option<usize>)) -> Result<(), String> {
validate_solid_params(id, p)?;
if let Some(doc) = doc {
// In wireframe mode the edges are drawn with no graphics, and their art is not checked.
if let Some(doc) = doc.filter(|_| !wireframe::wireframe_params(id, p)) {
graphics::validate_symbols(doc, p)?;
}
let label = label_of(id);
@@ -461,7 +465,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?;
check_profiles(id, p, &shapes, b)?;
check_solids(id, p, &shapes)?;
return check_side_graphics(doc, n, id, p, &shapes);
check_side_graphics(doc, n, id, p, &shapes)?;
return check_membrane_graphics(doc, n, id, p, &shapes);
}
let (path, rule) = object_profile(n, label)?;
let anchors = || format!("{label} requires a shape with at least two anchors");
@@ -479,7 +484,8 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at:
let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }];
check_profiles(id, p, &shapes, b)?;
check_solids(id, p, &shapes)?;
check_side_graphics(doc, n, id, p, &shapes)
check_side_graphics(doc, n, id, p, &shapes)?;
check_membrane_graphics(doc, n, id, p, &shapes)
}
/// Does 3D effect `id` with parameters `p` cast a shadow: is it Extrude & Bevel, Inflate or Rotate
@@ -493,6 +499,30 @@ fn visible(item: &AppearanceItem, member: f32) -> bool {
paint_of(item, member).1 > 0.0
}
/// An error when the graphics of Inflate `id` with parameters `p`, with the symbols of `doc`, are
/// past their limits on the front and puffed back of the solids of `shapes`: their art, or the
/// parts they draw on its pieces ([`graphics::surface_parts`]), or when the solids can't be built
/// with their pieces carrying the graphics. They are built as the art builds them
/// ([`surfaces_with`]). Without `doc` nothing is drawn, and nothing is checked. In wireframe mode no
/// graphics are drawn, and none are checked.
fn check_membrane_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
let Some(doc) = doc else { return Ok(()) };
if id != INFLATE || wireframe::wireframe_params(id, p) || mapped_graphics(p).is_empty() {
return Ok(());
}
for face in [PlanarFace::Front, PlanarFace::Back] {
graphics::validate_surface_symbols(doc, p, face)?;
}
let fx = Effect { id: id.into(), params: p.clone(), visible: true };
let mut dropped = false;
// Art that can't be built with the graphics draws without them.
let built = surfaces_with(Some(doc), n, &fx, shapes, false, true, &mut dropped);
if dropped || built.is_none() {
return Err("The graphics are too complex: simplify the symbols' art".into());
}
Ok(())
}
/// An error when the graphics on the side of Extrude & Bevel `id` with parameters `p`, with the
/// symbols of `doc`, are past their limits on the side of the solid of `shapes` that takes them
/// ([`side_carrier`]): their art, or the parts they draw on its pieces
@@ -521,7 +551,7 @@ fn check_side_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value, sh
let fx = Effect { id: id.into(), params: p.clone(), visible: true };
let mut dropped = false;
// Art that can't be built draws the source path, without the side's graphics.
let built = surfaces_with(Some(doc), n, &fx, shapes, false, &mut dropped);
let built = surfaces_with(Some(doc), n, &fx, shapes, false, false, &mut dropped);
if dropped || built.is_none() {
return Err("The graphics are too complex: simplify the symbols' art".into());
}
@@ -572,7 +602,7 @@ fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> {
if !cast {
return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ()));
}
let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, None)
let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, false, None)
.map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces)))
.collect::<Result<Vec<_>, String>>()?;
cast_built(id, p, shapes, built).map(|_| ())
@@ -846,11 +876,37 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
group
}
/// The parts of `graphics` that fall on each of `facets`, the facets of one of Inflate's solids in
/// drawing order, built with their front and puffed back carrying the graphics
/// ([`vectorcraft_three_d::Inflate::map_surface`]): for each facet, the parts of the graphics on
/// its face to draw right after it ([`graphics::surface_parts`]), shaded as a solid color is on
/// that facet. `copies` counts the bytes of the paint copies of the object's graphics. `None` past
/// the graphics' limits.
fn membrane_parts(
doc: Option<&Document>,
id: NodeId,
graphics: &[MappedGraphic],
facets: &[Facet],
copies: &mut usize,
) -> Option<Vec<Vec<Arc<Node>>>> {
let shade = |f: &graphics::OnFace<'_>, c: vectorcraft_doc::color::Color| Paint::solid(crate::lighting::shade(c, f.facet.illumination));
let mut out: Vec<Vec<Arc<Node>>> = vec![vec![]; facets.len()];
for face in [PlanarFace::Front, PlanarFace::Back].into_iter().filter(|face| graphics.iter().any(|g| g.face == *face)) {
let on: Vec<graphics::OnFace<'_>> = facets.iter().map(|facet| graphics::OnFace { facet, face }).collect();
let parts = graphics::surface_parts(doc, id, (graphics, face), &on, &shade, copies)?;
for (slot, extra) in out.iter_mut().zip(parts) {
slot.extend(extra);
}
}
Some(out)
}
/// `surface`, a plain group of one face for each facet ([`surface`]), with each face followed by
/// the parts of the side's graphics that `parts` holds for its facet ([`graphics::surface_parts`]):
/// a face with parts becomes a group of the face and its parts, so nearer faces drawn after it
/// cover them too. `surface` is returned as it is when no facet has a part or it is not such a group.
fn with_side_parts(id: NodeId, mut surface: Node, parts: Vec<Vec<Arc<Node>>>) -> Node {
/// the parts of the graphics that `parts` holds for its facet (on Extrude & Bevel's side
/// [`graphics::surface_parts`], on Inflate's front and back [`membrane_parts`]): a face with parts
/// becomes a group of the face and its parts, so nearer faces drawn after it cover them too.
/// `surface` is returned as it is when no facet has a part or it is not such a group.
fn with_surface_parts(id: NodeId, mut surface: Node, parts: Vec<Vec<Arc<Node>>>) -> Node {
if parts.iter().all(Vec::is_empty) {
return surface;
}
@@ -984,7 +1040,7 @@ fn built_solids<'a>(
bounds: Rect,
limit: usize,
) -> impl Iterator<Item = Result<Option<Vec<Facet>>, String>> + 'a {
built_solids_cast(id, p, parts, bounds, limit, false, None).map(|r| r.map(|s| s.map(|(f, _)| f)))
built_solids_cast(id, p, parts, bounds, limit, false, false, None).map(|r| r.map(|s| s.map(|(f, _)| f)))
}
/// One solid's facets and, when its shadow is cast, the faces it is cast from.
@@ -995,9 +1051,12 @@ type CastingSolid = (Vec<Facet>, Option<SolidFaces>);
type SurfacesAndFaces = (Vec<Arc<Node>>, Vec<Option<SolidFaces>>);
/// [`built_solids`], and with `cast` for Extrude & Bevel or Inflate each solid's faces its shadow
/// is cast from, from the same build ([`SolidFaces`]). The solid of part `side`, when there is one,
/// is built with the pieces of its side carrying where they lie on it unrolled, for the graphics
/// on Extrude & Bevel's side ([`side_carrier`]).
/// is cast from, from the same build ([`SolidFaces`]). With `membrane`, Inflate's solids are built
/// with the pieces of their front and puffed back carrying where they lie in the art's plane, for
/// the graphics drawn on them ([`vectorcraft_three_d::Inflate::map_surface`]). The solid of part
/// `side`, when there is one, is built with the pieces of its side carrying where they lie on it
/// unrolled, for the graphics on Extrude & Bevel's side ([`side_carrier`]).
#[allow(clippy::too_many_arguments)] // the build's inputs and the two surfaces that carry graphics
fn built_solids_cast<'a>(
id: &'a str,
p: &'a Value,
@@ -1005,12 +1064,13 @@ fn built_solids_cast<'a>(
bounds: Rect,
limit: usize,
cast: bool,
membrane: bool,
side: Option<usize>,
) -> impl Iterator<Item = Result<Option<CastingSolid>, String>> + 'a {
// Inflate's eye is placed for every puff together, as far away as the highest needs.
let mut inflated = (id == INFLATE).then(|| -> Box<dyn Iterator<Item = Result<CastingSolid, String>>> {
let shapes: Vec<(&PathData, FillRule)> = parts.iter().map(|(_, _, area, rule, _, _)| (area, *rule)).collect();
let (o, view) = (inflate_options(p), view_options(p));
let (o, view) = (Inflate { map_surface: membrane, ..inflate_options(p) }, view_options(p));
if cast {
Box::new(vectorcraft_three_d::inflate_shadowed(&shapes, bounds, o, view).map(|r| r.map(|(f, faces)| (f, Some(faces)))))
} else {
@@ -1962,14 +2022,33 @@ fn seen_ends(f: &[Facet]) -> impl Iterator<Item = &Facet> {
/// [`art_for`] without the shadow: the solids' surfaces, with the graphics mapped onto their planar
/// faces drawn right after the last of the solids' surfaces that holds that face. With `cast`, each
/// solid built also keeps the faces its shadow is cast from, from the same build, in the order the
/// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art.
/// solids are built ([`cast_built`]); `None` for a stroke's solid left out of the art. Inflate's
/// graphics are drawn on the pieces of its front and puffed back; when its solids can't be built
/// with those pieces, or the graphics are past their limits on them, the solids draw without them.
fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool) -> Option<SurfacesAndFaces> {
surfaces_with(doc, n, fx, shapes, cast, &mut false)
let p = crate::merged_params(&fx.id, &fx.params);
if fx.id == INFLATE && doc.is_some() && !mapped_graphics(&p).is_empty() {
let mut dropped = false;
if let Some(built) = surfaces_with(doc, n, fx, shapes, cast, true, &mut dropped).filter(|_| !dropped) {
return Some(built);
}
}
surfaces_with(doc, n, fx, shapes, cast, false, &mut false)
}
/// [`surfaces_for`], setting `side_dropped` when the graphics on Extrude & Bevel's side are past
/// their limits on the pieces drawn, and the solid that takes them draws without them.
fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile], cast: bool, side_dropped: &mut bool) -> Option<SurfacesAndFaces> {
/// [`surfaces_for`], with `membrane` building Inflate's solids with their front and puffed back
/// carrying the graphics ([`built_solids_cast`]), and setting `dropped` when those graphics, or the
/// graphics on Extrude & Bevel's side, are past their limits on the pieces drawn and the solid that
/// takes them draws without them.
fn surfaces_with(
doc: Option<&Document>,
n: &Node,
fx: &Effect,
shapes: &[Profile],
cast: bool,
membrane: bool,
dropped: &mut bool,
) -> Option<SurfacesAndFaces> {
let b = union_bounds(shapes)?;
let p = crate::merged_params(&fx.id, &fx.params);
let classic = fx.id == CLASSIC_EXTRUDE || fx.id == CLASSIC_ROTATE;
@@ -2025,7 +2104,7 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil
let map_art = MapArt::of(doc, &fx.id, &p).filter(|_| fx.id == CLASSIC_EXTRUDE);
let mut layouts: Vec<SolidLayout> = vec![];
let mut surfaces_before = 0usize;
let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, carrier);
let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, membrane, carrier);
for (k, ((item, opacity, area, rule, scopes, member), f)) in parts.iter().zip(made).enumerate() {
let item: &AppearanceItem = item;
let layout = map_art.as_ref().map(|_| {
@@ -2044,11 +2123,12 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil
layouts.extend(layout);
built.push(faces);
}
// A stroke's outline past the limits is left out; the fill's solid still draws, and
// A stroke's outline past the limits is left out; the fill's solid still draws. Built
// with the graphics' pieces, a stroke past the limits draws without the graphics, and
// the side's graphics on that outline are not drawn.
Ok(None) => {
built.push(None);
*side_dropped |= carrier == Some(k);
*dropped |= membrane || carrier == Some(k);
}
// A loaded file or a shape edited past the limits (its own, or those of the object's
// solids together) keeps drawing its source path instead of failing the frame;
@@ -2161,8 +2241,10 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil
// ([`in_one_order`], [`underlaid_surface`]).
let seals: Vec<bool> = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect();
let seal = |range: std::ops::Range<usize>| seals.get(range).is_some_and(|s| s.iter().any(|s| *s));
let membrane_graphics = if membrane && graphics_on { mapped_graphics(&p) } else { vec![] };
let side_graphics = carrier.map(|_| mapped_graphics(&p)).unwrap_or_default();
// The paint copies of the side's graphics, apart from those of the surfaces, as on Revolve.
// The paint copies of Inflate's graphics and of the side's, apart from those of the surfaces,
// as on Revolve.
let mut graphic_copies = 0usize;
let surfaces: Vec<BuiltSurface> = solids
.into_iter()
@@ -2171,22 +2253,29 @@ fn surfaces_with(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profil
let depths: Vec<Placed> = f.iter().map(|f| Placed::of(f, shape, paints)).collect();
let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect();
let (paint, opacity, blend) = paint_of(item, member);
// The carrier's pieces draw the parts of the side's graphics that fall on them; past
// the graphics' limits the solid draws without them.
let parts = if side_graphics.is_empty() || !f.iter().any(|f| f.surface.is_some()) {
// The pieces of Inflate's front and back, and the carrier's pieces of Extrude & Bevel's
// side, draw the parts of the graphics that fall on them; past the graphics' limits the
// solid draws without them.
let parts = if !f.iter().any(|f| f.surface.is_some()) {
vec![]
} else {
} else if !membrane_graphics.is_empty() {
let parts = membrane_parts(doc, n.id, &membrane_graphics, &f, &mut graphic_copies);
*dropped |= parts.is_none();
parts.unwrap_or_default()
} else if !side_graphics.is_empty() {
let shade = |f: &Facet, c: vectorcraft_doc::color::Color| Paint::solid(crate::lighting::shade(c, f.illumination));
let parts = graphics::surface_parts(doc, n.id, (&side_graphics, PlanarFace::Side), &f, &shade, &mut graphic_copies);
*side_dropped |= parts.is_none();
*dropped |= parts.is_none();
parts.unwrap_or_default()
} else {
vec![]
};
let drawn = parts.iter().any(|p| !p.is_empty());
let art = if classic {
classic_arts.next().unwrap_or_else(|| Node::group(n.id, vec![]))
} else {
let faces = drawn || (split && shared.get(shape).copied().unwrap_or(false));
with_side_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts)
with_surface_parts(n.id, surface(n, f, &paint, opacity, blend, colored, faces), parts)
};
(depths, art, scopes, ends)
})
@@ -2476,14 +2565,15 @@ fn group_solid_art(doc: Option<&Document>, n: &Node) -> Option<Node> {
/// Where the graphics of the 3D effect of `n` (on the object itself with `item` `None`, else on its
/// fill or stroke `item`) are drawn: the bounds its solids are built with and the maps of their
/// planar faces ([`graphics::GraphicFrame`]). `None` when `n` has no visible Extrude & Bevel or
/// Rotate there, or its art can't be built.
/// planar faces, or Inflate's puffed faces ([`graphics::GraphicFrame`]). `None` when `n` has no
/// visible Extrude & Bevel, Inflate or Rotate there, or its art can't be built.
pub fn graphic_frame(doc: Option<&Document>, n: &Node, item: Option<usize>) -> Option<graphics::GraphicFrame> {
frame_of(doc, n, item, &solid)
}
/// [`graphic_frame`] of the 3D effect at `index` in that list, which must be a visible Extrude &
/// Bevel, Rotate or Revolve. Revolve's frame is its unrolled side seen from the front, centered on
/// Bevel, Rotate, Revolve or Inflate. Inflate's frame places handles on the pieces of its puffed
/// front and back the viewer sees. Revolve's frame is its unrolled side seen from the front, centered on
/// the origin, with no face maps: it sizes a new graphic and places no handles.
pub fn graphic_frame_at(doc: Option<&Document>, n: &Node, item: Option<usize>, index: usize) -> Option<graphics::GraphicFrame> {
frame_of(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && is_three_d(&e.id)).map(|e| (index, e)))
@@ -2546,6 +2636,17 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option<usize>, pick: &Pick<'
return Some(graphics::GraphicFrame::new(b, plane, None));
}
let (parts, bounds) = solid_parts(&shapes, b);
if fx.id == INFLATE {
// Inflate's graphics lie on its puffed front and back: the pieces the viewer sees place
// their handles. A stroke left out places none of its own. When a fill's solid can't be
// built, or the solids together pass the limit, the art draws its source and no piece
// places a handle.
let built: Vec<Facet> = built_solids_cast(INFLATE, &p, &parts, bounds, MAX_OBJECT_FACES, false, true, None)
.collect::<Result<Vec<_>, String>>()
.map(|solids| solids.into_iter().flatten().flat_map(|(f, _)| f).collect())
.unwrap_or_default();
return Some(graphics::GraphicFrame::inflated(bounds, graphics::MembraneFrame::of(&built)));
}
let options = extrude_options(&p);
let map = |face| vectorcraft_three_d::extrude_face_map(bounds, options, view, face);
let frame = graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back));
+242 -56
View File
@@ -16,7 +16,14 @@
//! Bevel's side (face `side`) lie on its walls and bevels unrolled the same way, x along the
//! outline and y from the front toward the back, drawn on the pieces of the side of the solid with
//! the longest outline.
//!
//! On Inflate the graphics lie on the puffed front, and on the puffed back when Both Sides is on:
//! each is placed in the art's plane as on Extrude & Bevel's caps and carried straight out onto
//! the surface above it, so it follows the puff. Each piece of the surface draws the part of the
//! graphics that falls on it, as on Revolve's side, and the twist and taper carry the back's
//! graphics with the back.
use std::borrow::Cow;
use std::sync::Arc;
use serde_json::{Map, Value, json};
@@ -24,7 +31,7 @@ use vectorcraft_doc::color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, Symbol};
use vectorcraft_geom::kurbo::{CubicBez, ParamCurve, PathEl, Shape};
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, SubPath, Vec2};
use vectorcraft_three_d::{FaceMap, Facet, PlanarFace};
use vectorcraft_three_d::{DepthPlane, FaceMap, Facet, PlanarFace};
/// The effect parameter that holds the graphics.
pub const GRAPHICS: &str = "graphics";
@@ -50,7 +57,7 @@ const MAX_NESTING: usize = 8;
const MAX_LEVELS: usize = 4 * vectorcraft_doc::MAX_DEPTH;
/// The error for graphics on a 3D effect that takes none.
pub const NOT_TAKEN: &str = "Graphics map onto the Plane, Extrude and Revolve object types";
pub const NOT_TAKEN: &str = "Graphics map onto the Plane, Extrude, Revolve and Inflate object types";
/// The buckets around the unrolled side surface that the pieces of Revolve's graphics are sorted
/// into, so each face looks only at the pieces near it.
@@ -151,10 +158,10 @@ impl MappedGraphic {
}
}
/// The 3D effects that take graphics: Extrude & Bevel (its caps and its side), Rotate (the plane)
/// and Revolve (its swept side).
/// The 3D effects that take graphics: Extrude & Bevel (its caps and its side), Rotate (the plane),
/// Revolve (its swept side) and Inflate (its puffed front and back).
pub fn takes_graphics(id: &str) -> bool {
id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE
id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE || id == super::INFLATE
}
/// The graphics in parameters `p`, leaving out entries that are not valid (a file may hold
@@ -166,9 +173,9 @@ pub fn mapped_graphics(p: &Value) -> Vec<MappedGraphic> {
}
}
/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate and
/// Revolve take graphics; a plane has only a front, and Revolve's graphics go on its side, named
/// the front. Only Extrude & Bevel takes graphics on its side.
/// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate,
/// Revolve and Inflate take graphics; a plane has only a front, and Revolve's graphics go on its
/// side, named the front. Only Extrude & Bevel takes graphics on its side.
pub fn validate(id: &str, p: &Value) -> Result<(), String> {
// Map Art's maps are checked with the graphics: an effect that takes none refuses them.
map_art::validate(id, p)?;
@@ -194,6 +201,9 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> {
if id == crate::REVOLVE && g.face != PlanarFace::Front {
return Err("Revolve maps graphics onto its side: map them onto the front".into());
}
if id == super::INFLATE && g.face == PlanarFace::Side {
return Err("Inflate maps graphics onto its front and back, not onto a side".into());
}
}
Ok(())
}
@@ -629,10 +639,11 @@ struct Unrolled {
place: Affine,
}
/// The areas of `graphics` on `face` (the front, for Revolve's side, or Extrude & Bevel's side)
/// placed on the unrolled side surface, cut into straight pieces. A graphic whose symbol `doc` does
/// not have, or whose art is past the limits of [`pieces_of`], is left out. `None` when the pieces
/// take more than [`MAX_ELEMENTS`] points together.
/// The areas of `graphics` on `face` (the front, for Revolve's side; Extrude & Bevel's side;
/// Inflate's front or back) placed on the unrolled side surface, or in the art's plane about the
/// center of the object's bounds, cut into straight pieces. A graphic whose symbol `doc` does not
/// have, or whose art is past the limits of [`pieces_of`], is left out. `None` when the pieces take
/// more than [`MAX_ELEMENTS`] points together.
fn unrolled(doc: &Document, graphics: &[MappedGraphic], face: PlanarFace) -> Option<Vec<Unrolled>> {
let mut pieces = vec![];
let mut points = 0usize;
@@ -713,9 +724,9 @@ fn straight_pieces(path: &BezPath, points: &mut usize) -> Option<Vec<Vec<Point>>
(*points <= MAX_ELEMENTS).then_some(polygons)
}
/// Do the graphics on `face` in parameters `p` (the front of Revolve, Extrude & Bevel's side) fit
/// the limits with the symbols of `doc`? Their art, cut into straight pieces on the side surface,
/// may take up to [`MAX_ELEMENTS`] points together.
/// Do the graphics on `face` in parameters `p` (the front of Revolve; Extrude & Bevel's side;
/// Inflate's front or back) fit the limits with the symbols of `doc`? Their art, cut into straight
/// pieces on the surface, may take up to [`MAX_ELEMENTS`] points together.
pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value, face: PlanarFace) -> Result<(), String> {
let list = mapped_graphics(p);
if !list.iter().any(|g| g.face == face) || unrolled(doc, &list, face).is_some() {
@@ -724,16 +735,16 @@ pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value, face: PlanarFa
Err("The graphics are too complex: simplify the symbols' art".into())
}
/// A face of a side surface that graphics are drawn on ([`surface_parts`]): a face of Revolve's
/// swept side, or a piece of Extrude & Bevel's walls and bevels.
/// A face of a surface that graphics are drawn on ([`surface_parts`]): a face of Revolve's swept
/// side, a piece of Extrude & Bevel's walls and bevels, or a piece of Inflate's front or back.
pub(crate) trait SurfaceFace {
/// Where the face lies on the side unrolled, when it is a face of the side that shows its
/// outside to the viewer.
/// Where the face lies on the surface, when it carries graphics and shows the surface's outside
/// to the viewer.
fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell>;
/// The outline the face's parts are cut to, when it is not the polygon of its cell's corners:
/// its curved outline, when its edges along an end are curved, or the outline of a piece cut
/// from a larger face.
fn curved(&self) -> Option<std::borrow::Cow<'_, PathData>>;
fn curved(&self) -> Option<Cow<'_, PathData>>;
fn rgb_light(&self) -> Option<vectorcraft_three_d::RgbGradient>;
fn light(&self) -> [f64; 3];
fn outline_path(&self) -> PathData;
@@ -743,8 +754,8 @@ impl SurfaceFace for vectorcraft_three_d::Face {
fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> {
self.surface.as_ref().filter(|c| c.outward && !self.cap)
}
fn curved(&self) -> Option<std::borrow::Cow<'_, PathData>> {
self.outline.as_ref().map(std::borrow::Cow::Borrowed)
fn curved(&self) -> Option<Cow<'_, PathData>> {
self.outline.as_ref().map(Cow::Borrowed)
}
fn rgb_light(&self) -> Option<vectorcraft_three_d::RgbGradient> {
self.rgb_gradient
@@ -757,17 +768,18 @@ impl SurfaceFace for vectorcraft_three_d::Face {
}
}
/// A piece of Extrude & Bevel's side ([`Facet::surface`]).
impl SurfaceFace for Facet {
fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> {
self.surface.as_ref().filter(|c| c.outward)
}
fn curved(&self) -> Option<std::borrow::Cow<'_, PathData>> {
fn curved(&self) -> Option<Cow<'_, PathData>> {
if let Some(outline) = &self.outline {
return Some(std::borrow::Cow::Borrowed(outline));
return Some(Cow::Borrowed(outline));
}
// A piece of a stroke's face cut where it passes through a wall keeps its face's cell.
let cut = self.surface.as_ref().is_some_and(|c| self.contours.len() != 1 || self.contours.first() != Some(&c.page));
cut.then(|| std::borrow::Cow::Owned(self.path()))
cut.then(|| Cow::Owned(self.path()))
}
fn rgb_light(&self) -> Option<vectorcraft_three_d::RgbGradient> {
self.rgb_gradient
@@ -780,18 +792,48 @@ impl SurfaceFace for Facet {
}
}
/// The parts of the graphics on `face` of `graphics` (the front of Revolve, Extrude & Bevel's side)
/// that fall on each of `faces`, a side surface's faces in drawing order, for an object with id
/// `id`: for each face, the nodes to draw right after it. Only faces of the side that show their
/// outside to the viewer carry a part, so a graphic narrows toward the silhouette, is hidden past
/// it and is covered by the nearer faces drawn after it. `shade` gives the paint of a solid color
/// on a face, as the surface under it is shaded; the colors of gradients and patterns are
/// multiplied by the face's light. A graphic whose symbol `doc` does not have, or that is past the
/// limits of its art, draws nothing. `None` past [`MAX_ELEMENTS`] points together before they are
/// cut at the faces, [`MAX_SURFACE_POINTS`] after, [`MAX_SURFACE_CUTS`] points cut, or when the
/// copies of their paints in the parts take `copies`, the bytes of the copies of the object's
/// graphics so far, past Revolve's budget for them: commands refuse such graphics, and a loaded
/// file draws the surface without them.
/// A piece of Inflate's front or back ([`Facet::membrane`]) that carries graphics on `face` only.
pub(crate) struct OnFace<'a> {
pub(crate) facet: &'a Facet,
pub(crate) face: PlanarFace,
}
impl SurfaceFace for OnFace<'_> {
fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> {
self.facet.surface.as_ref().filter(|c| c.outward && self.facet.membrane == Some(self.face))
}
fn curved(&self) -> Option<Cow<'_, PathData>> {
if let Some(outline) = &self.facet.outline {
return Some(Cow::Borrowed(outline));
}
// A piece of a stroke's face cut where it passes through another face keeps its face's
// cell, and its parts are cut to its own outline.
let cut = self.facet.surface.as_ref().is_some_and(|c| self.facet.contours.len() != 1 || self.facet.contours.first() != Some(&c.page));
cut.then(|| Cow::Owned(self.facet.path()))
}
fn rgb_light(&self) -> Option<vectorcraft_three_d::RgbGradient> {
self.facet.rgb_gradient
}
fn light(&self) -> [f64; 3] {
self.facet.illumination
}
fn outline_path(&self) -> PathData {
self.facet.path()
}
}
/// The parts of the graphics on `face` of `graphics` (the front of Revolve; Extrude & Bevel's side;
/// Inflate's front or back) that fall on each of `faces`, a surface's faces in drawing order, for
/// an object with id `id`: for each face, the nodes to draw right after it. Only faces of the
/// surface that show their outside to the viewer carry a part, so a graphic narrows toward the
/// silhouette, is hidden past it and is covered by the nearer faces drawn after it.
/// `shade` gives the paint of a solid color on a face, as the surface under it is shaded; the
/// colors of gradients and patterns are multiplied by the face's light. A graphic whose symbol
/// `doc` does not have, or that is past the limits of its art, draws nothing. `None` past
/// [`MAX_ELEMENTS`] points together before they are cut at the faces, [`MAX_SURFACE_POINTS`]
/// after, [`MAX_SURFACE_CUTS`] points cut, or when the copies of their paints in the parts take
/// `copies`, the bytes of the copies of the object's graphics so far, past Revolve's budget for
/// them: commands refuse such graphics, and a loaded file draws the surface without them.
pub(crate) fn surface_parts<F: SurfaceFace>(
doc: Option<&Document>,
id: NodeId,
@@ -1092,13 +1134,22 @@ pub(super) fn art_bounds(doc: &Document, name: &str) -> Option<Rect> {
/// Where a 3D object's graphics are drawn: the bounds its solids are built with (the graphics'
/// offsets are from their center), the maps of its front and back faces, when it has them, and
/// the visible part of its side unrolled, when it has graphics there.
/// the visible part of its side unrolled, when it has graphics there, and for Inflate the pieces of
/// its puffed faces the viewer sees.
#[derive(Clone, Debug, PartialEq)]
pub struct GraphicFrame {
pub bounds: Rect,
front: Option<FaceMap>,
back: Option<FaceMap>,
side: Option<SideFrame>,
membrane: Option<MembraneFrame>,
}
/// Does triangle `t` hold point `q`, its edges included?
fn in_triangle(t: &[Point; 3], q: Point) -> bool {
let side = |a: Point, b: Point| (b - a).cross(q - a);
let s = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])];
s.iter().all(|v| *v >= -1e-9) || s.iter().all(|v| *v <= 1e-9)
}
/// The pieces of Extrude & Bevel's side that show their outside to the viewer, as the graphics are
@@ -1137,11 +1188,6 @@ impl SideFrame {
/// triangle of its corners on the same side of its diagonal from corner 0 to corner 2, grown and
/// cut to its outline as [`surface_parts`] cuts the parts. `None` when no piece holds it.
fn map(&self, p: Point, from_page: bool) -> Option<Point> {
let inside = |t: &[Point; 3], q: Point| {
let side = |a: Point, b: Point| (b - a).cross(q - a);
let s = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])];
s.iter().all(|v| *v >= -1e-9) || s.iter().all(|v| *v <= 1e-9)
};
let mut best: Option<(Point, f64)> = None;
for piece in &self.pieces {
let (from, to) = if from_page { (&piece.page, &piece.uv) } else { (&piece.uv, &piece.page) };
@@ -1150,7 +1196,7 @@ impl SideFrame {
let pick = |of: &[Point]| Some([*of.get(corners[0])?, *of.get(corners[1])?, *of.get(corners[2])?]);
let (Some(a), Some(b)) = (pick(from), pick(to)) else { continue };
let window = if piece.outline.is_some() { grown(a, 3.0) } else { a };
if !inside(&window, p) {
if !in_triangle(&window, p) {
continue;
}
// A four-cornered piece's two triangles meet along its diagonal: each holds its side.
@@ -1176,9 +1222,136 @@ impl SideFrame {
}
}
/// The pieces of Inflate's front and puffed back that show their outside to the viewer, as the
/// graphics are drawn on them ([`surface_parts`]): each piece's face, its corners in the art's plane
/// (offsets from the center of the object's bounds) and on the page, its depth (larger is nearer)
/// and its plane, for its depth at a point of the page. The other facets the viewer sees (the
/// sides, and pieces that show the surface's inside) are kept as `covers`, for where they hide
/// a piece.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MembraneFrame {
pieces: Vec<MembranePiece>,
covers: Vec<Cover>,
}
/// A facet that can hide a piece of Inflate's front or back: its contours on the page (nonzero
/// winding), its depth, its plane and its place among the solid's facets.
#[derive(Clone, Debug, PartialEq)]
struct Cover {
contours: Vec<Vec<Point>>,
depth: f64,
plane: Option<DepthPlane>,
index: usize,
}
impl Cover {
/// Does the facet hold page point `p`?
fn holds(&self, p: Point) -> bool {
let mut winding = 0i32;
for c in &self.contours {
for (a, b) in c.iter().zip(c.iter().cycle().skip(1)).take(c.len()) {
let side = (*b - *a).cross(p - *a);
if a.y <= p.y && b.y > p.y && side > 0.0 {
winding += 1;
} else if a.y > p.y && b.y <= p.y && side < 0.0 {
winding -= 1;
}
}
}
winding != 0
}
}
#[derive(Clone, Debug, PartialEq)]
struct MembranePiece {
face: PlanarFace,
uv: [Point; 3],
page: [Point; 3],
depth: f64,
plane: Option<DepthPlane>,
/// The piece's place among the solid's facets: of two facets drawn last, the later one is drawn
/// over the other.
index: usize,
}
impl MembranePiece {
/// The piece's depth at page point `p`: its plane's depth there, or its own depth when it has
/// no plane or the plane gives none.
fn depth_at(&self, p: Point) -> f64 {
self.plane.and_then(|plane| plane.depth_at(p)).unwrap_or(self.depth)
}
}
impl MembraneFrame {
/// The pieces of `facets` that carry where they lie in the art's plane and show the outside of
/// Inflate's front or back, and the other facets not turned away from the viewer as covers.
pub(super) fn of<'a>(facets: impl IntoIterator<Item = &'a Facet>) -> Self {
let (mut pieces, mut covers) = (Vec::new(), Vec::new());
for (index, f) in facets.into_iter().enumerate() {
let piece = f.membrane.zip(f.surface.as_ref().filter(|c| c.outward)).and_then(|(face, cell)| {
let uv = <[Point; 3]>::try_from(cell.uv.as_slice()).ok()?;
let page = <[Point; 3]>::try_from(cell.page.as_slice()).ok()?;
Some(MembranePiece { face, uv, page, depth: f.depth, plane: f.plane, index })
});
match piece {
Some(piece) => pieces.push(piece),
None if !f.away => covers.push(Cover { contours: f.contours.clone(), depth: f.depth, plane: f.plane, index }),
None => {}
}
}
Self { pieces, covers }
}
/// Point `p` of `face` in the art's plane mapped onto the page, or with `from_page` a page point
/// mapped into the art's plane, through the piece of that face that holds it and is nearest at
/// that point of the page. `None` when no piece the viewer sees holds it, or when another nearer
/// piece, of either face, or a nearer cover hides that point of the page.
fn map(&self, face: PlanarFace, p: Point, from_page: bool) -> Option<Point> {
let inside = in_triangle;
let mut best: Option<(Point, f64, &MembranePiece)> = None;
for piece in self.pieces.iter().filter(|piece| piece.face == face) {
let (from, to) = if from_page { (&piece.page, &piece.uv) } else { (&piece.uv, &piece.page) };
if !inside(from, p) {
continue;
}
let Some(q) = triangle_map(from, to).map(|m| m * p).filter(|q| q.is_finite()) else { continue };
let depth = piece.depth_at(if from_page { p } else { q });
// A piece drawn last is drawn over every other one, and the later of two drawn last is
// drawn over the other, whatever their planes' depths.
let over = |(_, nearest, other): (Point, f64, &MembranePiece)| match (piece.depth == f64::MAX, other.depth == f64::MAX) {
(true, true) => piece.index > other.index,
(true, false) => true,
(false, true) => false,
(false, false) => depth > nearest,
};
if best.is_none_or(over) {
best = Some((q, depth, piece));
}
}
let (q, depth, shown) = best?;
let at = if from_page { p } else { q };
// A facet drawn last (depth `f64::MAX`) is drawn over every other one, and over another
// drawn last before it. Otherwise, where the front, the back and the sides meet, they give
// the same depth there, and only a facet clearly nearer covers.
let hides = |raw: f64, there: f64, index: usize| match (raw == f64::MAX, shown.depth == f64::MAX) {
(true, true) => index > shown.index,
(true, false) => true,
(false, true) => false,
(false, false) => there > depth + 1e-6 * depth.abs().max(1.0),
};
let covered = self
.pieces
.iter()
.filter(|piece| !std::ptr::eq(*piece, shown))
.any(|piece| inside(&piece.page, at) && hides(piece.depth, piece.depth_at(at), piece.index))
|| self.covers.iter().any(|c| c.holds(at) && hides(c.depth, c.plane.and_then(|plane| plane.depth_at(at)).unwrap_or(c.depth), c.index));
(!covered).then_some(q)
}
}
impl GraphicFrame {
pub(super) fn new(bounds: Rect, front: Option<FaceMap>, back: Option<FaceMap>) -> Self {
Self { bounds, front, back, side: None }
Self { bounds, front, back, side: None, membrane: None }
}
/// The frame with the visible part of the side `side`, for its graphics' handles.
@@ -1186,6 +1359,12 @@ impl GraphicFrame {
Self { side: Some(side), ..self }
}
/// The frame of an Inflate object built about `bounds`, whose graphics are drawn on the pieces
/// of `membrane`.
pub(super) fn inflated(bounds: Rect, membrane: MembraneFrame) -> Self {
Self { bounds, front: None, back: None, side: None, membrane: Some(membrane) }
}
pub fn map(&self, face: PlanarFace) -> Option<&FaceMap> {
match face {
PlanarFace::Front => self.front.as_ref(),
@@ -1208,27 +1387,34 @@ impl GraphicFrame {
/// Where graphic `g`'s center lands on the page, and whether its face is turned toward the
/// viewer. `None` when the object has no such face or the point has no page point. A graphic on
/// the side lands where its center is on the part of the side the viewer sees, and is `None`
/// elsewhere.
/// elsewhere. On Inflate the center lands on the puffed face above it, and is `None` where the
/// viewer does not see that face.
pub fn handle(&self, g: &MappedGraphic) -> Option<(Point, bool)> {
if g.face == PlanarFace::Side {
return Some((self.side.as_ref()?.map(Point::new(g.x, g.y), false)?, true));
}
if let Some(membrane) = &self.membrane {
let uv = if g.face == PlanarFace::Back { Point::new(-g.x, g.y) } else { Point::new(g.x, g.y) };
return Some((membrane.map(g.face, uv, false)?, true));
}
let map = self.map(g.face)?;
Some((map.to_page(self.art_point(g.face, (g.x, g.y)))?, map.visible))
}
/// The offset of a graphic on `face` whose center lands on page point `page`. On the side, only
/// a point on the part of the side the viewer sees has one.
/// a point on the part of the side the viewer sees has one, and on Inflate only a point on the
/// part of the puffed face the viewer sees.
pub fn offset_at(&self, face: PlanarFace, page: Point) -> Option<(f64, f64)> {
let art = match face {
PlanarFace::Side => self.side.as_ref()?.map(page, true)?,
_ => self.map(face)?.to_art(page)?,
};
let c = self.bounds.center();
let (x, y) = match face {
PlanarFace::Front => (art.x - c.x, art.y - c.y),
PlanarFace::Back => (c.x - art.x, art.y - c.y),
PlanarFace::Side => (art.x, art.y),
let (x, y) = if face == PlanarFace::Side {
let art = self.side.as_ref()?.map(page, true)?;
(art.x, art.y)
} else if let Some(membrane) = &self.membrane {
let uv = membrane.map(face, page, true)?;
if face == PlanarFace::Back { (-uv.x, uv.y) } else { (uv.x, uv.y) }
} else {
let art = self.map(face)?.to_art(page)?;
let c = self.bounds.center();
if face == PlanarFace::Back { (c.x - art.x, art.y - c.y) } else { (art.x - c.x, art.y - c.y) }
};
(x.abs() <= MAX_OFFSET && y.abs() <= MAX_OFFSET).then_some((x, y))
}
+52
View File
@@ -587,6 +587,30 @@ fn drawn_face_bounds(f: &Node) -> Rect {
}
}
/// Under a colored light, an Inflate in a solid color with a graphic on its front lies over an
/// underlay of its faces, the faces that carry parts of the graphic included.
#[test]
fn a_colored_inflate_with_a_graphic_lies_over_an_underlay_of_its_faces() {
let mut d = Document::new(1000.0, 1000.0);
let mark = Node::path(
NodeId(0),
vectorcraft_geom::shapes::rectangle(Rect::new(500.0, 500.0, 510.0, 510.0)),
Appearance::basic(Paint::solid(BLUE), Paint::None, 0.0),
);
d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Mark".into(), art: Arc::new(mark) });
let square = vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0));
let mut n = Node::path(NodeId(7), square, Appearance::basic(Paint::solid(RED), Paint::None, 0.0));
let p = json!({"rotationX": -20, "rotationY": -30, "rotationZ": 0, "lights": [{"color": "#ff8080"}], "graphics": [{"symbol": "Mark", "scale": 300.0}]});
n.appearance.effects.push(fx(INFLATE, p));
let art = solid_art_in(Some(&d), &n).unwrap();
let order = art.children().unwrap()[0].children().unwrap();
let faces: Vec<Arc<Node>> = order.iter().flat_map(unsealed).collect();
assert!(faces.len() > order.len(), "the faces lie over an underlay");
let carrying = faces.iter().filter(|f| matches!(f.kind, NodeKind::Group { clip: false, .. })).count();
assert!(carrying > 0, "faces carry parts of the graphic");
assert!(order.iter().all(|run| !Arc::ptr_eq(&unsealed(run)[0], run)), "every face is in a sealed run");
}
/// Under a light that is not white, a solid-color fill and a solid-color stroke, plain, dashed or
/// with a width profile, draw their faces in one order, the faces of both solids in the order of
/// their depths where they overlap, in Inflate and in Extrude & Bevel, with and without perspective
@@ -775,6 +799,7 @@ fn a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet() {
away: false,
end: None,
surface: None,
membrane: None,
plane: Some(DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
cell: None,
};
@@ -1206,6 +1231,33 @@ fn a_groups_solids_together_past_the_limit_draw_the_source() {
assert_eq!(three_d_wireframe_in(None, &past), Err(vectorcraft_three_d::TOO_COMPLEX_SOLID.to_string()));
}
/// An Inflate group whose second member's fill is past the limits draws its source art, and its
/// frame places no graphic handle on the first member's puff.
#[test]
fn an_inflate_frame_places_no_handle_when_a_fill_is_past_the_limits() {
let mut b = BezPath::new();
b.move_to((0.0, 0.0));
b.line_to((40_000.0, 0.0));
b.line_to((40_000.0, 40_000.0));
b.line_to((0.0, 40_000.0));
b.close_path();
let square = Node::path(NodeId(1), PathData::from_bezpath(&b), Appearance::basic(Paint::solid(RED), Paint::None, 0.0));
let view = json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0});
let group = |members: Vec<Node>| {
let mut g = Node::group(NodeId(9999), members.into_iter().map(Arc::new).collect());
g.appearance.effects.push(fx(INFLATE, view.clone()));
g
};
let center = MappedGraphic::from_value(&json!({"symbol": "Mark"})).unwrap();
// The square alone builds, and the graphic's handle sits on its puff.
let alone = group(vec![square.clone()]);
assert!(graphic_frame(None, &alone, None).unwrap().handle(&center).is_some());
// 70,000 corners: more points than a fill's solid takes.
let past = group(vec![square, polygon_node(2, 70_000)]);
assert!(solid_art(&past).is_none(), "the source art draws");
assert!(graphic_frame(None, &past, None).unwrap().handle(&center).is_none());
}
/// A fill and strokes whose solids each fit, but not all of them together, draw the source art,
/// and the strokes after the one past the limit are not left out to make room.
#[test]
+207 -1
View File
@@ -505,6 +505,31 @@ fn the_symbol_check_counts_what_the_view_draws() {
assert!(validate_three_d_in(Some(&dense_document(true)), &n, EXTRUDE, &flat).is_ok());
}
#[test]
fn a_wireframe_is_not_refused_for_graphics_it_does_not_draw() {
let check = |d: &Document, id: &str, mut p: Value, wire: bool| {
if wire {
p["render"] = json!({"mode": "wireframe"});
}
validate_three_d_in(Some(d), &object(id, p.clone()), id, &p)
};
// The straight 30,000-sided polygon at 1000% fits the symbol limit, but cut into pieces on
// Inflate's puffed front it is too complex.
let straight = dense_document(false);
let big = json!({"perspectiveAngle": 0.0, "graphics": [{"symbol": "Dense", "scale": 1000.0}]});
assert!(validate_symbols(&straight, &big).is_ok());
let e = check(&straight, INFLATE, big.clone(), false).unwrap_err();
assert!(e.contains("too complex"), "{e}");
// Two copies of the curved one under a perspective are past the symbol limit on Extrude & Bevel.
let curved = dense_document(true);
let two = json!({"perspectiveAngle": 60.0, "graphics": [{"symbol": "Dense"}, {"symbol": "Dense", "face": "back"}]});
let e = check(&curved, EXTRUDE, two.clone(), false).unwrap_err();
assert!(e.contains("too complex"), "{e}");
// A wireframe draws the faces' edges and no graphics, so neither is checked.
assert_eq!(check(&straight, INFLATE, big, true), Ok(()));
assert_eq!(check(&curved, EXTRUDE, two, true), Ok(()));
}
#[test]
fn a_plane_and_a_hollow_solid() {
let d = document();
@@ -548,7 +573,9 @@ fn graphics_are_checked() {
}
assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err());
assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "side"}])).is_err());
assert!(check(INFLATE, json!([{"symbol": "Mark"}])).is_err());
// Inflate takes graphics on its front and its puffed back, and none on a side.
assert!(check(INFLATE, json!([{"symbol": "Mark"}, {"symbol": "Mark", "face": "back"}])).is_ok());
assert!(check(INFLATE, json!([{"symbol": "Mark", "face": "side"}])).is_err());
// Revolve takes graphics on its side, named the front; Revolve (Classic) takes none.
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_ok());
assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "back"}]})).is_err());
@@ -579,6 +606,10 @@ fn a_change_to_a_plane_drops_the_back_caps_graphics() {
// Revolve drops the side's graphics too; Extrude & Bevel keeps every face's.
assert_eq!(three_d_params_as(EXTRUDE, &p, crate::REVOLVE)["graphics"], json!([{"symbol": "Mark", "face": "front"}]));
assert_eq!(three_d_params_as(EXTRUDE, &p, EXTRUDE)["graphics"], p["graphics"]);
// Inflate keeps the front's and the back's graphics and drops the side's.
let inflated = three_d_params_as(EXTRUDE, &p, INFLATE);
assert_eq!(inflated["graphics"], json!([{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}]));
assert!(validate_three_d_params(INFLATE, &inflated).is_ok());
// Back to Extrude & Bevel, the front's graphic stays.
assert_eq!(three_d_params_as(ROTATE, &plane, EXTRUDE)["graphics"], plane["graphics"]);
}
@@ -981,3 +1012,178 @@ fn only_an_opaque_part_on_revolve_takes_a_seam_stroke() {
// A pattern's tile may hold transparent art, which the overlap would show.
assert!(!takes_seam(&piece(Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }, 1.0, BlendMode::Normal)));
}
/// The paths in `art` filled in a shade of red: the parts of the "Mark" graphic.
fn red_parts(art: &Node) -> Vec<PathData> {
let mut out = vec![];
art.walk(&mut |n| {
let Some(path) = n.path_data() else { return };
let red = n.appearance.items.iter().any(|i| match i {
AppearanceItem::Fill(f) => f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.3 && c.to_rgb()[1] < 0.1 && c.to_rgb()[2] < 0.1),
AppearanceItem::Stroke(_) => false,
});
if red {
out.push(path.clone());
}
});
out
}
fn reach(parts: &[PathData]) -> Rect {
parts.iter().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap()
}
#[test]
fn an_inflate_graphic_lies_on_its_puffed_front_where_the_art_is() {
let d = document();
let n = object(INFLATE, json!({"graphics": [{"symbol": "Mark", "x": 20.0, "y": -10.0, "scale": 200.0}]}));
let art = solid_art_in(Some(&d), &n).unwrap();
// Straight on, the puff rises toward the viewer and the graphic is carried straight out onto it:
// a 20 × 20 square centered 20 right of and 10 above (50, 50).
let parts = red_parts(&art);
assert!(!parts.is_empty());
assert!(close(reach(&parts), Rect::new(60.0, 30.0, 80.0, 50.0)), "{:?}", reach(&parts));
// Turned, the graphic moves and foreshortens with the puff under it.
let n = object(INFLATE, json!({"rotationY": 40.0, "graphics": [{"symbol": "Mark", "scale": 200.0}]}));
let turned = reach(&red_parts(&solid_art_in(Some(&d), &n).unwrap()));
assert!(turned.width() < 20.0 - 0.5 && (turned.height() - 20.0).abs() < 2.0, "{turned:?}");
// Without the document nothing is drawn.
assert!(red_parts(&solid_art_in(None, &n).unwrap()).is_empty());
}
#[test]
fn an_inflate_back_takes_its_graphic_with_both_sides_and_twist_carries_it() {
let d = document();
let back = |extra: Value| {
let mut p = json!({"rotationY": 180.0, "graphics": [{"symbol": "Mark", "face": "back", "x": 20.0, "scale": 200.0}]});
p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());
red_parts(&solid_art_in(Some(&d), &object(INFLATE, p)).unwrap())
};
// Without Both sides the back is flat and open, with no puffed face to carry the graphic.
assert!(back(json!({})).is_empty());
// Seen from behind, the back reads left to right: 20 to the right as seen from behind is 20 to
// the left of the art's center, which turned half a turn lies 20 right on the page.
let plain = back(json!({"bothSides": true}));
assert!(!plain.is_empty());
let r = reach(&plain);
assert!((r.center().x - 70.0).abs() < 0.5 && (r.center().y - 50.0).abs() < 0.5 && (r.width() - 20.0).abs() < 0.5, "{r:?}");
// Twist turns the back, and the graphic turns with it.
let twisted = reach(&back(json!({"bothSides": true, "twist": 45.0})));
assert!(twisted.width() > r.width() + 3.0, "{twisted:?} {r:?}");
}
#[test]
fn an_inflate_frame_puts_the_handle_on_the_puff_and_reads_it_back() {
let d = document();
let n = object(INFLATE, json!({"bothSides": true}));
let frame = graphic_frame(Some(&d), &n, None).unwrap();
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "x": 20.0, "y": -10.0})).unwrap();
let (page, shown) = frame.handle(&g).unwrap();
assert!(shown && (page.x - 70.0).abs() < 1e-6 && (page.y - 40.0).abs() < 1e-6, "{page:?}");
let (x, y) = frame.offset_at(PlanarFace::Front, page).unwrap();
assert!((x - 20.0).abs() < 1e-6 && (y + 10.0).abs() < 1e-6, "{x} {y}");
// From the front the back is out of sight: it has no handle and no offset.
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "back"})).unwrap();
assert!(frame.handle(&g).is_none());
assert!(frame.offset_at(PlanarFace::Back, Point::new(50.0, 50.0)).is_none());
// Turned half a turn, the back's handle reads back its offset, as seen from behind.
let n = object(INFLATE, json!({"bothSides": true, "rotationY": 180.0}));
let frame = graphic_frame(Some(&d), &n, None).unwrap();
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "back", "x": 15.0, "y": 5.0})).unwrap();
let (page, _) = frame.handle(&g).unwrap();
let (x, y) = frame.offset_at(PlanarFace::Back, page).unwrap();
assert!((x - 15.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6, "{x} {y}");
}
/// Where two pieces of an Inflate face overlap on the page, a point maps through the piece nearer
/// at that point, though the other is nearer at its center.
#[test]
fn overlapping_inflate_pieces_map_a_point_through_the_one_nearer_there() {
let page = [Point::new(0.0, 0.0), Point::new(20.0, 0.0), Point::new(10.0, 20.0)];
let piece = |shift: f64, depth: f64, normal: [f64; 3], offset: f64| MembranePiece {
face: PlanarFace::Front,
uv: page.map(|p| p + Vec2::new(shift, 0.0)),
page,
depth,
plane: Some(DepthPlane { normal, offset, center: Point::ORIGIN, eye: None }),
index: 0,
};
// The tilted piece is nearer at its center (depth 10) but at depth 0 where x is 10; the flat
// one lies at depth 5 everywhere.
let tilted = piece(0.0, 10.0, [1.0, 0.0, 1.0], 10.0);
let flat = piece(100.0, 5.0, [0.0, 0.0, 1.0], 5.0);
let frame = GraphicFrame::inflated(Rect::new(0.0, 0.0, 20.0, 20.0), MembraneFrame { pieces: vec![tilted, flat], covers: vec![] });
let (x, y) = frame.offset_at(PlanarFace::Front, Point::new(10.0, 5.0)).unwrap();
assert!((x - 110.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6, "{x} {y}");
// Near the tilted piece's left corner it is the nearer one.
let (x, _) = frame.offset_at(PlanarFace::Front, Point::new(2.0, 0.5)).unwrap();
assert!((x - 2.0).abs() < 1e-6, "{x}");
// A graphic's center has a handle only where its own piece is the nearer one, and the handle
// maps back to the same offset.
let mark = |x: f64, y: f64| MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "front", "x": x, "y": y})).unwrap();
assert!(frame.handle(&mark(10.0, 5.0)).is_none());
for (x, y) in [(2.0, 0.5), (110.0, 5.0)] {
let (at, _) = frame.handle(&mark(x, y)).unwrap();
let (bx, by) = frame.offset_at(PlanarFace::Front, at).unwrap();
assert!((bx - x).abs() < 1e-6 && (by - y).abs() < 1e-6, "{x} {y}: {bx} {by}");
}
// Of two overlapping pieces drawn last, the later one is drawn over the other, though the
// earlier one's plane is nearer.
let last = |shift: f64, offset: f64, index: usize| MembranePiece { index, ..piece(shift, f64::MAX, [0.0, 0.0, 1.0], offset) };
let pieces = vec![last(0.0, 10.0, 0), last(100.0, 0.0, 1)];
let frame = GraphicFrame::inflated(Rect::new(0.0, 0.0, 20.0, 20.0), MembraneFrame { pieces, covers: vec![] });
let (x, _) = frame.offset_at(PlanarFace::Front, Point::new(10.0, 5.0)).unwrap();
assert!((x - 110.0).abs() < 1e-6, "{x}");
assert!(frame.handle(&mark(10.0, 5.0)).is_none());
assert!(frame.handle(&mark(110.0, 5.0)).is_some());
}
/// A graphic on Inflate's back has no handle where a nearer piece of the front covers its center
/// on the page, and the back has no offset there; where the back is nearer, it has both.
#[test]
fn an_inflate_back_graphic_covered_by_a_nearer_front_piece_has_no_handle() {
let page = [Point::new(0.0, 0.0), Point::new(20.0, 0.0), Point::new(10.0, 20.0)];
let piece = |face: PlanarFace, depth: f64| MembranePiece { face, uv: page, page, depth, plane: None, index: 0 };
let frame = |front: f64, back: f64| {
let pieces = vec![piece(PlanarFace::Front, front), piece(PlanarFace::Back, back)];
GraphicFrame::inflated(Rect::new(0.0, 0.0, 20.0, 20.0), MembraneFrame { pieces, covers: vec![] })
};
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "back", "x": -10.0, "y": 5.0})).unwrap();
let covered = frame(10.0, 5.0);
assert!(covered.handle(&g).is_none());
assert!(covered.offset_at(PlanarFace::Back, Point::new(10.0, 5.0)).is_none());
assert!(covered.offset_at(PlanarFace::Front, Point::new(10.0, 5.0)).is_some());
let seen = frame(5.0, 10.0);
let (at, _) = seen.handle(&g).unwrap();
assert!((at.x - 10.0).abs() < 1e-6 && (at.y - 5.0).abs() < 1e-6, "{at:?}");
assert!(seen.offset_at(PlanarFace::Back, Point::new(10.0, 5.0)).is_some());
}
/// A nearer side facet that covers a graphic's center on Inflate's front hides its handle; one
/// behind the front, or beside the center, leaves it. A facet drawn last (a back cap) hides it
/// whatever its plane's depth, unless the front piece is drawn last too, after it.
#[test]
fn an_inflate_graphic_covered_by_a_nearer_side_has_no_handle() {
let page = [Point::new(0.0, 0.0), Point::new(20.0, 0.0), Point::new(10.0, 20.0)];
let front = |depth: f64, index: usize| MembranePiece { face: PlanarFace::Front, uv: page, page, depth, plane: None, index };
let side = |x0: f64, depth: f64, index: usize| Cover {
contours: vec![vec![Point::new(x0, 0.0), Point::new(x0 + 4.0, 0.0), Point::new(x0 + 4.0, 20.0), Point::new(x0, 20.0)]],
depth,
// A plane behind the front, as a back cap's is.
plane: Some(DepthPlane { normal: [0.0, 0.0, 1.0], offset: 1.0, center: Point::ORIGIN, eye: None }),
index,
};
let frame = |piece: MembranePiece, cover: Cover| {
GraphicFrame::inflated(Rect::new(0.0, 0.0, 20.0, 20.0), MembraneFrame { pieces: vec![piece], covers: vec![cover] })
};
let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "front", "x": 10.0, "y": 5.0})).unwrap();
let mut nearer = side(8.0, 10.0, 1);
nearer.plane = None;
assert!(frame(front(5.0, 0), nearer.clone()).handle(&g).is_none());
assert!(frame(front(5.0, 0), nearer).offset_at(PlanarFace::Front, Point::new(10.0, 5.0)).is_none());
assert!(frame(front(5.0, 0), side(8.0, 10.0, 1)).handle(&g).is_some());
assert!(frame(front(5.0, 0), side(14.0, 10.0, 1)).handle(&g).is_some());
assert!(frame(front(5.0, 0), side(8.0, f64::MAX, 1)).handle(&g).is_none());
assert!(frame(front(f64::MAX, 0), side(8.0, f64::MAX, 1)).handle(&g).is_none());
assert!(frame(front(f64::MAX, 2), side(8.0, f64::MAX, 1)).handle(&g).is_some());
}
@@ -185,6 +185,7 @@ fn a_piece_cut_from_a_face_draws_its_own_part() {
away: false,
end: None,
surface: Some(vectorcraft_three_d::SurfaceCell { page: square, uv, outward: true }),
membrane: None,
plane: Some(vectorcraft_three_d::DepthPlane { normal, offset, center: Point::ZERO, eye: None }),
cell: None,
}
@@ -207,6 +207,7 @@ fn art_on_a_facet_with_a_curved_edge_is_clipped_to_that_edge() {
end: None,
plane: None,
surface: None,
membrane: None,
cell: None,
};
let cell = MapCell { surface: 0, page: quad.clone(), uv: quad.clone() };
@@ -251,6 +252,7 @@ fn art_on_a_facet_whose_curved_edge_bows_out_covers_the_whole_facet() {
end: None,
plane: None,
surface: None,
membrane: None,
cell: None,
};
let cell = MapCell { surface: 0, page: quad.clone(), uv: quad };
@@ -290,6 +292,7 @@ fn the_bounds_tests_of_contours_away_from_a_cell_count_as_cuts() {
end: None,
plane: None,
surface: None,
membrane: None,
cell: None,
};
let cell = MapCell { surface: 0, page: quad.clone(), uv: quad };
+1 -1
View File
@@ -379,7 +379,7 @@ fn a_stroke_left_out_of_the_art_casts_no_shadow() {
let p = crate::merged_params(id, &json!({"shadow": true}));
let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap());
let mut built: Vec<Option<SolidFaces>> =
built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true, None).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect();
built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true, false, None).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect();
let stroke = parts.iter().position(|(item, ..)| matches!(item, AppearanceItem::Stroke(_))).unwrap();
assert!(built.len() == 2 && built.iter().all(Option::is_some), "{id}");
let (both, _, cast) = cast_built(id, &p, &shapes, built.clone()).unwrap().unwrap();
+4
View File
@@ -911,6 +911,10 @@ pub use gradpresets::{GradientPreset, GradientPresetEntry};
/// A saved Image Trace preset ([`crate::Prefs::trace_presets`]), and a change to the saved presets.
pub use buildcmds::{TracePreset, TracePresetChange};
/// The `format`, extensions and largest size of the tracing presets files
/// `imageTrace.presets.export` writes and `imageTrace.presets.import` reads.
pub use buildcmds::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES};
/// An Image Trace made off the UI thread, and what it traced (#3098).
pub use buildcmds::{TraceRun, Traced, image_trace_target};
+175 -22
View File
@@ -29,6 +29,7 @@ use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::appearance::SharedStack;
use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, FillLayer, Node, NodeKind, ParaStyle, StrokeLayer};
use vectorcraft_geom::Rect;
use vectorcraft_tools::builder::{edges, faces, is_live_paint};
use super::edit::{outermost, roots_of, selected_roots};
use super::opacitymask::percent;
@@ -48,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add New Fill",
["Window", "Appearance"],
Some("Cmd+/"),
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
"{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). In the contents of a Live Paint group the fill goes on its faces only, and its hidden source paths, like every contents edit, are left as they are. With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
has_doc,
|s, p| add_item(s, p, true)
),
@@ -57,7 +58,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add New Stroke",
["Window", "Appearance"],
Some("Cmd+Alt+/"),
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
"{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. In the contents of a Live Paint group the stroke goes on its edges only, and its hidden source paths are left as they are. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)",
has_doc,
|s, p| add_item(s, p, false)
),
@@ -129,7 +130,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Eyedropper",
[],
None,
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}",
"{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; a whole Live Paint group (selected, in ids, or `source` with `reverse`) takes the fill attributes on its faces and the stroke attributes on its edges (a whole-appearance pick: every fill row on each face and every stroke row on each edge, which keep their rows of the other kind and their effects; `append` adds the source's rows but not its object effects to them), and its hidden source paths keep their paint; a whole Live Paint group picked up (`source`, or selected first with `reverse`) gives its first face's fills with its first edge's strokes above them and the group's own opacity, blend mode and effects; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}",
has_doc,
copy_from
),
@@ -280,7 +281,8 @@ impl ItemTarget {
/// [`ItemTarget::targets`] of a fill (`fill`) or a stroke edit: on the topmost fill or stroke, a
/// Live Paint group stands for its faces in a fill edit and for its edges in a stroke edit
/// ([`super::paint::live_paint_parts_skipped`]).
/// ([`super::paint::live_paint_parts_skipped`]); an item edit with `target: "contents"` leaves out
/// the parts of the other kind the same way ([`contents_skipped`]).
pub(crate) fn targets_for(self, s: &Session, p: &Value, fill: bool) -> Result<Vec<NodeId>> {
Ok(self.targets_and_skipped(s, p, fill)?.0)
}
@@ -290,13 +292,16 @@ impl ItemTarget {
/// to new art.
pub(crate) fn targets_and_skipped(self, s: &Session, p: &Value, fill: bool) -> Result<(Vec<NodeId>, bool)> {
let mut ids = self.targets(s, p)?;
let mut skipped_any = false;
if self == ItemTarget::Top {
let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill);
let before = ids.len();
ids.retain(|id| !skipped.contains(id));
skipped_any = ids.len() != before;
}
// An item edit of the contents of a Live Paint group goes to its parts of the edited kind too.
let skipped = if self == ItemTarget::Top {
super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill)
} else {
contents_skipped(s, p, fill)?
};
let before = ids.len();
ids.retain(|id| !skipped.contains(id));
// A contents edit already leaves hidden source paths out of `ids`, so `skipped` is checked on its own too.
let skipped_any = ids.len() != before || !skipped.is_empty();
Ok((ids, skipped_any))
}
@@ -491,15 +496,37 @@ pub(crate) fn subject_roots(s: &Session) -> Result<Vec<NodeId>> {
/// Objects whose own appearance stack a command edits: `ids`/`id` (layers too; an id inside
/// another given one is dropped), else the [`subject_roots`]; with `target: "contents"` the painted
/// objects inside the groups and layers among them ([`leaf_targets`]).
/// objects inside the groups and layers among them ([`leaf_targets`]), without the hidden source paths
/// of Live Paint groups.
pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
let roots = if p.get("ids").is_none() && p.get("id").is_none() {
subject_roots(s)?
let roots = appearance_roots(s, p)?;
if !targets_contents(p)? {
return Ok(roots);
}
let (_, _, hidden) = super::paint::live_paint_split(&s.doc()?.doc, &roots);
let mut ids = leaf_targets(s, &roots)?;
ids.retain(|id| !hidden.contains(id));
Ok(ids)
}
/// The objects [`appearance_targets`] starts from: `ids`/`id`, else the [`subject_roots`].
fn appearance_roots(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
if p.get("ids").is_none() && p.get("id").is_none() {
subject_roots(s)
} else {
let d = &s.doc()?.doc;
outermost(d, targets(s, p)?.into_iter().filter(|id| d.node(*id).is_some()).collect())
};
if targets_contents(p)? { leaf_targets(s, &roots) } else { Ok(roots) }
Ok(outermost(d, targets(s, p)?.into_iter().filter(|id| d.node(*id).is_some()).collect()))
}
}
/// The parts of the Live Paint groups whose contents `p` targets (`target: "contents"`) that a fill
/// (`fill`) or stroke edit of those contents leaves as they are: their edges or faces. Empty without
/// `target: "contents"`.
pub(crate) fn contents_skipped(s: &Session, p: &Value, fill: bool) -> Result<HashSet<NodeId>> {
if !targets_contents(p)? {
return Ok(HashSet::new());
}
Ok(super::paint::live_paint_parts_skipped(&s.doc()?.doc, &appearance_roots(s, p)?, fill))
}
/// The refusal of an appearance edit whose targets are all the art of graph designs drawn in graph series.
@@ -897,7 +924,26 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result<Value> {
}
fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
let ids = require_targets(s, p, if fill { "appearance.addFill" } else { "appearance.addStroke" })?;
let cmd = if fill { "appearance.addFill" } else { "appearance.addStroke" };
let mut ids = row_targets(s, p, cmd)?;
if ids.is_empty() {
// A selected Live Paint group left with only its hidden source paths has nothing to edit: it is
// still a selection, so the edit changes nothing.
let roots = appearance_roots(s, p)?;
if targets_contents(p)? && !roots.is_empty() && !super::paint::live_paint_split(&s.doc()?.doc, &roots).2.is_empty() {
return ok();
}
return Err(bad(cmd, "select objects or give ids"));
}
// In the contents of a Live Paint group, a new fill goes on its faces and a new stroke on its edges;
// with no part of that kind, nothing changes.
let skipped = contents_skipped(s, p, fill)?;
if !skipped.is_empty() {
ids.retain(|id| !skipped.contains(id));
if ids.is_empty() {
return ok();
}
}
let defaults = s.paint.clone();
// The panel's active Fill row, when the new fill goes on the selection: the new fill takes that
// row's paint, right above it in each target that has it (others take their top fill's paint).
@@ -1779,7 +1825,23 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
// Reversed, the first selected object's attributes go onto the clicked object; with nothing
// selected, what the Eyedropper picked up last does (#4382).
let (source, mut targets) = if reverse {
let source = match leaf_targets(s, &selected)?.into_iter().next() {
// The selected objects are tried in order: a Live Paint group with a look is picked up as a whole
// ([`live_paint_look`]), any other object gives its first painted leaf, and a group with nothing to pick
// up (its hidden source paths are not what it draws) passes to the next object.
let d = &s.doc()?.doc;
let mut first = None;
for root in &selected {
if d.node(*root).and_then(live_paint_look).is_some() {
first = Some(*root);
break;
}
let (_, _, hidden) = super::paint::live_paint_split(d, &[*root]);
if let Some(leaf) = leaf_targets(s, &[*root])?.into_iter().find(|id| !hidden.contains(id)) {
first = Some(leaf);
break;
}
}
let source = match first {
Some(first) => Some(first),
None if s.eyedropper_sample.is_some() => None,
None => return Err(bad(C, "select the object to copy from")),
@@ -1788,10 +1850,45 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
} else {
(Some(clicked), leaf_targets(s, &selected)?)
};
targets.retain(|id| Some(*id) != source);
// A whole Live Paint group takes the fill attributes on its faces and the stroke attributes on its edges, and its
// hidden source paths keep their paint.
let roots = if reverse { vec![clicked] } else { selected };
let (faces, edges, hidden) = super::paint::live_paint_split(&s.doc()?.doc, &roots);
// Some(true) for a face, Some(false) for an edge.
let part_of = |id: &NodeId| {
if faces.contains(id) {
Some(true)
} else if edges.contains(id) {
Some(false)
} else {
None
}
};
let attrs_for = |id: &NodeId| {
let mut a = attrs;
match part_of(id) {
Some(true) => a.appearance.stroke = StrokeAttrs::NONE,
Some(false) => a.appearance.fill = FillAttrs::NONE,
None => {}
}
a
};
// A pick of the whole appearance gives a face every fill row and an edge every stroke row.
let whole = attrs.appearance.fill == FillAttrs::ALL && attrs.appearance.stroke == StrokeAttrs::ALL;
// A source that is a Live Paint group is not one of its own targets: neither are its faces and edges.
let mut inside_source = HashSet::new();
if let Some(n) = source.and_then(|id| s.doc().ok()?.doc.node(id)).filter(|n| is_live_paint(n)) {
n.walk(&mut |c| {
inside_source.insert(c.id);
});
}
targets.retain(|id| Some(*id) != source && !hidden.contains(id) && !inside_source.contains(id));
let mut targets = without_design_art(&s.doc()?.doc, targets, C)?;
let node = match source {
Some(id) => Arc::new(s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.clone()),
Some(id) => {
let n = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?;
Arc::new(live_paint_look(n).unwrap_or_else(|| n.clone()))
}
None => s.eyedropper_sample.clone().ok_or_else(|| bad(C, "select the object to copy from"))?,
};
let picked = Picked::of(&node);
@@ -1919,7 +2016,17 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
super::overprint::edit_counted(s, "Eyedropper", |d| {
for id in &targets {
if let Some(n) = d.node_mut(*id) {
picked.apply(n, &attrs, append, characters.get(id));
match part_of(id) {
Some(fill) if whole && !append => picked.apply_rows(n, &attrs, fill),
// `append` does not add the picked object effects to a face or edge, as a whole pick keeps the part's
// own; a row's effects go with the row.
Some(_) => {
let effects = n.appearance.effects.len();
picked.apply(n, &attrs_for(id), append, characters.get(id));
n.appearance.effects.truncate(effects);
}
None => picked.apply(n, &attrs_for(id), append, characters.get(id)),
}
}
}
check_text_bounds(d)?;
@@ -2170,6 +2277,52 @@ impl Picked {
}
super::object::snap_if_aligned(n);
}
/// A whole pick ([`Self::apply`] with every fill and stroke attribute) onto a Live Paint face
/// (`fill`) or edge: the face's fills (the edge's strokes) become the picked ones, and its rows of
/// the other kind and its effects stay as they are.
fn apply_rows(&self, n: &mut Node, a: &EyedropperAttrs, fill: bool) {
if a.appearance.transparency {
n.opacity = self.opacity;
n.blend = self.blend;
}
let taken: Vec<AppearanceItem> = self.placed(n.geometric_bounds()).items.into_iter().filter(|it| it.is_fill() == fill).collect();
// The picked rows go where the part's first row of that kind was, the other rows keep their order; without
// such a row, fills go to the bottom and strokes to the top.
let items = &n.appearance.items;
let at = items.iter().position(|it| it.is_fill() == fill);
let at = at.map_or(if fill { 0 } else { items.iter().filter(|it| it.is_fill() != fill).count() }, |i| {
items.iter().take(i).filter(|it| it.is_fill() != fill).count()
});
let mut kept: Vec<AppearanceItem> = items.iter().filter(|it| it.is_fill() != fill).cloned().collect();
kept.splice(at..at, taken);
n.appearance.items = kept;
super::object::snap_if_aligned(n);
}
}
/// What the Eyedropper picks up from a whole Live Paint group `n`: its first face (else its first edge) with that
/// face's fills and the first edge's strokes above them, their gradients placed as on those parts, and the group's
/// own opacity, blend mode and effects. None for any other object, and for a group with no face and no edge.
fn live_paint_look(n: &Node) -> Option<Node> {
if !is_live_paint(n) {
return None;
}
let (face, edge) = (faces(n).first().copied(), edges(n).first().copied());
let mut look = (**face.or(edge)?).clone();
let rows = |part: Option<&Arc<Node>>, fill: bool| -> Vec<AppearanceItem> {
part.map(|p| p.appearance.items.iter().filter(|it| it.is_fill() == fill).cloned().collect()).unwrap_or_default()
};
// The edge's stroke gradients, placed relative to the look's bounds as they are to the edge's.
let mut strokes = Appearance { items: rows(edge, false), ..Default::default() };
if let (Some(from), Some(to)) = (edge.and_then(|e| e.geometric_bounds()), look.geometric_bounds()) {
strokes.rebase_gradients(from, to);
}
look.appearance.items = rows(face, true).into_iter().chain(strokes.items).collect();
look.appearance.effects = n.appearance.effects.clone();
look.opacity = n.opacity;
look.blend = n.blend;
Some(look)
}
/// The focal (topmost) fill and stroke attributes `a` of `from` onto `to`. Taking a colour creates
+48
View File
@@ -178,6 +178,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[
BuiltinBrushLibrary { id: "paint", name: "Paint", make: paint },
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
BuiltinBrushLibrary { id: "decorative", name: "Decorative", make: decorative },
BuiltinBrushLibrary { id: "ornamental", name: "Ornamental", make: ornamental },
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
BuiltinBrushLibrary { id: "stipple", name: "Stipple", make: stipple },
BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails },
@@ -733,6 +734,53 @@ fn decorative() -> BrushLibrary {
)
}
/// Ornamental: one-pass flourishes and arrow accents that stretch with the path rather than
/// repeating a pattern tile. Every shape is original filled vector art.
fn ornamental() -> BrushLibrary {
let scrollwork = group(vec![
black(band(100.0, 1.2, 64, |x| 2.6 * (x / 100.0 * std::f64::consts::TAU).sin())),
ring(Point::new(7.0, 0.0), 4.0, 2.0),
ring(Point::new(93.0, 0.0), 4.0, 2.0),
black(polygon(&[(28.0, 1.0), (34.0, -5.0), (40.0, -3.0), (33.0, 2.0)])),
black(polygon(&[(60.0, 3.0), (66.0, 5.0), (72.0, -1.0), (67.0, -2.0)])),
]);
let arrow = group(vec![
// The shaft runs into the head's notch at x = 85 so the two overlap.
black(shapes::rectangle(Rect::new(4.0, -0.7, 86.0, 0.7))),
black(polygon(&[(80.0, -6.5), (100.0, 0.0), (80.0, 6.5), (85.0, 0.0)])),
ring(Point::new(7.0, 0.0), 4.0, 1.7),
black(polygon(&[(25.0, -0.4), (31.0, -4.4), (37.0, -2.0), (31.0, 0.8)])),
black(polygon(&[(43.0, 0.4), (49.0, 4.4), (55.0, 2.0), (49.0, -0.8)])),
]);
let mut petals = vec![black(band(100.0, 1.0, 48, |x| 1.8 * (x / 100.0 * std::f64::consts::PI).sin()))];
for x in [19.0, 43.0, 67.0, 87.0] {
let y = 1.8 * (x / 100.0 * std::f64::consts::PI).sin();
petals.push(black(shapes::ellipse(Rect::new(x - 4.5, y - 7.5, x + 4.5, y - 0.3))));
petals.push(black(shapes::ellipse(Rect::new(x - 3.5, y + 0.3, x + 3.5, y + 5.5))));
}
let petal_sweep = group(petals);
let twin_curl = group(vec![
black(band(100.0, 0.9, 64, |x| -3.8 + 1.6 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())),
black(band(100.0, 0.9, 64, |x| 3.8 - 1.6 * (x / 100.0 * 2.0 * std::f64::consts::TAU).sin())),
ring(Point::new(8.0, -3.8), 3.0, 1.5),
ring(Point::new(92.0, 3.8), 3.0, 1.5),
]);
let ornament = |name: &str, art: Node| Brush {
name: name.into(),
kind: BrushKind::Art(ArtBrush { art, width: 300.0, colorization: Colorization::Tints, ..Default::default() }),
};
built(
"Ornamental",
Document::new(100.0, 100.0),
vec![
ornament("Scrollwork", scrollwork),
ornament("Filigree Arrow", arrow),
ornament("Petal Sweep", petal_sweep),
ornament("Twin Curl", twin_curl),
],
)
}
fn scatter(name: &str, art: Node, s: Scatter) -> Brush {
Brush { name: name.into(), kind: BrushKind::Scatter(Scatter { art, ..s }) }
}
+43 -6
View File
@@ -40,10 +40,14 @@ mod trace;
pub use live_paint::live_paint_gaps;
pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, isolated_live_paints, merge_drawn_in_isolation};
use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge};
use shape_builder::{sb_merge, sb_regions};
use shape_builder::{sb_copy_region, sb_merge, sb_regions};
pub(crate) use trace::TracePresetChanges;
pub use trace::{TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target};
use trace::{trace_expand, trace_make, trace_presets_delete, trace_presets_save, trace_release, trace_set_view};
pub use trace::{
TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES, TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target,
};
use trace::{
trace_expand, trace_make, trace_presets_delete, trace_presets_export, trace_presets_import, trace_presets_save, trace_release, trace_set_view,
};
/// Name of an Image Trace group.
pub const TRACE_NAME: &str = "Image Trace";
@@ -68,6 +72,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection_or_ids,
sb_regions
),
cmd!(
"shapeBuilder.copyRegion",
"Fill Area",
[],
None,
"{point: [x,y], ids?|id?: [id…] (the objects or layers whose paths bound areas; default: every layer, nothing needs to be selected), gap?: pt (0–72; 0: Gap Detection off; out of range is an error), openFilledAsClosed?: true (as shapeBuilder.merge), fill?, stroke?: \"#rrggbb\" | {color|swatch|gradient|none} (default: the current fill and stroke, with the current stroke weight)} add a new closed path of the area under point that the visible, unlocked paths enclose (the region of shapeBuilder.regions holding it: areas a shape already fills and areas open paths bound count too), directly above the front-most object along the area (its outline touches the area's outline, or it covers the area; when a group, Live Paint group, Shaper group or clipping group holds that path, above the outermost group in its layer, never inside it), and select it; in isolation mode only the paths of the isolated layer or group bound areas (with ids, only the paths of the listed objects that are in it), and the new path goes inside it, directly above the object in it that holds that path; no area is found while the isolated object is not a layer or group (a path or compound path), is a Live Paint group, compound shape, Shaper group, graph, Image Trace result, dimension, flare or Objects on Path group, is a layer or group with a live effect or a clipping mask, or lies inside one of these or inside an envelope; the paths around the area are not changed; a point in no enclosed area is an error and changes nothing (no undo step); when the paths together have more than 65,536 segments, only an area the paths near the point enclose is found → {id, above (the object the new path went above)}",
has_doc,
sb_copy_region
),
cmd!(
"livePaint.make",
"Make",
@@ -208,6 +221,24 @@ pub fn specs() -> Vec<CommandSpec> {
always,
trace_presets_delete
),
cmd!(
query "imageTrace.presets.import",
"Import Image Trace Presets",
[],
None,
"{path? | data?: file text | dataBase64?, replace?: false (true: a preset whose name a saved preset has replaces that preset's settings; false: it is skipped)} add the presets of a .vctracepresets file (as imageTrace.presets.export writes, at most 4 MiB and 1,000 presets) to the saved ones → {imported: [names added], replaced: [names], skipped: [names]}; every preset is checked first, and a file with a built-in preset's or Custom's name, two presets of one name, a preset without a name or with settings imageTrace.presets.save refuses, or a newer version changes nothing",
always,
trace_presets_import
),
cmd!(
query "imageTrace.presets.export",
"Export Image Trace Presets",
[],
None,
"{names?: [saved preset names] (default: every saved preset; built-in ones are refused), path?} write the saved tracing presets as a .vctracepresets file (JSON: format, version 1, presets: [{name, params}]) → {path, count}; without path → {data: the file's text, count}; more than 1,000 presets, or a file over 4 MiB, is refused, as imageTrace.presets.import would refuse it",
always,
trace_presets_export
),
]
}
@@ -263,12 +294,18 @@ fn stroke_only(paint: Paint, width: f64) -> Appearance {
// ---------- Shape Builder ----------
fn fill_param(s: &Session, p: &Value, cmd: &str) -> Result<Option<Paint>> {
match p.get("fill") {
paint_param(s, p, "fill", cmd)
}
/// The paint `p` gives for `key` (`"#rrggbb"` or `{color|swatch|gradient|none}`), as `fill` is read.
fn paint_param(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<Option<Paint>> {
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v @ Value::Object(o)) if o.contains_key("color") || o.contains_key("swatch") || o.contains_key("gradient") || o.contains_key("none") => {
paint_from(s, v)
// A paint key whose value is not a paint, such as `{"swatch": 123}`, gives no paint.
paint_from(s, v)?.map(Some).ok_or_else(|| bad(cmd, format!("bad {key} {v}")))
}
Some(v) => color_value(v).map(|c| Some(Paint::solid(super::paint::new_color(s, p, c)))).ok_or_else(|| bad(cmd, format!("bad fill {v}"))),
Some(v) => color_value(v).map(|c| Some(Paint::solid(super::paint::new_color(s, p, c)))).ok_or_else(|| bad(cmd, format!("bad {key} {v}"))),
}
}
@@ -1,7 +1,7 @@
use super::{
Arc, Beside, BuilderMap, EngineError, FillRule, Node, NodeId, PathData, Point, Rect, Result, Session, Touched, Value, b, bad, check_numbers,
f64_or, fill_param, finite, gap_param, ids_json, json, marquee_param, po, points_param, remnant, replace_leaves, replace_with_pieces, root_ids,
shape_node, switch_or,
f64_or, fill_param, finite, gap_param, ids_json, json, marquee_param, named_ids, number_or, outermost, paint_param, po, point_param,
points_param, remnant, replace_leaves, replace_with_pieces, root_ids, shape_node, switch_or,
};
pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
@@ -183,6 +183,49 @@ pub(super) fn sb_merge(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
pub(super) fn sb_copy_region(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "shapeBuilder.copyRegion";
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
let open_filled_as_closed = switch_or(p, "openFilledAsClosed", true, C)?;
let gap = number_or(p, "gap", 0.0, C)?;
if !(0.0..=po::SHAPE_BUILDER_MAX_GAP).contains(&gap) {
return Err(bad(C, format!("gap must be 0 to {} pt, not {gap}", po::SHAPE_BUILDER_MAX_GAP)));
}
let fill = paint_param(s, p, "fill", C)?.unwrap_or_else(|| s.paint.fill.clone());
let stroke = paint_param(s, p, "stroke", C)?.unwrap_or_else(|| s.paint.stroke.clone());
let look = s.new_art_look(fill, stroke, s.paint.stroke_width);
let area = {
let st = s.doc()?;
let d = &st.doc;
let named = match named_ids(p)? {
Some(ids) => {
if let Some(bad_id) = ids.iter().find(|i| d.node(**i).is_none()) {
return Err(EngineError::NoNode(*bad_id));
}
// An object listed with a layer or group that holds it counts once.
Some(outermost(d, ids))
}
None => None,
};
// In isolation mode only the isolated layer or group's paths bound areas, and the new path
// goes inside it.
b::fill_area_roots(d, st.isolation, named.as_deref())
.and_then(|(roots, scope)| b::AreaFinder::new(d, &roots, scope, gap, open_filled_as_closed).find(pt))
};
let Some(area) = area else { return Err(EngineError::Other("Fill Area: no enclosed area under the pointer".into())) };
let id = s.edit("Fill Area", |d, sel| {
let mut n = shape_node(d, area.path.clone(), None);
look.apply(d, &mut n);
let id = n.id;
let mut above = Beside::above(d, &[area.above]);
above.put(d, area.above, vec![n])?;
above.finish(d)?;
sel.set([id]);
Ok(id)
})?;
Ok(json!({ "id": id.0, "above": area.above.0 }))
}
pub(super) fn sb_regions(s: &mut Session, p: &Value) -> Result<Value> {
let open_filled_as_closed = switch_or(p, "openFilledAsClosed", true, "shapeBuilder.regions")?;
check_numbers(p, &["gap"], "shapeBuilder.regions")?;
+159
View File
@@ -168,6 +168,9 @@ pub(super) fn trace_presets_save(s: &mut Session, p: &Value) -> Result<Value> {
if old.is_none() && new_name.is_some() {
return Err(bad(C, format!("no saved preset named `{name}` to rename")));
}
if old.is_none() && s.prefs.trace_presets.len() >= TRACE_PRESET_MAX_COUNT {
return Err(bad(C, format!("{TRACE_PRESET_MAX_COUNT} tracing presets are saved, the most there can be: delete one first")));
}
// A saved preset changes from its own settings unless `preset` says where to start.
let mut q = p.clone();
if let (Some(old), Some(o), None) = (&old, q.as_object_mut(), preset) {
@@ -203,6 +206,162 @@ pub(super) fn trace_presets_delete(s: &mut Session, p: &Value) -> Result<Value>
Ok(json!({ "deleted": deleted }))
}
/// The `format` of a tracing presets file, also its extension.
pub const TRACE_PRESET_FORMAT: &str = "vctracepresets";
/// The extensions of tracing presets files (opening one imports it).
pub const TRACE_PRESET_EXTS: &[&str] = &[TRACE_PRESET_FORMAT];
/// The `version` `imageTrace.presets.export` writes; `imageTrace.presets.import` reads files of
/// this version and earlier ones.
const TRACE_PRESET_VERSION: u64 = 1;
/// The largest tracing presets file `imageTrace.presets.import` reads.
pub const TRACE_PRESET_MAX_BYTES: usize = 4 << 20;
/// The most presets one tracing presets file may hold, and the most tracing presets that can be
/// saved (so every saved preset fits in one exported file).
const TRACE_PRESET_MAX_COUNT: usize = 1000;
pub(super) fn trace_presets_export(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "imageTrace.presets.export";
let presets: Vec<&TracePreset> = match p.get("names").filter(|v| !v.is_null()) {
Some(Value::Array(names)) => {
let mut out: Vec<&TracePreset> = vec![];
for n in names {
let n = n.as_str().ok_or_else(|| bad(C, "`names` must hold preset names"))?;
if tr::preset(n).is_some() {
return Err(bad(C, format!("`{n}` is a built-in preset: only saved presets are exported")));
}
let q = s.trace_preset(n).ok_or_else(|| bad(C, format!("no saved preset named `{n}`")))?;
if !out.iter().any(|o| o.name == q.name) {
out.push(q);
}
}
out
}
Some(_) => return Err(bad(C, "`names` must be an array of preset names")),
None => s.prefs.trace_presets.iter().collect(),
};
if presets.is_empty() {
return Err(bad(C, "no saved tracing presets to export"));
}
// A file is written only when `imageTrace.presets.import` can read it back.
let count = presets.len();
if count > TRACE_PRESET_MAX_COUNT {
return Err(bad(C, format!("{count} presets are more than one file holds ({TRACE_PRESET_MAX_COUNT}): export fewer with `names`")));
}
let rows: Vec<Value> = presets.iter().map(|q| json!({"name": q.name, "params": q.params})).collect();
let file = json!({"format": TRACE_PRESET_FORMAT, "version": TRACE_PRESET_VERSION, "presets": rows});
let text = serde_json::to_string_pretty(&file).map_err(|e| EngineError::Other(e.to_string()))?;
if text.len() > TRACE_PRESET_MAX_BYTES {
return Err(bad(C, format!("the file would be larger than {} MiB: export fewer with `names`", TRACE_PRESET_MAX_BYTES >> 20)));
}
match opt_str(C, p, "path")? {
Some(path) => {
crate::cmd::fileio::write_file(path, text.as_bytes())?;
Ok(json!({"path": path, "count": count}))
}
None => Ok(json!({"data": text, "count": count})),
}
}
/// The bytes of the tracing presets file `p` names (`path`, `data` or `dataBase64`), at most
/// [`TRACE_PRESET_MAX_BYTES`] of them.
fn trace_preset_file(c: &str, p: &Value) -> Result<Vec<u8>> {
let too_big = || bad(c, format!("the file is larger than {} MiB", TRACE_PRESET_MAX_BYTES >> 20));
let bytes = match (opt_str(c, p, "path")?, opt_str(c, p, "data")?, opt_str(c, p, "dataBase64")?) {
(Some(path), ..) => crate::cmd::fileio::read_file_head(path, TRACE_PRESET_MAX_BYTES + 1)?,
(None, Some(text), _) => {
if text.len() > TRACE_PRESET_MAX_BYTES {
return Err(too_big());
}
text.as_bytes().to_vec()
}
(None, None, Some(b64)) => {
if vectorcraft_format::base64_decoded_len(b64) > TRACE_PRESET_MAX_BYTES as u64 {
return Err(too_big());
}
vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?
}
_ => return Err(bad(c, "give `path`, `data` or `dataBase64`")),
};
if bytes.len() > TRACE_PRESET_MAX_BYTES {
return Err(too_big());
}
Ok(bytes)
}
pub(super) fn trace_presets_import(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "imageTrace.presets.import";
let replace = switch_or(p, "replace", false, C)?;
let bytes = trace_preset_file(C, p)?;
let not_file = |why: String| bad(C, format!("not a tracing presets file: {why}"));
let file: Value = serde_json::from_slice(&bytes).map_err(|e| not_file(e.to_string()))?;
if file["format"] != TRACE_PRESET_FORMAT {
return Err(not_file(format!("format `{}`", file["format"].as_str().unwrap_or_default())));
}
match file["version"].as_u64() {
Some(v) if (1..=TRACE_PRESET_VERSION).contains(&v) => {}
Some(v) => return Err(bad(C, format!("the file's version {v} is newer than this version of VectorCraft reads ({TRACE_PRESET_VERSION})"))),
None => return Err(not_file("no `version`".into())),
}
let rows = file["presets"].as_array().ok_or_else(|| not_file("no `presets` list".into()))?;
if rows.len() > TRACE_PRESET_MAX_COUNT {
return Err(bad(C, format!("the file holds {} presets, more than {TRACE_PRESET_MAX_COUNT}", rows.len())));
}
// Every preset is checked before any is saved, so a file with a fault changes nothing.
let mut presets: Vec<TracePreset> = Vec::with_capacity(rows.len());
for (i, row) in rows.iter().enumerate() {
let name = row["name"].as_str().map(str::trim).unwrap_or_default();
if name.is_empty() {
return Err(bad(C, format!("preset {} has no name", i + 1)));
}
if tr::preset(name).is_some() || name.eq_ignore_ascii_case("Custom") {
return Err(bad(C, format!("`{name}` is the name of a built-in preset: rename it in the file")));
}
if presets.iter().any(|q| q.name.eq_ignore_ascii_case(name)) {
return Err(bad(C, format!("the file holds two presets named `{name}`")));
}
let params = match row.get("params").filter(|v| v.is_object()) {
Some(params) => trace_params(s, C, &json!({"preset": "Default", "params": params})).map_err(|e| match e {
EngineError::BadParams { msg, .. } => bad(C, format!("`{name}`: {msg}")),
e => e,
})?,
None => return Err(bad(C, format!("`{name}` has no `params`"))),
};
presets.push(TracePreset { name: name.to_string(), params });
}
let added = presets.iter().filter(|q| s.trace_preset_index(&q.name).is_none()).count();
if s.prefs.trace_presets.len() + added > TRACE_PRESET_MAX_COUNT {
return Err(bad(
C,
format!("the file's {added} new presets would make more than {TRACE_PRESET_MAX_COUNT} saved tracing presets: delete some first"),
));
}
let (mut imported, mut replaced, mut skipped) = (vec![], vec![], vec![]);
for preset in presets {
let name = preset.name.clone();
match s.trace_preset_index(&name) {
Some(i) if replace => {
let Some(slot) = s.prefs.trace_presets.get_mut(i) else { continue };
// The saved preset keeps its name as it was saved.
let kept = slot.name.clone();
*slot = TracePreset { name: kept.clone(), params: preset.params };
s.trace_preset_changes.note(TracePresetChange { revision: 0, name: kept.clone(), renamed_from: None, deleted: false });
replaced.push(kept);
}
Some(_) => skipped.push(name),
None => {
s.prefs.trace_presets.push(preset);
s.trace_preset_changes.note(TracePresetChange { revision: 0, name: name.clone(), renamed_from: None, deleted: false });
imported.push(name);
}
}
}
Ok(json!({"imported": imported, "replaced": replaced, "skipped": skipped}))
}
/// The string `key` of `p` (`None` when it is missing or null); any other type is an error of
/// command `c`.
fn opt_str<'a>(c: &str, p: &'a Value, key: &str) -> Result<Option<&'a str>> {
+7 -2
View File
@@ -19,7 +19,7 @@ use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_brush::Brush;
use vectorcraft_color::Swatch;
use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef};
use vectorcraft_doc::{Document, GraphDesign, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef};
use vectorcraft_geom::{PathData, Rect};
pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture};
@@ -94,6 +94,9 @@ pub struct Clipboard {
pub para_styles: Vec<TextStyleDef>,
/// Brushes the objects' strokes use.
pub brushes: Vec<Brush>,
/// Graph designs the copied graphs draw their columns, bars or markers with. Pasting adds the
/// ones the document lacks; a design the document has under the same name stays as it is.
pub graph_designs: Vec<GraphDesign>,
/// The artboard the objects were copied from (none when they lie on no artboard; the first of
/// [`Self::artboards`] when there are any): Paste on All Artboards keeps their offset to it.
pub source_artboard: Option<Rect>,
@@ -395,7 +398,7 @@ impl Clipboard {
if self.source_doc == Some(st.uid) && !self.colors_converted {
return vec![];
}
self.conflicts(&st.doc, &self.used())
self.conflicts(&st.doc, &self.used(&st.doc))
}
/// A standalone document holding the objects and their resources (SVG export).
@@ -408,6 +411,7 @@ impl Clipboard {
d.graphic_styles.extend(self.graphic_styles.iter().cloned());
d.char_styles = self.char_styles.clone().into();
d.para_styles = self.para_styles.clone().into();
d.graph_designs = self.graph_designs.clone();
if !self.brushes.is_empty() {
let mut lib = vectorcraft_brush::library(&d);
// Each brush's place in the library by name: finding it by scanning the growing list
@@ -469,6 +473,7 @@ impl Clipboard {
char_styles: d.char_styles.to_vec(),
para_styles: d.para_styles.to_vec(),
brushes: vectorcraft_brush::library(&d),
graph_designs: d.graph_designs.clone(),
images: self.images.clone(),
symbol_options: self.symbol_options.clone(),
source_artboard: self.source_artboard,
+212 -13
View File
@@ -1,8 +1,9 @@
//! The document resources copied objects use, and adding them to the document they're pasted into.
//!
//! Objects refer to resources by name (image blobs, symbols, patterns, swatches, character and
//! paragraph styles, brushes) and to graphic styles by id. Copy follows those references, also
//! through the symbols, patterns, styles and brush art it finds, and keeps what they lead to.
//! paragraph styles, brushes, graph designs) and to graphic styles by id. Copy follows those
//! references, also through the symbols, patterns, styles, brush art and graph design art it finds,
//! and keeps what they lead to.
//!
//! Pasting matches each resource by name: an identical one in the document is used, a missing one
//! is added, and a different one of the same name is added under a free name, which the pasted
@@ -22,8 +23,8 @@ use vectorcraft_brush::Brush;
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_doc::text::{KINSOKU_NAME_MAX, KINSOKU_SETS_MAX};
use vectorcraft_doc::{
Appearance, AppearanceItem, Document, Effect, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol, SymbolExportType,
SymbolNineSlice, SymbolRegistration, TextStyleDef,
Appearance, AppearanceItem, Document, Effect, GraphDesign, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol,
SymbolExportType, SymbolNineSlice, SymbolRegistration, TextStyleDef,
};
use super::super::brushsym::{set_natural_size, stored_natural_size};
@@ -44,6 +45,7 @@ enum Res {
ParaStyle,
Brush,
GraphicStyle,
GraphDesign,
}
impl Res {
@@ -57,6 +59,7 @@ impl Res {
Res::ParaStyle => "paraStyle",
Res::Brush => "brush",
Res::GraphicStyle => "graphicStyle",
Res::GraphDesign => "graphDesign",
}
}
}
@@ -139,6 +142,10 @@ fn node_refs(n: &Node, f: Visit) {
for s in [&l.values_para, &l.categories_para, &l.legend_para].into_iter().flatten().filter_map(|pa| pa.style_name.as_ref()) {
f(Ref::Name(Res::ParaStyle, s));
}
// The designs its series draw their markers, columns or bars with.
for d in g.series_markers.iter().flatten().chain(g.series_columns.iter().flatten().map(|c| &c.design)) {
f(Ref::Name(Res::GraphDesign, d));
}
}
match &m.kind {
NodeKind::Text(t) => {
@@ -217,6 +224,7 @@ struct Defs<'a> {
char_styles: &'a [TextStyleDef],
para_styles: &'a [TextStyleDef],
brushes: Brushes<'a>,
graph_designs: &'a [GraphDesign],
/// Where each name is defined, built the first time a kind is followed.
index: DefIndex,
}
@@ -236,6 +244,7 @@ struct DefIndex {
char_styles: OnceCell<NameIndex>,
para_styles: OnceCell<NameIndex>,
brushes: OnceCell<NameIndex>,
graph_designs: OnceCell<NameIndex>,
}
/// The items of `list` named `name`, in order, `index` holding their positions (built from
@@ -279,6 +288,7 @@ impl<'a> Defs<'a> {
char_styles: &d.char_styles,
para_styles: &d.para_styles,
brushes: Brushes::Lazy(d, brushes),
graph_designs: &d.graph_designs,
index: DefIndex::default(),
}
}
@@ -376,6 +386,7 @@ impl Used {
Res::ParaStyle => todo.extend(named(&ix.para_styles, defs.para_styles, |s| &s.name, name).map(|s| Source::Attrs(&s.attrs))),
// A scatter or art brush's art, a pattern brush's tiles.
Res::Brush => todo.extend(named(&ix.brushes, defs.brushes.get(), |b| &b.name, name).flat_map(|b| b.art().into_iter().map(Source::Node))),
Res::GraphDesign => todo.extend(named(&ix.graph_designs, defs.graph_designs, |g| &g.name, name).map(|g| Source::Node(&g.art))),
_ => {}
}
}
@@ -406,7 +417,7 @@ pub struct ArtResources {
/// The resources `art` uses in `doc`, through the definitions they lead to as Copy follows them
/// ([`Used`]): images, symbols, patterns (tile type, overlap and spacing too), swatches (linked
/// colours, tints, gradient swatches; colour groups' included), character and paragraph styles,
/// brushes and graphic styles, and the document's Spot Colors option. Art and image bytes count
/// brushes, graph designs and graphic styles, and the document's Spot Colors option. Art and image bytes count
/// by identity, the other definitions by their saved form: working the key out walks `art` and
/// the definitions it leads to, and never reads an image's bytes.
pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator<Item = &'a Node>) -> ArtResources {
@@ -451,6 +462,7 @@ pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator<Item = &'a No
Res::CharStyle => doc.char_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)),
Res::ParaStyle => doc.para_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)),
Res::Brush => defs.brushes.get().iter().filter(|b| b.name == *name).for_each(|b| saved(&mut h, b)),
Res::GraphDesign => doc.graph_designs.iter().filter(|g| g.name == *name).for_each(|g| node(&mut h, &mut kept.0, &g.art)),
// Swatches below (tints count too); graphic styles go by id.
Res::Swatch | Res::GraphicStyle => {}
}
@@ -824,6 +836,22 @@ fn same_art(r: &Relink, ours: &[Arc<Node>], theirs: &[Arc<Node>]) -> bool {
ours.len() == theirs.len() && ours.iter().zip(theirs).all(|(a, b)| relinked(&unlinked, a) == relinked(r, b))
}
/// `n` with the ids of its objects, those of opacity-mask art included, all 0: art drawn again
/// compares equal to art drawn the same way, whatever ids each drawing gave it.
fn without_ids(n: &Node) -> Node {
let mut n = n.clone();
n.id = vectorcraft_doc::NodeId(0);
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) {
mask.art = Arc::new(without_ids(&mask.art));
}
if let Some(children) = n.children_mut() {
for c in children.iter_mut() {
*c = Arc::new(without_ids(c));
}
}
n
}
/// Is `ours` (a document brush) brush `theirs` (a pasted one) once the art of that is relinked by
/// `r`? Graphic style links don't count, as in [`same_art`].
fn same_brush(r: &Relink, ours: &Brush, theirs: &Brush) -> bool {
@@ -1106,6 +1134,17 @@ pub(crate) struct Imported {
/// `{kind, from, to}` for every resource the pasted objects now know under another name: added
/// renamed, or a copy added renamed by an earlier paste.
pub renamed: Vec<Value>,
/// The graph designs the pasted graphs draw with that the document has under the same name
/// and that would draw them otherwise than the art they were pasted with: the document keeps
/// its own, and the pasted graphs are drawn again with it.
pub kept_designs: BTreeSet<String>,
/// The names of the symbols added to the document, whose art may hold graphs that draw with
/// [`Self::kept_designs`].
pub added_symbols: BTreeSet<String>,
/// The names of the graph designs added to the document.
pub added_designs: BTreeSet<String>,
/// The global and spot colors that took the document's color (merged).
merged_swatches: BTreeSet<String>,
}
impl Imported {
@@ -1161,15 +1200,24 @@ impl Clipboard {
char_styles: pick(Res::CharStyle, &src.char_styles),
para_styles: pick(Res::ParaStyle, &src.para_styles),
brushes,
graph_designs: src.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name)).cloned().collect(),
set_densities: src.set_densities_of(&nodes),
nodes,
..Default::default()
}
}
/// The resources the objects use now (Paste without Formatting leaves text styles behind).
pub(super) fn used(&self) -> Used {
let defs = Defs {
/// The resources the objects use now (Paste without Formatting leaves text styles behind),
/// pasted into `d`: the art of a graph design `d` has under the same name is not followed, as
/// `d` keeps its own design.
pub(super) fn used(&self, d: &Document) -> Used {
let designs: Vec<GraphDesign> = self.graph_designs.iter().filter(|g| !d.graph_designs.iter().any(|x| x.name == g.name)).cloned().collect();
Used::of(&self.defs(&designs), &self.nodes)
}
/// The clipboard's definitions, with graph designs `designs`.
fn defs<'a>(&'a self, designs: &'a [GraphDesign]) -> Defs<'a> {
Defs {
swatches: self.swatches.iter().collect(),
symbols: &self.symbols,
patterns: &self.patterns,
@@ -1177,9 +1225,9 @@ impl Clipboard {
char_styles: &self.char_styles,
para_styles: &self.para_styles,
brushes: Brushes::Ready(&self.brushes),
graph_designs: designs,
index: DefIndex::default(),
};
Used::of(&defs, &self.nodes)
}
}
/// The used global and spot colours whose name `d` gives another one: (pasted, document).
@@ -1200,7 +1248,8 @@ impl Clipboard {
/// paste ([`Self::colors_converted`]), its color-bearing resources are compared as another
/// document's are, while its image blobs are still the document's own under their keys.
pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result<Imported> {
self.import_used_with_images(d, &self.used(), choices, same_doc && !self.colors_converted, same_doc)
let used = self.used(d);
self.import_used_with_images(d, &used, choices, same_doc && !self.colors_converted, same_doc)
}
/// Give the objects' colors linked to a global or spot swatch whose conflict with `d`
@@ -1211,7 +1260,7 @@ impl Clipboard {
if same_doc {
return;
}
let used = self.used();
let used = self.used(d);
let colors: BTreeMap<String, Color> = self
.conflicts(d, &used)
.into_iter()
@@ -1248,6 +1297,11 @@ impl Clipboard {
) -> Result<Imported> {
let mut out = Imported::default();
out.relink.filters = self.filter_links(d, same_doc)?;
let held = |name: &str| d.graph_designs.iter().any(|x| x.name == name);
let new_designs = self.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name) && !held(&g.name)).count();
if new_designs > 0 && d.graph_designs.len().saturating_add(new_designs) > GraphDesign::MAX {
return Err(EngineError::Other(format!("a document keeps at most {} graph designs", GraphDesign::MAX)));
}
self.import_images(d, used, same_doc_images, &mut out);
self.import_swatches(d, used, choices, same_doc, &mut out);
self.import_kinsoku_sets(d, used, same_doc, &mut out);
@@ -1331,11 +1385,18 @@ impl Clipboard {
.collect(),
None => HashMap::new(),
};
// A symbol whose graphs the paste draws again with the document's designs is
// also the document's one that holds its art drawn that way (an earlier paste
// added it).
let redrawn = (!fresh && d.symbols.iter().any(|s| copy_of(&def.name, &s.name)))
.then(|| self.redrawn_art(d, &def.art, &out.relink))
.flatten();
let r = &out.relink;
let p = place(&mut d.symbols, def, same_doc, |a, b| {
!fresh
&& options.is_none_or(|o| theirs.get(&a.name) == Some(o))
&& same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))
&& (same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art))
|| redrawn.as_ref().is_some_and(|art| without_ids(&a.art) == *art))
});
if let Some(name) = p.new_name(&def.name) {
if let Some(o) = options {
@@ -1371,6 +1432,7 @@ impl Clipboard {
}
}
self.import_graphic_styles(d, used, same_doc, &mut out);
self.import_graph_designs(d, used, same_doc, &mut out)?;
for (r, name, def) in added_styles {
let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles };
if let Some(s) = theirs.iter_mut().find(|s| s.name == name) {
@@ -1381,6 +1443,7 @@ impl Clipboard {
for s in d.symbols.iter_mut().filter(|s| added_symbols.contains(&s.name)) {
out.relink.node(Arc::make_mut(&mut s.art));
}
out.added_symbols = added_symbols.into_iter().collect();
for p in d.patterns.iter_mut().filter(|p| added_patterns.contains(&p.name)) {
for a in &mut p.art {
out.relink.node(Arc::make_mut(a));
@@ -1497,6 +1560,10 @@ impl Clipboard {
for a in self.brushes.iter().flat_map(Brush::art) {
node_filters(a, &mut found);
}
// A design the document has under the same name stays its own, so its art here is not pasted.
for g in self.graph_designs.iter().filter(|g| !d.graph_designs.iter().any(|x| x.name == g.name)) {
node_filters(&g.art, &mut found);
}
for g in &self.graphic_styles {
appearance_filters(&g.appearance, &mut found);
}
@@ -1575,6 +1642,7 @@ impl Clipboard {
for w in &bases {
let p = if conflicts.contains(&w.name) && choices.of(&w.name) == SwatchChoice::Merge {
out.merged += 1;
out.merged_swatches.insert(w.name.clone());
Placed::Existing
} else {
add_swatch(d, w, same_doc)
@@ -1624,6 +1692,71 @@ impl Clipboard {
out.relink.styles.insert(g.id, d.graphic_style_id(i));
}
}
/// Symbol art `art` relinked by `relink` with its graphs drawn again with the designs `d` holds
/// under a name whose design the clipboard lacks or holds with other art, as a paste that adds
/// the symbol draws it, its ids left out ([`without_ids`]). `None` when no graph of it draws
/// with such a design.
fn redrawn_art(&self, d: &mut Document, art: &Arc<Node>, relink: &Relink) -> Option<Node> {
let theirs = |n: &str| self.graph_designs.iter().find(|g| g.name == n);
let differs: BTreeSet<String> = d
.graph_designs
.iter()
.filter(|x| theirs(&x.name).is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art))
.map(|x| x.name.clone())
.collect();
if differs.is_empty() || !crate::cmd::graph::holds_designs(art, &differs) {
return None;
}
let mut n = (**art).clone();
relink.node(&mut n);
crate::cmd::graph::redraw_detached(d, &mut n, &differs);
Some(without_ids(&n))
}
/// Graph designs: the document's design of a name stays as it is and the pasted graphs draw
/// with it ([`Imported::kept_designs`]); a design the document lacks is added under its name, its art following the
/// resources placed above, with fresh ids. Called once every other resource is placed.
fn import_graph_designs(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) -> Result<()> {
// Every name the pasted graphs draw with whose design in the document would draw them
// otherwise: another design of that name, one the clipboard holds no design for (deleted
// and made again), or, from another document, the same art when a resource came in renamed
// or a swatch took the document's color, that the design's art uses. (An SVG filter effect
// carries its definition, so a filter that draws otherwise makes the art differ.)
let defs = self.defs(&self.graph_designs);
let moved = |n: &str| {
if same_doc || (out.relink.renames.is_empty() && out.merged_swatches.is_empty()) {
return false;
}
let uses = designs_used(&defs, &[n.to_string()]);
out.relink.renames.iter().any(|(r, names)| names.keys().any(|from| uses.has(*r, from)))
|| out.merged_swatches.iter().any(|w| uses.has(Res::Swatch, w))
};
let differs = |n: &str| {
let ours = d.graph_designs.iter().find(|x| x.name == n);
let theirs = self.graph_designs.iter().find(|g| g.name == n);
ours.is_some_and(|x| theirs.is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art) || moved(n))
};
let named = used.names.get(&Res::GraphDesign).into_iter().flatten();
let kept: Vec<String> = named.filter(|n| differs(n)).cloned().collect();
out.kept_designs.extend(kept);
for g in self.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name)) {
if d.graph_designs.iter().any(|x| x.name == g.name) {
out.placed(Res::GraphDesign, &g.name, &Placed::Existing);
continue;
}
if d.graph_designs.len() >= GraphDesign::MAX {
return Err(EngineError::Other(format!("a document keeps at most {} graph designs", GraphDesign::MAX)));
}
let mut art = (*g.art).clone();
out.relink.node(&mut art);
let art = d.reid(&art);
d.graph_designs.push(GraphDesign { name: g.name.clone(), art: Arc::new(art) });
out.placed(Res::GraphDesign, &g.name, &Placed::Added);
out.added_designs.insert(g.name.clone());
}
Ok(())
}
}
/// Where a loaded text style is in the document ([`import_text_styles`]).
@@ -1663,6 +1796,72 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool,
Ok(placed)
}
/// The resources graph designs `names` of `src` use, through the definitions they lead to.
fn designs_used(defs: &Defs<'_>, names: &[String]) -> Used {
let mut used = Used::default();
let mut todo = vec![];
for n in names {
used.note(defs, Ref::Name(Res::GraphDesign, n), &mut todo);
}
used.follow(defs, todo);
used
}
/// A document holding `src`'s graph designs and the swatches, patterns, symbols, styles, brushes
/// and images their art uses, and nothing else: what a document opened as a library keeps for the
/// Graph Column and Graph Marker dialogs. `None` when `src` has no graph designs.
pub(crate) fn graph_design_library(src: &Document) -> Option<Document> {
if src.graph_designs.is_empty() {
return None;
}
let names: Vec<String> = src.graph_designs.iter().map(|g| g.name.clone()).collect();
let library = OnceCell::new();
let used = designs_used(&Defs::of(src, &library), &names);
let clip = Clipboard::with_used(src, &used, &library, vec![]);
let mut d = clip.to_document();
// A new document's default swatches and graphic styles give way to the source's of the same
// name or id, so a design draws with the source's.
let defaults = d.swatches.len().saturating_sub(clip.swatches.len());
let mut i = 0;
d.swatches.retain(|s| {
i += 1;
i > defaults || !clip.swatches.iter().any(|c| c.name == s.name)
});
// The swatch groups are all a new document's.
for g in d.swatch_groups.iter_mut() {
g.swatches.retain(|s| !clip.swatches.iter().any(|c| c.name == s.name));
}
let defaults = d.graphic_styles.len().saturating_sub(clip.graphic_styles.len());
let mut i = 0;
d.graphic_styles.retain(|g| {
i += 1;
i > defaults || !clip.graphic_styles.iter().any(|c| (c.id != 0 && c.id == g.id) || c.name == g.name)
});
// The symbols keep their Symbol Options, which the document keeps by name.
for (name, options) in &clip.symbol_options {
options.give(&mut d, name);
}
d.title = src.title.clone();
Some(d)
}
/// Add graph designs `names` of `src` to `d`, with the swatches, patterns, symbols, styles,
/// brushes and images their art uses, placed as Paste places them ([`Clipboard::import_into`]; a
/// global or spot color whose name `d` gives another color is `d`'s). A design `d` has under the
/// same name stays as it is, and the art of `src`'s design of that name is not followed. → the
/// names of the designs added ([`Imported::added_designs`]): those of `names` `d` lacked, and those
/// their art uses; with the symbols added and the designs `d` kept that their art draws with
/// ([`Imported::added_symbols`], [`Imported::kept_designs`]). An error, with `d` unchanged, when `d`
/// would hold more than [`GraphDesign::MAX`] designs.
pub(crate) fn import_graph_designs(src: &Document, d: &mut Document, names: &[String]) -> Result<Imported> {
let library = OnceCell::new();
let held = |n: &str| d.graph_designs.iter().any(|x| x.name == n);
let followed: Vec<GraphDesign> = src.graph_designs.iter().filter(|g| names.contains(&g.name) || !held(&g.name)).cloned().collect();
let used = designs_used(&Defs { graph_designs: &followed, ..Defs::of(src, &library) }, names);
let clip = Clipboard::with_used(src, &used, &library, vec![]);
clip.import_used(d, &used, &SwatchChoices::default(), false)
}
/// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups
/// share one namespace).
fn add_swatch(d: &mut Document, w: &Swatch, same_doc: bool) -> Placed {
+18 -6
View File
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Circle Through Points",
[],
None,
"{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn",
"{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count), anchors?: \"standard\"|\"points\" (default standard: four anchors at 0°, 90°, 180° and 270°; points: an anchor at each point and more between them so that no curve turns more than a quarter)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn",
has_doc,
circle_through_points
),
@@ -443,20 +443,32 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
}
/// A live ellipse whose edge passes through two or three points: `points`, or the two or three
/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One
/// undo step, named as an Ellipse tool drag is.
/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. With
/// `anchors: "points"` the circle is a plain path with an anchor at each point
/// ([`shapes::circle_with_anchors_at`]); otherwise it is a live ellipse. One undo step, named as an
/// Ellipse tool drag is.
fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "shape.circleThroughPoints";
let points = match p.get("points").filter(|v| !v.is_null()) {
Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?,
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?,
};
let key = "anchors";
let at_points = match p.get(key).map(Value::as_str) {
None | Some(Some("standard")) => false,
Some(Some("points")) => true,
Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, points"))),
};
let (center, radius) = shapes::circle_through_points(&points)
.ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?;
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
// Not pixel-aligned: the circle stays through the points.
let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?;
let mut out = if at_points {
add_art_unaligned(s, "Ellipse", path_kind(shapes::circle_with_anchors_at(center, radius, &points), None))?
} else {
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?
};
out["cx"] = json!(center.x);
out["cy"] = json!(center.y);
out["radius"] = json!(radius);
+11
View File
@@ -1653,6 +1653,17 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
for id in &new_ids {
super::object::keep_compound_aligned(d, *id, vectorcraft_doc::Scaling::default());
}
// A pasted graph whose design the document has under the same name draws with the document's,
// in the pasted objects and in the art of the symbols the paste added.
if !imported.kept_designs.is_empty() {
super::graph::redraw_with_designs(d, &new_ids, &imported.kept_designs)?;
super::graph::redraw_symbols_with_designs(d, &imported.added_symbols, &imported.kept_designs);
}
// The graphs already in the document that draw with a design the paste added are drawn
// again with it; the pasted ones already draw with it.
if !imported.added_designs.is_empty() {
super::graph::refresh_graphs(d, &imported.added_designs, &new_ids, &imported.added_symbols)?;
}
sel.set(new_ids.iter().copied());
// Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a
// paste of guides alone keeps them where they were, but onto another artboard or every
+10 -2
View File
@@ -1,5 +1,6 @@
//! Window › 3D and Materials › Materials › Graphics: art kept as a document symbol (Add as Single
//! Graphic) and mapped onto 3D objects (Extrude & Bevel's caps, a plane, Revolve's side). The
//! Graphic) and mapped onto 3D objects (Extrude & Bevel's caps, a plane, Revolve's side, Inflate's
//! puffed front and back). The
//! graphics an object shows are the `graphics` parameter of its 3D effect, which `effect.setParams`
//! also edits.
@@ -28,7 +29,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Map Graphic",
[],
None,
"{symbol: name of a document symbol, face?: front|back|side (front; Plane has only a front; the back reads left to right as seen from behind; side is Extrude & Bevel's walls and bevels; on Revolve the front is its swept side, which is the only face), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on a side from the middle of the side unrolled flat: on Extrude & Bevel x along the outline, clockwise from its top, and y from the front toward the back; on Revolve x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Extrude & Bevel's side inside the side unrolled about x = 0, short of its cut, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on a side wrapped around it, and drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap, or on the side, hollow or not), Rotate (the Plane type) or Revolve; one undo step → {ids, graphic}",
"{symbol: name of a document symbol, face?: front|back|side (front; Plane has only a front; the back reads left to right as seen from behind; side is Extrude & Bevel's walls and bevels; on Revolve the front is its swept side, which is the only face; on Inflate the back takes graphics only with Both sides and Cap on), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Inflate in the art's plane, the graphic carried straight out onto the puffed face; on a side from the middle of the side unrolled flat: on Extrude & Bevel x along the outline, clockwise from its top, and y from the front toward the back; on Revolve x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Extrude & Bevel's side inside the side unrolled about x = 0, short of its cut, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on a side wrapped around it, and on Inflate following the puff, Twist and Taper carrying the back's, each drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap, or on the side, hollow or not), Rotate (the Plane type), Revolve or Inflate; one undo step → {ids, graphic}",
has_doc,
map_graphic
),
@@ -134,6 +135,13 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
if base.face != effects::PlanarFace::Front && extrude.is_some_and(|o| o.depth <= 0.0) {
return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0)));
}
// Inflate's back takes graphics where it puffs out: with Both sides and Cap on.
if base.face == effects::PlanarFace::Back && effect.id == effects::INFLATE {
let o = effects::inflate_options(&merged);
if !(o.both_sides && o.cap) {
return Err(bad(C, format!("object {}: Inflate's back takes graphics with Both sides and Cap on", id.0)));
}
}
let mut graphic = base.clone();
if p.get("scale").is_none()
&& let Some(art) = effects::graphic_bounds(d, &graphic.symbol)
@@ -95,10 +95,10 @@ fn map_graphic_puts_a_graphic_on_the_side_of_a_revolve() {
#[test]
fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() {
let (mut s, id) = setup("threeD.inflate");
let (mut s, id) = setup("threeD.classicExtrude");
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap_err().to_string();
assert!(e.contains("Plane, Extrude and Revolve"), "{e}");
assert!(e.contains("Plane, Extrude, Revolve and Inflate"), "{e}");
let (mut s, id) = setup("threeD.rotate");
for (p, says) in [
(json!({"symbol": "Gone"}), "no symbol named"),
@@ -188,11 +188,36 @@ fn set_params_edits_graphics_and_checks_them() {
let null = json!({"ids": [id.0], "index": 0, "item": null, "params": {"graphics": null}});
assert!(s.execute("effect.setParams", &null).is_err());
assert_eq!(graphics(&s, id), moved);
// Extrude to Plane keeps the graphics; to Inflate drops them.
// Extrude to Plane keeps the graphics, and so does Inflate.
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "plane"})).unwrap();
assert_eq!(graphics(&s, id), moved);
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "threeDType": "inflate"})).unwrap();
assert_eq!(graphics(&s, id), Value::Null);
assert_eq!(graphics(&s, id), moved);
}
#[test]
fn map_graphic_puts_a_graphic_on_an_inflate_and_its_back_only_with_both_sides() {
let (mut s, id) = setup("threeD.inflate");
let plain = {
let d = &s.doc().unwrap().doc;
vectorcraft_render::effects::solid_art_in(Some(d), d.node(id).unwrap())
};
let history = undo_len(&s);
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).unwrap();
assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "front", "x": 0.0, "y": 0.0, "scale": 100.0, "rotation": 0.0}]));
assert_eq!(undo_len(&s), history + 1);
let d = &s.doc().unwrap().doc;
assert_ne!(vectorcraft_render::effects::solid_art_in(Some(d), d.node(id).unwrap()), plain, "the graphic is drawn");
// The back is flat until Both sides puffs it.
let history = undo_len(&s);
let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap_err().to_string();
assert!(e.contains("Both sides and Cap"), "{e}");
assert_eq!(undo_len(&s), history);
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"bothSides": true, "cap": false}})).unwrap();
assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).is_err());
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": {"cap": true}})).unwrap();
s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "back", "ids": [id.0]})).unwrap();
assert_eq!(graphics(&s, id)[1]["face"], "back");
}
#[test]
+1 -1
View File
@@ -804,7 +804,7 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &roots, !stroke);
leaf_targets(s, &roots)?.into_iter().filter(|id| !skipped.contains(id)).collect()
}
_ => item.targets(s, p)?,
_ => item.targets_for(s, p, !stroke)?,
};
if targets.is_empty() {
return Err(EngineError::Other("nothing selected".into()));
+1
View File
@@ -41,6 +41,7 @@ pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph
pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv};
#[cfg(test)]
use data::{fmt_value, to_csv};
pub(crate) use designs::{holds_designs, redraw_detached, redraw_symbols_with_designs, redraw_with_designs, refresh_graphs};
pub use edit::{GraphTypeSubject, graph_type_subject};
pub(crate) use edit::{edit_graph_art, graphs_holding, keep_placed};
pub use generate::calculated_axes;
+17 -4
View File
@@ -1,5 +1,5 @@
use super::data::fmt_value;
use super::designs::design_names;
use super::designs::{bring_in_for, design_names, from_library, libraries_json};
use super::edit::{regenerate, spec_of, target};
use super::generate::generate_with;
use super::markers::{design_frame, fit_affine};
@@ -437,7 +437,7 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result<Value> {
let mut spec = spec_of(s, id)?;
let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES);
let picked = picked_series(s, p, id, count, C)?;
let names = design_names(&s.doc()?.doc);
let mut names = design_names(&s.doc()?.doc);
let all: Vec<usize> = if picked.is_empty() { (0..count).collect() } else { picked.clone() };
// The column design the picked series (all of them with none picked) share; a design deleted since doesn't count,
// as those series draw plain columns.
@@ -446,14 +446,21 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result<Value> {
let shared = used.first().copied().flatten().filter(|c| used.iter().all(|x| *x == Some(*c))).cloned();
let Some(v) = p.get("design") else {
let options = shared.clone().unwrap_or_default();
return Ok(json!({
let mut out = json!({
"designs": names,
"design": shared.map(|c| c.design),
"columnType": options.column_type.id(),
"each": options.each,
"fractions": options.fractions.id(),
}));
});
if let Some(libs) = libraries_json(s) {
out["libraries"] = libs;
}
return Ok(out);
};
// A design of a loaded library comes into the document in the same undo step.
let library = from_library(s, p, C)?;
names.extend(library.as_ref().map(|(_, n)| n.clone()));
let design = match v {
Value::Null => None,
Value::String(n) if names.contains(n) => Some(n.clone()),
@@ -485,11 +492,17 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result<Value> {
}
// Drawn once on a copy of the document, to refuse designs past the budget before the edit.
let mut probe = (*s.doc()?.doc).clone();
if let Some((lib, name)) = &library {
bring_in_for(&mut probe, lib, name, id, &mut spec)?;
}
let looks = column_designs(&probe, &spec);
if generate_with(&mut probe, &spec, &looks).is_none() {
return Err(bad(C, "the design is too big to draw in every column of this graph"));
}
s.edit("Graph Column", |d, sel| {
if let Some((lib, name)) = &library {
bring_in_for(d, lib, name, id, &mut spec)?;
}
regenerate(d, id, spec)?;
if !reselect.is_empty() {
reselect_series(d, sel, id, &reselect);
+3 -3
View File
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Design…",
["Object", "Graph"],
None,
"{new?: name|true (New Design: the selected art becomes a graph design, named \"New Design\" when true; put a rectangle at the back to set the size it draws at), rename?: name, to?: new name (the graphs drawing it follow), paste?: name (Paste Design: a copy of the design's art into the document, selected, to edit and save again), delete?: name|[names] (graphs drawing them go back to their default marks), ids?|id?: object ids (default: the selection), selectUnused?: bool (Select Unused: just the list)}; no params or selectUnused → {designs: [names], unused: [the names no graph draws with]}",
"{new?: name|true (New Design: the selected art becomes a graph design, named \"New Design\" when true; put a rectangle at the back to set the size it draws at), rename?: name, to?: new name (the graphs drawing it follow), paste?: name (Paste Design: a copy of the design's art into the document, selected, to edit and save again), delete?: name|[names] (graphs drawing them go back to their default marks), ids?|id?: object ids (default: the selection), selectUnused?: bool (Select Unused: just the list), library?: the id or name of a document loaded with swatch.library.load (Other Library…) that holds graph designs, add?: name|[names] of that library's designs (copy them into the document as one undo step, with the swatches, patterns, symbols, styles, brushes and images their art uses, as pasting brings them; a design the document already has under the same name stays as it is) → {added: [names], existing: [names the document already had]}}; library alone → {designs: [the library's names]}; no params or selectUnused → {designs: [names], unused: [the names no graph draws with], libraries?: [{library, name, designs}] (the loaded libraries that hold graph designs)}",
has_doc,
design
),
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Column…",
["Object", "Graph"],
None,
"{id?, seriesIndexes?: [index], design?: name|null, columnType?: vertical|uniform|repeating|sliding, each?: value (more than 0), fractions?: chop|scale} draw the columns or bars and the legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, its backmost object as its frame and its guides left out: vertical stretches it along the value axis to each column's length at the column's width, uniform scales it both ways to that length, centered on the column, repeating stacks copies out from the zero line that each stand for `each` and cuts off the last one where the value ends (chop) or scales it down to fit (scale) (vertical when one copy would be longer than the canvas), and sliding scales the part above its horizontal guide line (in bar graphs, right of a vertical one) in proportion to the column's width and stretches the part below to fill the rest (vertical without a guide, or in a column too short for the part above); type in the design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits, the first digit giving the least number of places before the decimal point (zeros added in front; 0 = as many as the value needs) and the second digit giving the places after it (rounded half away from zero), at the type's own size where the design's copy puts it (a repeating design shows it once, where a whole copy ending at the value end puts it; type inside a group that clips, is hidden or has its own opacity, blend mode, isolation, knockout, appearance or opacity mask, or inside a blend, compound shape, envelope, repeat or intertwine, stays there and is filled in each copy, drawn with the design; type inside a symbol stays as typed), and is left out of the legend swatch (a design of such type alone gets the default swatch); the design keeps its own orientation for negative values, and columns drawn with a design cast no drop shadow; null = plain columns; options left out keep the series' shared ones, else vertical, 10 and chop. Column, stacked column, bar and stacked bar series. No design → {designs: [names], design: the selected series' design or null, columnType, each, fractions}",
"{id?, seriesIndexes?: [index], design?: name|null, library?: id or name (a document loaded with swatch.library.load: a design of it that the document lacks is copied in first, in the same undo step, as graph.design's add copies it; the document's own design of a name is the one used), columnType?: vertical|uniform|repeating|sliding, each?: value (more than 0), fractions?: chop|scale} draw the columns or bars and the legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, its backmost object as its frame and its guides left out: vertical stretches it along the value axis to each column's length at the column's width, uniform scales it both ways to that length, centered on the column, repeating stacks copies out from the zero line that each stand for `each` and cuts off the last one where the value ends (chop) or scales it down to fit (scale) (vertical when one copy would be longer than the canvas), and sliding scales the part above its horizontal guide line (in bar graphs, right of a vertical one) in proportion to the column's width and stretches the part below to fill the rest (vertical without a guide, or in a column too short for the part above); type in the design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits, the first digit giving the least number of places before the decimal point (zeros added in front; 0 = as many as the value needs) and the second digit giving the places after it (rounded half away from zero), at the type's own size where the design's copy puts it (a repeating design shows it once, where a whole copy ending at the value end puts it; type inside a group that clips, is hidden or has its own opacity, blend mode, isolation, knockout, appearance or opacity mask, or inside a blend, compound shape, envelope, repeat or intertwine, stays there and is filled in each copy, drawn with the design; type inside a symbol stays as typed), and is left out of the legend swatch (a design of such type alone gets the default swatch); the design keeps its own orientation for negative values, and columns drawn with a design cast no drop shadow; null = plain columns; options left out keep the series' shared ones, else vertical, 10 and chop. Column, stacked column, bar and stacked bar series. No design → {designs: [names], design: the selected series' design or null, columnType, each, fractions, libraries?: [{library, name, designs}]}",
has_selection,
set_column
),
@@ -57,7 +57,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Marker…",
["Object", "Graph"],
None,
"{id?, seriesIndexes?: [index], design?: name|null} draw the data points and legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, scaled so its backmost object fills the default marker's square; null = the default marker. Line, scatter and radar series. No design → {designs: [names], design: the selected series' design or null}",
"{id?, seriesIndexes?: [index], design?: name|null, library?: id or name (a document loaded with swatch.library.load: a design of it that the document lacks is copied in first, in the same undo step, as graph.design's add copies it; the document's own design of a name is the one used)} draw the data points and legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, scaled so its backmost object fills the default marker's square; null = the default marker. Line, scatter and radar series. No design → {designs: [names], design: the selected series' design or null, libraries?: [{library, name, designs}]}",
has_selection,
set_marker
),
+294 -18
View File
@@ -1,44 +1,291 @@
use super::edit::regenerate;
use super::{Arc, Document, GraphDesign, GraphSpec, Result, Session, Value, bad, json, ok, str_param};
use super::edit::{regenerate, regenerate_detached};
use std::collections::BTreeSet;
use super::{Arc, Document, GraphDesign, GraphKind, GraphSpec, Node, Result, Session, Value, bad, json, ok, str_param};
use crate::cmd::clipboard::resources::import_graph_designs;
use crate::cmd::swatchlib::{concealed_library_id, shown_library_id};
/// The document's graph design names, in order.
pub(super) fn design_names(d: &Document) -> Vec<String> {
d.graph_designs.iter().map(|x| x.name.clone()).collect()
}
/// Whether graph `g` draws a series with design `name`, as its marker or its columns.
/// The library param `library` names: a document Other Library… loaded (`swatch.library.load`)
/// that holds graph designs, by its id, the id a reply showed for it, or its name (in any case, as
/// swatch library names are matched). `None` without
/// `library`.
fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<Option<Arc<Document>>> {
let key = match p.get("library") {
None | Some(Value::Null) => return Ok(None),
Some(Value::String(k)) => k.as_str(),
Some(_) => {
let list = "graph.design";
return Err(bad(cmd, format!("`library` is a library id or name (see {list})")));
}
};
let libs = &s.graph_design_libraries;
let own = concealed_library_id(s, key);
libs.get(key)
.or_else(|| own.as_deref().and_then(|id| libs.get(id)))
.or_else(|| libs.iter().find(|l| l.name.eq_ignore_ascii_case(key)))
.map(|l| Some(l.doc.clone()))
.ok_or_else(|| bad(cmd, format!("no library `{key}`")))
}
/// The loaded libraries' designs, as lists show them: `[{library, name, designs}]`; `None` when no
/// loaded library holds graph designs.
pub(super) fn libraries_json(s: &Session) -> Option<Value> {
let libs: Vec<Value> = s
.graph_design_libraries
.iter()
.map(|l| json!({ "library": shown_library_id(s, &l.id), "name": l.name, "designs": design_names(&l.doc) }))
.collect();
(!libs.is_empty()).then(|| json!(libs))
}
/// The library design `p`'s `design` names, with the library to bring it in from, when `p` gives a
/// `library` and the document has no design of that name: the document's own design of a name is
/// the one a graph draws with.
pub(super) fn from_library(s: &Session, p: &Value, cmd: &str) -> Result<Option<(Arc<Document>, String)>> {
let Some(lib) = library_param(s, p, cmd)? else { return Ok(None) };
let Some(Value::String(n)) = p.get("design") else { return Ok(None) };
if s.doc()?.doc.graph_designs.iter().any(|x| x.name == *n) {
return Ok(None);
}
if !lib.graph_designs.iter().any(|x| x.name == *n) {
return Err(bad(cmd, format!("no design named `{n}`")));
}
Ok(Some((lib, n.clone())))
}
/// Add designs `names` of library `lib` to `d` with the resources their art uses, and redraw the
/// graphs that already name a design the document lacked: one of `names`, or one their art uses.
/// The graphs in the art of the symbols that came in are drawn with the designs the document kept.
pub(super) fn bring_in(d: &mut Document, lib: &Document, names: &[String]) -> Result<()> {
let imported = import_graph_designs(lib, d, names)?;
if !imported.kept_designs.is_empty() {
redraw_symbols_with_designs(d, &imported.added_symbols, &imported.kept_designs);
}
if !imported.added_designs.is_empty() {
refresh_graphs(d, &imported.added_designs, &[], &BTreeSet::new())?;
}
Ok(())
}
/// [`bring_in`] library design `name` for graph `id`, whose new spec is `spec`: when that redraws
/// the graph, `spec` takes the rectangle the redraw gave it, so a graph moved or resized since it
/// was last drawn stays where it is.
pub(super) fn bring_in_for(d: &mut Document, lib: &Document, name: &str, id: super::NodeId, spec: &mut GraphSpec) -> Result<()> {
bring_in(d, lib, &[name.to_string()])?;
if let Some(g) = d.node(id).and_then(|n| n.extras().graph.as_deref()) {
spec.rect = g.rect;
}
Ok(())
}
/// Whether graph `g` draws a series with design `name`: as the marker of a series drawn with
/// markers (every series of a scatter or radar graph, and line series) while Mark Data Points is
/// on or the legend has an entry for the series, or as the columns of a series drawn as columns or
/// bars.
fn draws_with(g: &GraphSpec, name: &str) -> bool {
let scatter = g.kind == GraphKind::Scatter;
let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES);
// The legend draws entry `s` with marker design `s`, and leaves out an entry whose label is blank
// (a scatter graph's entries are its pairs of series, labeled by the first of each pair).
let in_legend = |s: usize| {
let entries = if scatter { nser.div_ceil(2) } else { nser };
let label = g.series.get(if scatter { s * 2 } else { s }).map_or("", String::as_str);
g.legend && !g.series.is_empty() && s < entries && !super::labels::blank_label(label)
};
// Point markers use the same range of designs: a scatter graph plots a pair of series for each.
let plotted = if scatter { nser.div_ceil(2) } else { nser };
let shown = |s: usize| s < plotted && (g.mark_points || in_legend(s));
let marked = |s: usize| shown(s) && (matches!(g.kind, GraphKind::Scatter | GraphKind::Radar) || g.series_kind(s) == GraphKind::Line);
let columnar = |s: usize| matches!(g.series_kind(s), GraphKind::Column | GraphKind::StackedColumn | GraphKind::Bar | GraphKind::StackedBar);
g.series_markers.iter().enumerate().any(|(s, m)| m.as_deref() == Some(name) && marked(s))
|| g.series_columns.iter().enumerate().any(|(s, c)| c.as_ref().is_some_and(|c| c.design == name) && columnar(s))
}
/// Whether graph `g` names design `name` for a series, as its marker or its columns, whether or
/// not the series draws with it.
fn names_design(g: &GraphSpec, name: &str) -> bool {
g.series_markers.iter().flatten().any(|m| m == name) || g.series_columns.iter().flatten().any(|c| c.design == name)
}
/// Regenerate the graphs whose series use design `name` (it was added or removed).
/// Regenerate the graphs whose series use design `name` (it was added or removed), in the layers,
/// in opacity-mask art and in symbols' art.
fn refresh_graphs_using(d: &mut Document, name: &str) -> Result<()> {
let mut ids = vec![];
refresh_graphs(d, &BTreeSet::from([name.to_string()]), &[], &BTreeSet::new())
}
/// Regenerate the graphs that draw a series with one of the designs `names`, in the layers, in
/// opacity-mask art and in symbols' art, except those in the subtrees of `skip` and in the art of
/// symbols `skip_symbols`.
pub(crate) fn refresh_graphs(d: &mut Document, names: &BTreeSet<String>, skip: &[super::NodeId], skip_symbols: &BTreeSet<String>) -> Result<()> {
let mut skipped = std::collections::HashSet::new();
for n in skip.iter().filter_map(|id| d.node(*id)) {
n.walk(&mut |m| {
skipped.insert(m.id);
});
}
let (mut ids, mut masked) = (vec![], vec![]);
d.walk(|n| {
if n.extras().graph.as_deref().is_some_and(|g| draws_with(g, name)) {
if skipped.contains(&n.id) {
return;
}
if n.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) {
ids.push(n.id);
}
if n.extras().mask.as_deref().is_some_and(|m| holds(&m.art, names)) {
masked.push(n.id);
}
});
for id in ids {
if let Some(spec) = d.node(id).and_then(|n| n.extras().graph.as_deref().cloned()) {
regenerate(d, id, spec)?;
}
}
// The graphs in objects' opacity-mask art.
for id in masked {
let Some(mut art) = d.node(id).and_then(|n| n.extras().mask.as_deref()).map(|m| (*m.art).clone()) else { continue };
redraw_in(d, &mut art, names);
if let Some(mask) = d.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()) {
mask.art = Arc::new(art);
}
}
// And the graphs in symbols' art, which instances draw.
let symbols: BTreeSet<String> = d.symbols.iter().map(|s| s.name.clone()).filter(|s| !skip_symbols.contains(s)).collect();
redraw_symbols_with_designs(d, &symbols, names);
Ok(())
}
/// The designs no graph's series draw with (Select Unused).
/// [`redraw_in`] for the clipboard: graph art `n`, outside the document, drawn again with `d`'s
/// designs `names`.
pub(crate) fn redraw_detached(d: &mut Document, n: &mut Node, names: &BTreeSet<String>) {
if holds(n, names) {
redraw_in(d, n, names);
}
}
/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that draws a series
/// with one of the designs `names`.
pub(crate) fn holds_designs(n: &Node, names: &BTreeSet<String>) -> bool {
holds(n, names)
}
/// Draw the graphs in the subtrees of `ids` again that draw a series with one of the designs
/// `names`: pasted graphs, after the paste kept the document's own designs of those names.
pub(crate) fn redraw_with_designs(d: &mut Document, ids: &[super::NodeId], names: &std::collections::BTreeSet<String>) -> Result<()> {
for id in ids {
let Some(mut n) = d.node(*id).filter(|n| holds(n, names)).cloned() else { continue };
redraw_in(d, &mut n, names);
*d.node_mut(*id).ok_or(super::EngineError::NoNode(*id))? = n;
}
Ok(())
}
/// Draw the graphs in the art of symbols `symbols` again that draw a series with one of the
/// designs `names`: graphs of the symbols a paste added, after the paste kept the document's own
/// designs of those names.
pub(crate) fn redraw_symbols_with_designs(
d: &mut Document,
symbols: &std::collections::BTreeSet<String>,
names: &std::collections::BTreeSet<String>,
) {
for i in 0..d.symbols.len() {
let Some(s) = d.symbols.get(i).filter(|s| symbols.contains(&s.name) && holds(&s.art, names)) else { continue };
let old = s.art.clone();
let mut art = (*old).clone();
redraw_in(d, &mut art, names);
let Some(s) = d.symbols.get_mut(i) else { continue };
s.art = Arc::new(art);
// Instances' changes to parts the redraw replaced are dropped.
let name = s.name.clone();
crate::cmd::symboledit::follow_art_change(d, &name, &old);
}
}
/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that draws a series
/// with one of the designs `names`.
fn holds(n: &Node, names: &std::collections::BTreeSet<String>) -> bool {
let mut found = false;
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
found |= m.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name)));
});
found
}
/// Redraw the graphs of `n`'s subtree, the art of opacity masks included, that draw a series with
/// one of the designs `names`.
fn redraw_in(d: &mut Document, n: &mut Node, names: &std::collections::BTreeSet<String>) {
if let Some(mut art) = n.extras().mask.as_deref().filter(|m| holds(&m.art, names)).map(|m| (*m.art).clone()) {
redraw_in(d, &mut art, names);
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) {
mask.art = Arc::new(art);
}
}
if n.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) {
regenerate_detached(d, n);
return;
}
if let Some(children) = n.children_mut() {
for c in children.iter_mut().filter(|c| holds(c, names)) {
redraw_in(d, Arc::make_mut(c), names);
}
}
}
/// The designs no graph's series draw with (Select Unused): graphs in the layers, in opacity-mask
/// art and in symbols' art count.
fn unused_designs(d: &Document) -> Vec<String> {
let mut used = std::collections::HashSet::new();
d.walk(|n| {
let mut note = |n: &Node| {
if let Some(g) = n.extras().graph.as_deref() {
used.extend(g.series_markers.iter().flatten().cloned());
used.extend(g.series_columns.iter().flatten().map(|c| c.design.clone()));
}
});
};
for art in d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)) {
vectorcraft_doc::swatches::walk_with_masks(art, &mut note);
}
d.graph_designs.iter().map(|x| x.name.clone()).filter(|n| !used.contains(n)).collect()
}
/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that names design
/// `name` for a series ([`names_design`]).
fn names_in(n: &Node, name: &str) -> bool {
let mut found = false;
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
found |= m.extras().graph.as_deref().is_some_and(|g| names_design(g, name));
});
found
}
/// Graph `g`'s series that name design `old` name `new` instead.
fn rename_series(g: &mut GraphSpec, old: &str, new: &str) {
for m in g.series_markers.iter_mut().flatten().filter(|m| **m == old) {
*m = new.to_string();
}
for c in g.series_columns.iter_mut().flatten().filter(|c| c.design == old) {
c.design = new.to_string();
}
}
/// [`rename_series`] for the graphs of `n`'s subtree, the art of opacity masks included.
fn rename_in(n: &mut Node, old: &str, new: &str) {
if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()).filter(|m| names_in(&m.art, old)) {
rename_in(Arc::make_mut(&mut mask.art), old, new);
}
if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) {
rename_series(g, old, new);
}
if let Some(children) = n.children_mut() {
for c in children.iter_mut().filter(|c| names_in(c, old)) {
rename_in(Arc::make_mut(c), old, new);
}
}
}
/// Design names from param `key`: one name or a list of names.
fn names_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Vec<String>>> {
match p.get(key) {
@@ -105,22 +352,29 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(x) = d.graph_designs.iter_mut().find(|x| x.name == old) {
x.name = new.clone();
}
let mut graphs = vec![];
let (mut graphs, mut masked) = (vec![], vec![]);
d.walk(|n| {
if n.extras().graph.as_deref().is_some_and(|g| draws_with(g, &old)) {
if n.extras().graph.as_deref().is_some_and(|g| names_design(g, &old)) {
graphs.push(n.id);
}
if n.extras().mask.as_deref().is_some_and(|m| names_in(&m.art, &old)) {
masked.push(n.id);
}
});
for id in graphs {
if let Some(g) = d.node_mut(id).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) {
for m in g.series_markers.iter_mut().flatten().filter(|m| **m == old) {
*m = new.clone();
}
for c in g.series_columns.iter_mut().flatten().filter(|c| c.design == old) {
c.design = new.clone();
}
rename_series(g, &old, &new);
}
}
// The graphs in opacity-mask art and in symbols' art follow too, their art as it is.
for id in masked {
if let Some(mask) = d.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()) {
rename_in(Arc::make_mut(&mut mask.art), &old, &new);
}
}
for s in d.symbols.iter_mut().filter(|s| names_in(&s.art, &old)) {
rename_in(Arc::make_mut(&mut s.art), &old, &new);
}
Ok(())
})?;
return Ok(json!({ "name": to }));
@@ -159,7 +413,29 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result<Value> {
})?;
return ok();
}
// Designs from a document loaded as a library: those the document has under the same name stay
// as they are.
if let Some(mut wanted) = names_param(p, "add", C)? {
let lib = library_param(s, p, C)?.ok_or_else(|| bad(C, "missing `library`"))?;
if let Some(n) = wanted.iter().find(|n| !lib.graph_designs.iter().any(|x| x.name == **n)) {
return Err(bad(C, format!("no design named `{n}`")));
}
let mut seen = std::collections::HashSet::new();
wanted.retain(|n| seen.insert(n.clone()));
let (existing, added): (Vec<String>, Vec<String>) = wanted.into_iter().partition(|n| taken(s, n));
if !added.is_empty() {
s.edit("New Design", |d, _| bring_in(d, &lib, &added))?;
}
return Ok(json!({ "added": added, "existing": existing }));
}
if let Some(lib) = library_param(s, p, C)? {
return Ok(json!({ "designs": design_names(&lib) }));
}
// The list, with the designs no graph draws with (Select Unused picks those).
let d = &s.doc()?.doc;
Ok(json!({ "designs": design_names(d), "unused": unused_designs(d) }))
let mut out = json!({ "designs": design_names(d), "unused": unused_designs(d) });
if let Some(libs) = libraries_json(s) {
out["libraries"] = libs;
}
Ok(out)
}
+27 -9
View File
@@ -109,6 +109,33 @@ pub(crate) fn edit_graph_art(n: &mut Node, edit: impl FnOnce(&mut Node)) {
/// generation, which is recorded in the spec's `placed_art` bounds, or `placed` in graphs saved without them).
pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> Result<()> {
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
carry_moves(n, &mut spec);
let children = generate(d, &spec);
spec.placed = children_bounds(&children);
spec.placed_art = art_bounds(&children);
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
if let Some(ch) = n.children_mut() {
*ch = children;
}
n.extras_mut().graph = Some(Box::new(spec));
Ok(())
}
/// [`regenerate`] graph `n` from its own spec, where `n` is outside `d`'s layers (in a symbol's art).
pub(super) fn regenerate_detached(d: &mut Document, n: &mut Node) {
let Some(mut spec) = n.extras().graph.as_deref().cloned() else { return };
carry_moves(n, &mut spec);
let children = generate(d, &spec);
spec.placed = children_bounds(&children);
spec.placed_art = art_bounds(&children);
if let Some(ch) = n.children_mut() {
*ch = children;
}
n.extras_mut().graph = Some(Box::new(spec));
}
/// Adjust `spec`'s plot rect for any move or scale of graph `n` since its last generation.
fn carry_moves(n: &Node, spec: &mut GraphSpec) {
if let Some((placed, now)) = measured(n)
&& placed.width() > 1e-9
&& placed.height() > 1e-9
@@ -119,15 +146,6 @@ pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> R
* Affine::translate(-placed.origin().to_vec2());
spec.rect = a.transform_rect_bbox(spec.rect);
}
let children = generate(d, &spec);
spec.placed = children_bounds(&children);
spec.placed_art = art_bounds(&children);
let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?;
if let Some(ch) = n.children_mut() {
*ch = children;
}
n.extras_mut().graph = Some(Box::new(spec));
Ok(())
}
pub(super) fn create(s: &mut Session, p: &Value) -> Result<Value> {
+22 -4
View File
@@ -1,4 +1,4 @@
use super::designs::design_names;
use super::designs::{bring_in_for, design_names, from_library, libraries_json};
use super::edit::{regenerate, spec_of, target};
use super::series::{picked_series, reselect_series};
use super::{Affine, Arc, Document, GraphSpec, Node, NodeKind, Rect, Result, Session, Value, bad, json};
@@ -55,7 +55,7 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result<Value> {
let mut spec = spec_of(s, id)?;
let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES);
let picked = picked_series(s, p, id, count, C)?;
let names = design_names(&s.doc()?.doc);
let mut names = design_names(&s.doc()?.doc);
let Some(v) = p.get("design") else {
// The design the picked series (all of them with none picked) share, or null.
let all: Vec<usize> = if picked.is_empty() { (0..count).collect() } else { picked };
@@ -63,8 +63,15 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result<Value> {
let used: Vec<Option<&String>> =
all.iter().map(|i| spec.series_markers.get(*i).and_then(Option::as_ref).filter(|n| names.contains(n))).collect();
let shared = used.first().copied().flatten().filter(|d| used.iter().all(|x| *x == Some(*d)));
return Ok(json!({ "designs": names, "design": shared }));
let mut out = json!({ "designs": names, "design": shared });
if let Some(libs) = libraries_json(s) {
out["libraries"] = libs;
}
return Ok(out);
};
// A design of a loaded library comes into the document in the same undo step.
let library = from_library(s, p, C)?;
names.extend(library.as_ref().map(|(_, n)| n.clone()));
let design = match v {
Value::Null => None,
Value::String(n) if names.contains(n) => Some(n.clone()),
@@ -83,10 +90,21 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result<Value> {
while spec.series_markers.last().is_some_and(Option::is_none) {
spec.series_markers.pop();
}
if marker_cost(&spec, &marker_designs(&s.doc()?.doc, &spec)) > MARKER_BUDGET {
let cost = match &library {
Some((lib, name)) => {
let mut probe = (*s.doc()?.doc).clone();
bring_in_for(&mut probe, lib, name, id, &mut spec)?;
marker_cost(&spec, &marker_designs(&probe, &spec))
}
None => marker_cost(&spec, &marker_designs(&s.doc()?.doc, &spec)),
};
if cost > MARKER_BUDGET {
return Err(bad(C, "the design is too big to draw at every data point of this graph"));
}
s.edit("Graph Marker", |d, sel| {
if let Some((lib, name)) = &library {
bring_in_for(d, lib, name, id, &mut spec)?;
}
regenerate(d, id, spec)?;
if !reselect.is_empty() {
reselect_series(d, sel, id, &reselect);
+958
View File
@@ -5469,6 +5469,964 @@ fn graph_designs_are_saved_pasted_and_deleted() {
assert!(series_parts(&s, id, 0).iter().all(|n| matches!(n.kind, NodeKind::Path { .. })));
}
/// Graph design "Coin" in the active document: a 10 × 10 rectangle filled with global swatch "Gold".
fn save_coin_design(s: &mut Session) {
s.execute("swatch.new", &json!({"name": "Gold", "color": "#d4a017", "global": true})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"swatch": "Gold", "ids": [r]})).unwrap();
s.execute("select.set", &json!({"ids": [r]})).unwrap();
s.execute("graph.design", &json!({"new": "Coin"})).unwrap();
}
/// Load a saved document holding [`save_coin_design`]'s design as a swatch library (Other
/// Library…) → its id.
fn load_coin_library(s: &mut Session) -> String {
let mut src = Session::new();
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut src);
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Coins.vectorcraft"});
let r = s.execute("swatch.library.load", &p).unwrap();
assert_eq!(r["graphDesigns"], 1);
r["library"].as_str().unwrap().to_string()
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
/// Whether some object of `n` is filled with a colour linked to swatch `name`.
fn paints_with_swatch(n: &vectorcraft_doc::Node, name: &str) -> bool {
let mut found = false;
n.walk(&mut |m| found |= m.appearance.items.iter().any(|it| matches!(it.paint(), Paint::Solid { swatch: Some(w), .. } if w == name)));
found
}
#[test]
fn designs_of_a_document_loaded_as_a_swatch_library_come_in_when_applied() {
let mut s = Session::new();
let lib = load_coin_library(&mut s);
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
// The Column dialog's list: none of the document's, Coin from the library.
let q = s.execute("graph.column", &json!({})).unwrap();
assert_eq!((q["designs"].clone(), q["libraries"][0]["library"].clone()), (json!([]), json!(lib)));
assert_eq!(q["libraries"][0]["designs"], json!(["Coin"]));
assert!(s.execute("graph.column", &json!({"design": "Coin"})).is_err(), "not the document's");
let steps = undo_len(&s);
s.execute("graph.column", &json!({"design": "Coin", "library": lib})).unwrap();
assert_eq!(undo_len(&s), steps + 1, "one undo step");
let d = &s.doc().unwrap().doc;
assert_eq!(d.graph_designs.iter().map(|g| g.name.as_str()).collect::<Vec<_>>(), ["Coin"]);
assert!(d.swatch("Gold").is_some_and(|w| w.global), "the swatch the design's art uses comes along");
assert!(paints_with_swatch(&d.graph_designs[0].art, "Gold"));
assert!(paints_with_swatch(series(d.node(id).unwrap(), 0), "Gold"), "the columns draw the design");
// Undo takes the design, its swatch and the columns' design out together.
s.execute("edit.undo", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.graph_designs.is_empty() && d.swatch("Gold").is_none() && spec(&s, id).series_columns.is_empty());
// Marker takes them too.
let line = graph(&mut s, "line");
s.execute("select.set", &json!({"ids": [line.0]})).unwrap();
s.execute("graph.marker", &json!({"design": "Coin", "library": lib})).unwrap();
assert_eq!(spec(&s, line).series_markers, [Some("Coin".to_string()), Some("Coin".to_string())]);
assert!(s.doc().unwrap().doc.swatch("Gold").is_some());
// An unknown library or design, and a library that is not a string, are refused.
for p in [json!({"design": "Coin", "library": "Nope"}), json!({"design": "Nope", "library": lib}), json!({"design": "Coin", "library": 3})] {
assert!(s.execute("graph.column", &p).is_err(), "{p}");
}
}
#[test]
fn a_library_design_applied_to_a_moved_graph_that_names_it_keeps_the_graph_in_place() {
let mut s = Session::new();
let lib = load_coin_library(&mut s);
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
// A library's name works in any case, as swatch library names do.
assert_eq!(s.execute("graph.design", &json!({"library": "COINS"})).unwrap(), json!({"designs": ["Coin"]}));
for (kind, cmd) in [("line", "graph.marker"), ("column", "graph.column")] {
// The graph names design "Coin", which the document no longer has, and is moved after.
save_design(&mut s, "Coin");
let id = graph(&mut s, kind);
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute(cmd, &json!({"design": "Coin"})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
let rect = spec(&s, id).rect;
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.move", &json!({"dx": 40, "dy": -10})).unwrap();
s.execute(cmd, &json!({"id": id.0, "design": "Coin", "library": lib})).unwrap();
let now = spec(&s, id).rect;
assert!((now.x0 - (rect.x0 + 40.0)).abs() < 1e-6 && (now.y0 - (rect.y0 - 10.0)).abs() < 1e-6, "{cmd}: {now:?}");
assert!((now.width() - rect.width()).abs() < 1e-6 && (now.height() - rect.height()).abs() < 1e-6, "{cmd}: {now:?}");
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
}
}
#[test]
fn a_design_the_document_has_under_the_same_name_stays_as_it_is() {
let mut s = Session::new();
let lib = load_coin_library(&mut s);
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
let own = s.doc().unwrap().doc.graph_designs[0].art.clone();
assert_eq!(s.execute("graph.design", &json!({"library": lib})).unwrap(), json!({"designs": ["Coin"]}));
let steps = undo_len(&s);
let r = s.execute("graph.design", &json!({"library": lib, "add": ["Coin", "Coin"]})).unwrap();
assert_eq!(r, json!({"added": [], "existing": ["Coin"]}));
assert_eq!(undo_len(&s), steps, "nothing changed: no undo step");
// Applying it with the library draws with the document's own design.
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin", "library": lib})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.graph_designs.len() == 1 && std::sync::Arc::ptr_eq(&d.graph_designs[0].art, &own));
assert!(d.swatch("Gold").is_none());
assert!(s.execute("graph.design", &json!({"add": "Coin"})).is_err(), "no library");
assert!(s.execute("graph.design", &json!({"library": lib, "add": "Nope"})).is_err());
assert!(s.execute("graph.design", &json!({"library": lib, "add": 4})).is_err());
// The document without it takes it as one undo step.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let r = s.execute("graph.design", &json!({"library": "Coins", "add": "Coin"})).unwrap();
assert_eq!(r, json!({"added": ["Coin"], "existing": []}));
assert!(s.doc().unwrap().doc.swatch("Gold").is_some());
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.graph_designs.is_empty());
}
#[test]
fn a_pasted_graph_brings_the_designs_its_series_draw_with() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
s.execute("edit.paste", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
assert_eq!(d.graph_designs.iter().map(|g| g.name.as_str()).collect::<Vec<_>>(), ["Coin"]);
assert!(paints_with_swatch(&d.graph_designs[0].art, "Gold") && d.swatch("Gold").is_some());
// A data edit redraws the pasted graph with the design.
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
s.execute("graph.setData", &json!({"id": pasted.0, "csv": ",A\nQ1,4\nQ2,6"})).unwrap();
assert!(paints_with_swatch(series(s.doc().unwrap().doc.node(pasted).unwrap(), 0), "Gold"));
// A document with its own design of that name keeps it.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
let own = s.doc().unwrap().doc.graph_designs[0].art.clone();
s.execute("edit.paste", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.graph_designs.len() == 1 && std::sync::Arc::ptr_eq(&d.graph_designs[0].art, &own));
// The pasted graph is drawn with that design straight away.
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
// The document's design is a rectangle and an ellipse, the pasted one a rectangle alone: each
// column and the legend swatch hold two paths.
let paths = |n: &vectorcraft_doc::Node| {
let mut count = 0;
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
count
};
let columns: Vec<usize> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect();
assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design");
}
#[test]
fn a_design_the_document_keeps_brings_none_of_the_pasted_designs_resources() {
// A column graph whose spec names marker design "Coin", which only line series draw: the
// graph's own art does not use the design's swatch.
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.marker", &json!({"design": "Coin"})).unwrap();
assert!(spec(&s, id).series_markers.iter().any(|m| m.as_deref() == Some("Coin")));
assert!(!paints_with_swatch(s.doc().unwrap().doc.node(id).unwrap(), "Gold"));
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
// A document with its own "Coin" keeps it and takes nothing the pasted design's art uses.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
s.execute("edit.paste", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.swatch("Gold").is_none());
// A document without one takes the design and its swatch.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
s.execute("edit.paste", &json!({})).unwrap();
assert!(s.doc().unwrap().doc.swatch("Gold").is_some());
}
#[test]
fn a_pasted_graph_naming_a_deleted_design_draws_with_the_documents_design_of_that_name() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
assert!(spec(&s, id).series_columns.iter().flatten().any(|c| c.design == "Coin"), "the graph still names it");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
s.execute("edit.paste", &json!({})).unwrap();
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
let paths = |n: &vectorcraft_doc::Node| {
let mut count = 0;
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
count
};
let d = &s.doc().unwrap().doc;
let columns: Vec<usize> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect();
assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design");
}
#[test]
fn a_pasted_graph_keeps_its_art_when_only_a_resource_its_design_does_not_use_comes_in_renamed() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
s.execute("swatch.new", &json!({"name": "Ink", "color": "#ff0000", "global": true})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setFill", &json!({"swatch": "Ink", "ids": [r]})).unwrap();
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
// An edit of the graph's art that drawing the graph again would not keep.
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
s.edit("Name", |d, _| {
if let Some(n) = d.node_mut(mark) {
n.name = Some("Mine".into());
}
Ok(())
})
.unwrap();
// A copy of the document holds the same design; its "Ink" is another color, so the pasted
// rectangle's swatch takes the document's color, or with "add" comes in renamed.
let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc));
s.execute("select.set", &json!({"ids": [id.0, r]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("document.open", &json!({"name": "b.vectorcraft", "dataBase64": saved})).unwrap();
s.execute("swatch.edit", &json!({"name": "Ink", "color": "#0000ff"})).unwrap();
for conflict in ["merge", "add"] {
let r = s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap();
let ink_renamed = r["renamed"].as_array().is_some_and(|a| a.iter().any(|x| x["from"] == "Ink"));
let expected = if conflict == "merge" { (json!(1), false) } else { (json!(0), true) };
assert_eq!((r["merged"].clone(), ink_renamed), expected, "{conflict}: {r}");
let st = s.doc().unwrap();
let d = &st.doc;
let pasted = st.selection.objects.iter().copied().find(|i| d.node(*i).is_some_and(|n| n.extras().graph.is_some())).unwrap();
let names: Vec<Option<String>> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect();
assert_eq!(names[0].as_deref(), Some("Mine"), "{conflict}: not drawn again: {names:?}");
}
}
#[test]
fn a_pasted_graph_is_drawn_again_when_its_designs_svg_filter_comes_in_under_another_name() {
const SHIFT: &str = r#"<filter id="Shift"><feOffset dx="3" dy="3"/></filter>"#;
const SHIFT_MORE: &str = r#"<filter id="Shift"><feOffset dx="9" dy="9"/></filter>"#;
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
s.execute("svgFilter.define", &json!({"xml": SHIFT})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("svgFilter.apply", &json!({"name": "Shift", "ids": [r]})).unwrap();
s.execute("select.set", &json!({"ids": [r]})).unwrap();
s.execute("graph.design", &json!({"new": "Coin"})).unwrap();
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
s.edit("Name", |d, _| {
if let Some(n) = d.node_mut(mark) {
n.name = Some("Mine".into());
}
Ok(())
})
.unwrap();
// A copy of the document holds the same design, but its "Shift" filter draws otherwise, so the
// pasted graph's filter keeps its own definition under another name.
let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc));
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("document.open", &json!({"name": "b.vectorcraft", "dataBase64": saved})).unwrap();
s.execute("svgFilter.define", &json!({"xml": SHIFT_MORE, "replace": "Shift"})).unwrap();
s.execute("edit.paste", &json!({})).unwrap();
let st = s.doc().unwrap();
let pasted = st.selection.objects.to_vec()[0];
let names: Vec<Option<String>> = series(st.doc.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect();
assert_ne!(names[0].as_deref(), Some("Mine"), "drawn again with the document's design: {names:?}");
}
#[test]
fn a_symbol_pasted_with_a_graph_inside_draws_it_with_the_documents_design_of_that_name() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
let instance = s.execute("symbol.new", &json!({"name": "Chart"})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [instance]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
// A document whose "Coin" is a rectangle and an ellipse: the symbol's graph draws with it.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
s.execute("edit.paste", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art;
let mut graphs = vec![];
art.walk(&mut |m| {
if m.extras().graph.is_some() {
graphs.push(m.clone());
}
});
let paths = |n: &vectorcraft_doc::Node| {
let mut count = 0;
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
count
};
let columns: Vec<usize> = series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect();
assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design");
}
#[test]
fn a_design_brought_in_from_a_library_redraws_the_graphs_in_symbols_that_name_it() {
let mut s = Session::new();
let lib = load_coin_library(&mut s);
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
// A graph that names "Coin", which the document no longer has, kept as a symbol's art.
save_design(&mut s, "Coin");
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap();
s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap();
let d = &s.doc().unwrap().doc;
let art = &d.symbols.iter().find(|x| x.name == "Chart").unwrap().art;
let mut graphs = vec![];
art.walk(&mut |m| {
if m.extras().graph.is_some() {
graphs.push(m.clone());
}
});
assert!(paints_with_swatch(series(&graphs[0], 0), "Gold"), "drawn with the library's design");
}
#[test]
fn a_design_brought_in_from_a_library_leaves_a_scatter_graph_that_names_it_for_a_slot_it_does_not_plot() {
let mut s = Session::new();
let lib = load_coin_library(&mut s);
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
// Four data columns plot two series, so marker slot 2 is never drawn.
let id = make(&mut s, "scatter", ",y1,x1,y2,x2\nP,1,10,2,20\nQ,3,11,4,22");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
assert!(spec(&s, id).mark_points, "Mark Data Points is on");
s.execute("graph.marker", &json!({"design": "Coin", "library": lib, "seriesIndexes": [2]})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
assert_eq!(spec(&s, id).series_markers.get(2).cloned().flatten().as_deref(), Some("Coin"));
// An edit of the graph's art that drawing the graph again would not keep.
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
s.edit("Name", |d, _| {
if let Some(n) = d.node_mut(mark) {
n.name = Some("Mine".into());
}
Ok(())
})
.unwrap();
s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap();
let names: Vec<Option<String>> = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect();
assert_eq!(names[0].as_deref(), Some("Mine"), "not drawn again: {names:?}");
}
#[test]
fn a_symbol_a_library_design_brings_draws_its_graph_with_the_documents_design_it_keeps() {
// The library's design "A" holds an instance of symbol "Chart", whose graph draws columns with
// the library's "B": a rectangle and an ellipse.
let mut src = Session::new();
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut src, "B");
let id = graph(&mut src, "column");
src.execute("select.set", &json!({"ids": [id.0]})).unwrap();
src.execute("graph.column", &json!({"design": "B"})).unwrap();
let instance = src.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
src.execute("select.set", &json!({"ids": [instance]})).unwrap();
src.execute("graph.design", &json!({"new": "A"})).unwrap();
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
let mut s = Session::new();
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Lib.vectorcraft"});
let lib = s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string();
// The document's own "B" is a single rectangle, and stays.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [r]})).unwrap();
s.execute("graph.design", &json!({"new": "B"})).unwrap();
s.execute("graph.design", &json!({"library": lib, "add": "A"})).unwrap();
let d = &s.doc().unwrap().doc;
assert_eq!(d.graph_designs.len(), 2, "A came in and B stayed");
let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art;
let mut graphs = vec![];
art.walk(&mut |m| {
if m.extras().graph.is_some() {
graphs.push(m.clone());
}
});
let paths = |n: &vectorcraft_doc::Node| {
let mut count = 0;
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
count
};
let columns: Vec<usize> = series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect();
assert_eq!(columns, [1, 1, 1, 1], "drawn with the document's B");
}
#[test]
fn a_design_brought_in_from_a_library_redraws_a_graph_in_an_opacity_mask() {
let mut s = Session::new();
let lib = load_coin_library(&mut s);
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap();
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
s.execute("select.set", &json!({"ids": [r, id.0]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap();
let mut graphs = vec![];
vectorcraft_doc::swatches::walk_with_masks(s.doc().unwrap().doc.node(NodeId(r)).unwrap(), &mut |m| {
if m.extras().graph.is_some() {
graphs.push(m.clone());
}
});
assert!(paints_with_swatch(series(&graphs[0], 0), "Gold"), "drawn with the library's design");
}
#[test]
fn an_instance_drops_its_changes_to_graph_parts_a_design_change_redraws() {
use vectorcraft_doc::symbol_overrides::SymbolOverride;
let mut s = Session::new();
let lib = load_coin_library(&mut s);
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0], "type": "dynamic"})).unwrap()["id"].as_u64().unwrap();
let instance = NodeId(instance);
// A change to the graph itself, and one to a part of it that drawing it again replaces.
let changes = vec![
SymbolOverride { path: vec![], opacity: Some(0.5), ..Default::default() },
SymbolOverride { path: vec![0], opacity: Some(0.25), ..Default::default() },
];
s.edit("Change", |d, _| {
if let Some(n) = d.node_mut(instance) {
n.extras_mut().symbol_overrides = changes;
}
Ok(())
})
.unwrap();
s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap();
let kept = s.doc().unwrap().doc.node(instance).unwrap().extras().symbol_overrides.clone();
assert_eq!(kept.iter().map(|o| o.path.clone()).collect::<Vec<_>>(), [Vec::<u32>::new()], "{kept:?}");
}
#[test]
fn a_graph_in_an_opacity_mask_draws_with_the_documents_design_when_pasted() {
let paths = |n: &vectorcraft_doc::Node| {
let mut count = 0;
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
count
};
let mask_graph = |n: &vectorcraft_doc::Node| {
let mut graphs = vec![];
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
if m.extras().graph.is_some() {
graphs.push(m.clone());
}
});
graphs.into_iter().next().expect("the masked graph")
};
// In a symbol's art and among the pasted objects.
for in_symbol in [true, false] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap();
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("select.set", &json!({"ids": [r, id.0]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
let copied = if in_symbol { s.execute("symbol.new", &json!({"name": "Masked", "ids": [r]})).unwrap()["id"].as_u64().unwrap() } else { r };
s.execute("select.set", &json!({"ids": [copied]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
s.execute("edit.paste", &json!({})).unwrap();
let st = s.doc().unwrap();
let g = if in_symbol {
mask_graph(&st.doc.symbols.iter().find(|x| x.name == "Masked").expect("the symbol came in").art)
} else {
mask_graph(st.doc.node(st.selection.objects.to_vec()[0]).unwrap())
};
let columns: Vec<usize> = series(&g, 0).children().unwrap().iter().map(|n| paths(n)).collect();
assert_eq!(columns, [2, 2, 2, 2], "in a symbol: {in_symbol}");
}
}
#[test]
fn a_graph_pasted_back_after_its_design_was_made_again_draws_with_the_new_design() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
// Made again under the same name as a rectangle and an ellipse.
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
save_design(&mut s, "Coin");
s.execute("edit.paste", &json!({})).unwrap();
let pasted = s.doc().unwrap().selection.objects.to_vec()[0];
let paths = |n: &vectorcraft_doc::Node| {
let mut count = 0;
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
count
};
let d = &s.doc().unwrap().doc;
let columns: Vec<usize> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect();
assert_eq!(columns, [2, 2, 2, 2], "drawn with the design the document has now");
}
/// The graphs in `n`'s subtree, those in opacity-mask art included.
fn graphs_in(n: &vectorcraft_doc::Node) -> Vec<vectorcraft_doc::Node> {
let mut graphs = vec![];
vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| {
if m.extras().graph.is_some() {
graphs.push(m.clone());
}
});
graphs
}
/// Load a saved document holding [`save_coin_design`]'s "Coin" and design "Chart", an instance of
/// symbol "Plot" whose column graph names "Coin" as its columns (`columns`) or only as a marker
/// its columns do not draw, as a swatch library → its id.
fn load_chart_library(s: &mut Session, columns: bool) -> String {
let mut src = Session::new();
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut src);
let id = graph(&mut src, "column");
src.execute("select.set", &json!({"ids": [id.0]})).unwrap();
src.execute(if columns { "graph.column" } else { "graph.marker" }, &json!({"design": "Coin"})).unwrap();
let instance = src.execute("symbol.new", &json!({"name": "Plot", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
src.execute("select.set", &json!({"ids": [instance]})).unwrap();
src.execute("graph.design", &json!({"new": "Chart"})).unwrap();
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Charts.vectorcraft"});
s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string()
}
#[test]
fn a_library_design_brings_none_of_the_resources_of_a_design_the_document_keeps() {
let mut s = Session::new();
let lib = load_chart_library(&mut s, false);
// The document keeps its own "Coin": nothing the library's "Coin" uses comes in.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.symbols.iter().any(|x| x.name == "Plot"), "the design's symbol came in");
assert!(d.swatch("Gold").is_none());
// A document without one takes the design and its swatch.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.graph_designs.iter().any(|x| x.name == "Coin") && d.swatch("Gold").is_some());
}
#[test]
fn a_design_a_library_design_brings_along_redraws_the_graphs_that_name_it() {
let mut s = Session::new();
let lib = load_chart_library(&mut s, true);
// A graph that names "Coin", which the document no longer has.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
let r = s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap();
assert_eq!(r, json!({"added": ["Chart"], "existing": []}));
let d = &s.doc().unwrap().doc;
assert!(paints_with_swatch(series(d.node(id).unwrap(), 0), "Gold"), "drawn with the library's Coin");
}
#[test]
fn a_paste_that_adds_a_design_redraws_the_documents_graphs_that_name_it_and_not_the_pasted_ones() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
// An edit of the copied graph's art that drawing it again would not keep.
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
s.edit("Name", |d, _| {
if let Some(n) = d.node_mut(mark) {
n.name = Some("Mine".into());
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
// A document whose graph names "Coin", which it no longer has.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
let own = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [own.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
s.execute("edit.paste", &json!({})).unwrap();
let st = s.doc().unwrap();
assert!(paints_with_swatch(series(st.doc.node(own).unwrap(), 0), "Gold"), "drawn with the pasted Coin");
let pasted = st.selection.objects.to_vec()[0];
let first = series(st.doc.node(pasted).unwrap(), 0).children().unwrap()[0].name.clone();
assert_eq!(first.as_deref(), Some("Mine"), "the pasted graph is not drawn again");
}
#[test]
fn a_paste_that_adds_a_marker_design_a_graph_does_not_show_leaves_that_graph_as_it_is() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
// A line graph whose series name "Coin", which the document no longer has, as a marker that
// Mark Data Points does not show, with no legend or with a legend that has no entry for them.
for (legend, csv) in [(false, ",2024,2025\nQ1,3,2\nQ2,5,4"), (true, ",,\nQ1,3,2\nQ2,5,4")] {
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
let p = json!({"type": "line", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv});
let own = NodeId(s.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [own.0]})).unwrap();
s.execute("graph.marker", &json!({"design": "Coin"})).unwrap();
s.execute("graph.setType", &json!({"id": own.0, "markPoints": false, "legend": legend})).unwrap();
s.execute("graph.design", &json!({"delete": "Coin"})).unwrap();
let mark = series(s.doc().unwrap().doc.node(own).unwrap(), 0).children().unwrap()[0].id;
s.edit("Name", |d, _| {
if let Some(n) = d.node_mut(mark) {
n.name = Some("Mine".into());
}
Ok(())
})
.unwrap();
s.execute("edit.paste", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.graph_designs.iter().any(|x| x.name == "Coin"), "legend {legend}: the paste added Coin");
let first = series(d.node(own).unwrap(), 0).children().unwrap()[0].name.clone();
assert_eq!(first.as_deref(), Some("Mine"), "legend {legend}: not drawn again");
}
}
#[test]
fn a_symbol_pasted_twice_with_a_graph_the_document_draws_again_is_added_once() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [instance]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
// A document whose "Coin" is other art: the first paste draws the symbol's graph with it.
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
// The paths of each column of the symbol's graph: 2 for the document's Coin, 1 for the copied one.
let columns = |s: &Session| {
let art = s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art.clone();
let graph = graphs_in(&art).remove(0);
let paths = |n: &vectorcraft_doc::Node| {
let mut count = 0;
n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. })));
count
};
series(&graph, 0).children().unwrap().iter().map(|n| paths(n)).collect::<Vec<usize>>()
};
s.execute("edit.paste", &json!({})).unwrap();
assert_eq!(columns(&s), [2, 2, 2, 2], "the first paste draws with the document's Coin");
s.execute("edit.paste", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
let names: Vec<&str> = d.symbols.iter().map(|x| x.name.as_str()).filter(|n| n.starts_with("Chart")).collect();
assert_eq!(names, ["Chart"]);
assert_eq!(columns(&s), [2, 2, 2, 2], "drawn with the document's Coin");
}
#[test]
fn a_symbol_pasted_twice_whose_designs_swatch_takes_the_documents_color_is_added_once() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
// A copy of the document holds the same "Coin"; its "Gold" is another color.
let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc));
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [instance]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
for conflict in ["merge", "add"] {
s.execute("document.open", &json!({"name": format!("{conflict}.vectorcraft"), "dataBase64": saved})).unwrap();
s.execute("swatch.edit", &json!({"name": "Gold", "color": "#0000ff"})).unwrap();
let r = s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap();
let gold_renamed = r["renamed"].as_array().is_some_and(|a| a.iter().any(|x| x["from"] == "Gold"));
let expected = if conflict == "merge" { (json!(1), false) } else { (json!(0), true) };
assert_eq!((r["merged"].clone(), gold_renamed), expected, "{conflict}: {r}");
s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap();
let d = &s.doc().unwrap().doc;
let names: Vec<&str> = d.symbols.iter().map(|x| x.name.as_str()).filter(|n| n.starts_with("Chart")).collect();
assert_eq!(names, ["Chart"], "{conflict}");
}
}
#[test]
fn a_pasted_graph_that_only_names_a_kept_design_as_an_undrawn_marker_keeps_its_art() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
// A column graph whose series name "Coin" as a marker, which columns do not draw.
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.marker", &json!({"design": "Coin"})).unwrap();
let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
s.edit("Name", |d, _| {
if let Some(n) = d.node_mut(mark) {
n.name = Some("Mine".into());
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("edit.copy", &json!({})).unwrap();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
s.execute("edit.paste", &json!({})).unwrap();
let st = s.doc().unwrap();
let pasted = st.selection.objects.to_vec()[0];
let first = series(st.doc.node(pasted).unwrap(), 0).children().unwrap()[0].name.clone();
assert_eq!(first.as_deref(), Some("Mine"), "not drawn again");
}
#[test]
fn renaming_a_design_renames_it_in_the_graphs_of_symbols_and_opacity_masks() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_coin_design(&mut s);
let in_symbol = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [in_symbol.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("symbol.new", &json!({"name": "Chart", "ids": [in_symbol.0]})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap();
let masked = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [masked.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("select.set", &json!({"ids": [r, masked.0]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
let before = graphs_in(&s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art);
s.execute("graph.design", &json!({"rename": "Coin", "to": "Medal"})).unwrap();
let d = &s.doc().unwrap().doc;
let symbol = graphs_in(&d.symbols.iter().find(|x| x.name == "Chart").unwrap().art);
let mask = graphs_in(d.node(NodeId(r)).unwrap());
for (where_, g) in [("symbol", &symbol[0]), ("mask", &mask[0])] {
let designs: Vec<String> = g.extras().graph.as_deref().unwrap().series_columns.iter().flatten().map(|c| c.design.clone()).collect();
assert!(!designs.is_empty() && designs.iter().all(|n| n == "Medal"), "{where_}: {designs:?}");
}
assert_eq!(symbol[0].children(), before[0].children(), "the symbol's graph keeps its art");
}
#[test]
fn a_design_only_a_graph_in_a_symbol_or_a_mask_draws_with_is_not_unused() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut s, "Coin");
save_design(&mut s, "Pill");
let id = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Coin"})).unwrap();
s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap();
let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap();
let masked = graph(&mut s, "column");
s.execute("select.set", &json!({"ids": [masked.0]})).unwrap();
s.execute("graph.column", &json!({"design": "Pill"})).unwrap();
s.execute("select.set", &json!({"ids": [r, masked.0]})).unwrap();
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
assert_eq!(s.execute("graph.design", &json!({})).unwrap()["unused"], json!([]));
}
#[test]
fn a_library_copied_to_user_defined_keeps_its_graph_designs_under_the_loaded_id() {
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-user");
let mut s = Session::new();
s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string()));
let loaded = load_coin_library(&mut s);
// The User Defined copy is a swatch file: it holds the swatches alone.
let copy = s.execute("swatch.library.copyToUser", &json!({"library": loaded})).unwrap()["library"].as_str().unwrap().to_string();
assert_ne!(copy, loaded);
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let libraries = s.execute("graph.design", &json!({})).unwrap()["libraries"].clone();
assert_eq!(libraries, json!([{"library": loaded, "name": libraries[0]["name"], "designs": ["Coin"]}]));
assert_eq!(s.execute("graph.design", &json!({"library": loaded})).unwrap(), json!({"designs": ["Coin"]}));
assert!(s.execute("graph.design", &json!({"library": copy})).is_err());
}
#[test]
fn a_swatch_library_file_over_the_size_limit_is_refused_before_it_is_read() {
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-size");
let path = dir.join("big.vectorcraft");
let f = std::fs::File::create(&path).unwrap();
f.set_len(((256 << 20) + 1) as u64).unwrap();
let mut s = Session::new();
let e = s.execute("swatch.library.load", &json!({"path": path})).unwrap_err().to_string();
assert!(e.contains("larger than 256 MB"), "{e}");
}
#[test]
fn a_document_with_graph_designs_and_no_swatches_loads_for_its_designs() {
let mut src = Session::new();
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
save_design(&mut src, "Pill");
let mut d = (*src.doc().unwrap().doc).clone();
d.swatches.clear();
d.swatch_groups.clear();
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d)), "name": "Pills.vectorcraft"});
let mut s = Session::new();
let r = s.execute("swatch.library.load", &p).unwrap();
assert_eq!((r["count"].clone(), r["graphDesigns"].clone()), (json!(0), json!(1)));
// Without graph designs it has nothing to offer.
d.graph_designs.clear();
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d)), "name": "Bare.vectorcraft"});
let e = s.execute("swatch.library.load", &p).unwrap_err().to_string();
assert!(e.contains("has no swatches of its own"), "{e}");
}
#[test]
fn a_design_library_keeps_the_sources_color_for_a_default_swatch_name() {
let mut src = Session::new();
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
// A default swatch the source made global and gave another color, used by a design.
let name = src.doc().unwrap().doc.swatches.iter().find(|w| !w.name.starts_with('[')).unwrap().name.clone();
let mine = Paint::solid(vectorcraft_color::Color::rgb(0.1, 0.7, 0.3));
let (n, p) = (name.clone(), mine.clone());
src.edit("Change", move |d, _| {
if let Some(w) = d.swatches.iter_mut().find(|w| w.name == n) {
w.paint = p;
w.global = true;
}
Ok(())
})
.unwrap();
let r = src.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
src.execute("paint.setFill", &json!({"swatch": name, "ids": [r]})).unwrap();
src.execute("select.set", &json!({"ids": [r]})).unwrap();
src.execute("graph.design", &json!({"new": "Green"})).unwrap();
let lib = crate::cmd::clipboard::resources::graph_design_library(&src.doc().unwrap().doc).unwrap();
let named: Vec<_> = lib.swatches.iter().filter(|w| w.name == name).collect();
assert_eq!(named.len(), 1, "one swatch named {name}");
assert_eq!(named[0].paint, mine);
// And one named like a swatch in a default group.
let grouped = src.doc().unwrap().doc.swatch_groups.iter().flat_map(|g| g.swatches.iter()).next().unwrap().name.clone();
let (n, p) = (grouped.clone(), mine.clone());
src.edit("Change", move |d, _| {
if let Some(w) = d.swatch_groups.iter_mut().flat_map(|g| g.swatches.iter_mut()).find(|w| w.name == n) {
w.paint = p;
w.global = true;
}
Ok(())
})
.unwrap();
let r = src.execute("shape.rectangle", &json!({"x": 650, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
src.execute("paint.setFill", &json!({"swatch": grouped, "ids": [r]})).unwrap();
src.execute("select.set", &json!({"ids": [r]})).unwrap();
src.execute("graph.design", &json!({"new": "Grouped"})).unwrap();
let lib = crate::cmd::clipboard::resources::graph_design_library(&src.doc().unwrap().doc).unwrap();
let all: Vec<_> = lib.swatches.iter().chain(lib.swatch_groups.iter().flat_map(|g| g.swatches.iter())).filter(|w| w.name == grouped).collect();
assert_eq!(all.len(), 1, "one swatch named {grouped}");
}
#[test]
fn inline_swatch_library_data_over_the_size_limit_is_refused_before_it_is_read() {
// With a limit of 3 bytes: text and base64 of 3 bytes pass, and of 4 bytes are refused.
let too_big = |p: serde_json::Value| crate::cmd::swatchlib::library_too_big(&p, "swatch.library.load", 3).unwrap();
assert!(!too_big(json!({"data": "abc"})));
assert!(too_big(json!({"data": "abcd"})));
let b64 = |n: usize| vectorcraft_format::base64_encode(&vec![7u8; n]);
assert!(!too_big(json!({"dataBase64": b64(3)})));
assert!(too_big(json!({"dataBase64": b64(4)})));
}
#[test]
fn a_swatch_library_file_is_read_no_further_than_the_size_limit() {
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-bound");
let path = dir.join("grown.gpl");
std::fs::write(&path, [b'a'; 9]).unwrap();
let mut s = Session::new();
let p = json!({"path": path});
let parsed = |_: &[u8], _: &str| Err(crate::EngineError::Other("parsed".into()));
// A file that grew past the limit after the size check is refused when it is read.
let e = s.swatch_libraries.load_within(&p, "swatch.library.load", Some(8), parsed).unwrap_err().to_string();
assert!(e.contains("larger than"), "{e}");
let e = s.swatch_libraries.load_within(&p, "swatch.library.load", Some(9), parsed).unwrap_err().to_string();
assert!(e.contains("parsed"), "{e}");
}
#[test]
fn reading_the_head_of_a_swatch_library_file_stops_at_the_limit() {
let dir = vectorcraft_testkit::TempDir::new("graph-design-library-head");
let path = dir.join("long.gpl");
std::fs::write(&path, vec![b'a'; 1 << 20]).unwrap();
// The read the limit check relies on returns the bytes up to one past the limit, not the file.
let head = crate::cmd::fileio::read_file_head(&path.to_string_lossy(), 9).unwrap();
assert_eq!(head.len(), 9);
}
#[test]
fn a_library_design_brings_its_symbols_with_their_symbol_options() {
// The source design is an instance of symbol "Corner" with 9-slice scaling, a top-left
// registration point and the Graphic export type.
let mut src = Session::new();
src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
src.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap();
src.execute("select.all", &json!({})).unwrap();
let opts = json!({"name": "Corner", "nineSlice": true, "registration": 0, "exportType": "graphic"});
let inst = src.execute("symbol.new", &opts).unwrap()["id"].as_u64().unwrap();
src.execute("select.set", &json!({"ids": [inst]})).unwrap();
src.execute("graph.design", &json!({"new": "Corner Mark"})).unwrap();
let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc);
let mut s = Session::new();
let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Corners.vectorcraft"});
let lib = s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
s.execute("graph.design", &json!({"library": lib, "add": "Corner Mark"})).unwrap();
let (from, to) = (&src.doc().unwrap().doc, &s.doc().unwrap().doc);
assert!(from.symbol_nine_slice("Corner").is_some());
assert_eq!(to.symbol_nine_slice("Corner"), from.symbol_nine_slice("Corner"));
assert_eq!(to.symbol_registration("Corner"), from.symbol_registration("Corner"));
assert_eq!(to.symbol_export_type("Corner"), from.symbol_export_type("Corner"));
}
#[test]
fn designs_and_markers_survive_save_and_open() {
let mut s = Session::new();
+2 -2
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Overprint",
[],
None,
"{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too). Without item and ids, the Appearance panel's active item stands in when it is of that kind → {changed: objects}",
"{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too). Without item and ids, the Appearance panel's active item stands in when it is of that kind. A whole Live Paint group (also its contents with `item`) takes the fill flags on its faces and the stroke flags on its edges, and its hidden source paths keep theirs → {changed: objects}",
has_doc,
set_overprint
),
@@ -135,7 +135,7 @@ fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator<Item = bool>
.into_iter()
.map(|fill| {
let it = item.of_kind(s, fill);
let ids = it.targets(s, p)?;
let ids = it.targets_for(s, p, fill)?;
let ids = if edit { super::appearance::drop_design_art_rows(s, ids, it, fill, cmd)? } else { ids };
Ok((fill, it, ids))
})
+39 -14
View File
@@ -216,12 +216,15 @@ impl Session {
}
let first = st.doc.node(*st.selection.subjects().first()?)?;
let item = self.appearance_item();
// Only an active Appearance row is shown here: it is a row of the first selected object.
if first.appearance.item_of_kind(item, !stroke).is_some() {
return Some((Cow::Borrowed(first), item));
}
// A Live Paint group without faces (or edges) shows the next selected object's paint; any other
// object without a painted object shows the defaults for new art.
for id in st.selection.subjects() {
// object without a painted object shows the defaults for new art. A face or edge selected with
// its Live Paint group counts with the group, wherever it is in the selection.
let covered = live_paint_covered(&st.doc, st.selection.subjects());
for id in st.selection.subjects().iter().filter(|id| !covered.contains(*id)) {
let Some(n) = st.doc.node(*id) else { continue };
let mut nodes = vec![];
painted(n, true, stroke, &mut nodes);
@@ -273,14 +276,6 @@ fn same_in_proxy(a: &Paint, b: &Paint) -> bool {
}
}
/// The ids of the faces and edges of `n` when it is a Live Paint group, else none.
pub(crate) fn live_paint_parts(n: &Node) -> Vec<NodeId> {
if !is_live_paint(n) {
return vec![];
}
faces(n).into_iter().chain(edges(n)).map(|part| part.id).collect()
}
/// The objects whose paints the proxies show for a selected `n`, the ones the paint commands
/// change ([`leaf_targets`]): groups and layers stand for their contents (and so do blends and
/// other containers inside them), a compound path for its parts. A Live Paint group stands for its
@@ -331,8 +326,9 @@ impl DocState {
// Looking the first object up builds the id cache when there is none.
let first = self.selection.objects.first().and_then(|id| self.doc.node(*id));
let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
// The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
let mut covered = std::collections::HashSet::new();
// The faces and edges of the selected Live Paint groups (or of those inside selected groups): selected as well,
// they count with their group's.
let covered = live_paint_covered(&self.doc, &self.selection.objects);
// Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each
// place it appears.
for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) {
@@ -342,7 +338,6 @@ impl DocState {
if covered.contains(&n.id) {
continue;
}
covered.extend(live_paint_parts(n));
painted(n, true, false, &mut fills);
painted(n, true, true, &mut strokes);
}
@@ -839,6 +834,36 @@ pub(crate) fn live_paint_parts_skipped(d: &Document, roots: &[NodeId], fill: boo
out
}
/// Faces, edges and the other objects (the hidden source paths) of Live Paint groups.
pub(crate) type LivePaintParts = (std::collections::HashSet<NodeId>, std::collections::HashSet<NodeId>, std::collections::HashSet<NodeId>);
/// The faces, the edges and the hidden source paths of the Live Paint groups in `roots` (or inside them),
/// found as [`live_paint_parts_skipped`] finds them.
pub(crate) fn live_paint_split(d: &Document, roots: &[NodeId]) -> LivePaintParts {
let groups = live_paint_groups(d, roots);
let mut hidden = inside_live_paint(d, &groups);
let (mut faces, mut edges) = (std::collections::HashSet::new(), std::collections::HashSet::new());
for (_, f, e) in &groups {
faces.extend(f.iter().copied());
edges.extend(e.iter().copied());
}
hidden.retain(|id| !faces.contains(id) && !edges.contains(id));
(faces, edges, hidden)
}
/// The faces and edges in `selected` whose Live Paint group is selected too, itself or inside another selected
/// object: they count with their group, wherever they are in `selected`. The groups are looked for only when an
/// object in `selected` is inside a Live Paint group.
pub(crate) fn live_paint_covered(d: &Document, selected: &[NodeId]) -> std::collections::HashSet<NodeId> {
let inside = |id: &NodeId| d.ancestry(*id).is_some_and(|up| up.iter().rev().skip(1).filter_map(|a| d.node(*a)).any(is_live_paint));
if !selected.iter().any(inside) {
return std::collections::HashSet::new();
}
let (mut parts, edges, _) = live_paint_split(d, selected);
parts.extend(edges);
parts
}
/// The instance whose object is selected with Direct Selection, and that object's path
/// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands
/// then change that object. A bad `target` or `aligned` is refused as it is for any other selection.
@@ -1356,7 +1381,7 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(
let item = item_target(s, p, cmd)?.of_kind(s, !stroke);
// Read before the check below, so that a bad param (such as `target` or `aligned`, or an explicit `item` the art has
// no row for) is still an error.
let targets = super::appearance::drop_design_art_rows(s, item.targets(s, p)?, item, !stroke, cmd)?;
let targets = super::appearance::drop_design_art_rows(s, item.targets_for(s, p, !stroke)?, item, !stroke, cmd)?;
let of = match item {
ItemTarget::Item { .. } => super::appearance::reference_of(s, p, item, cmd)?,
ItemTarget::Top => None,
+2 -3
View File
@@ -11,7 +11,7 @@ use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind};
use vectorcraft_geom::{Rect, shapes};
use super::{live_paint_parts, painted, picked_colors, proxy_paint, same_in_proxy};
use super::{live_paint_covered, painted, picked_colors, proxy_paint, same_in_proxy};
use crate::{DocState, Session};
thread_local! {
@@ -39,12 +39,11 @@ fn walked(st: &DocState, item: Option<usize>, points: &[(NodeId, Vec<usize>)]) -
}
let ids: HashSet<NodeId> = st.selection.objects.iter().copied().collect();
let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
let mut covered = HashSet::new();
let covered = live_paint_covered(&st.doc, &st.selection.objects);
st.doc.walk(|n| {
if ids.contains(&n.id) {
selected.push(n);
if !covered.contains(&n.id) {
covered.extend(live_paint_parts(n));
painted(n, true, false, &mut fills);
painted(n, true, true, &mut strokes);
}
@@ -153,6 +153,7 @@ pub(super) const ALLOWED: &[&str] = &[
"color.gamutCheck",
"color.harmony",
"color.plates",
"color.used",
"dataset.capture",
"dataset.delete",
"dataset.list",
@@ -573,6 +574,7 @@ pub(super) const ALLOWED: &[&str] = &[
"shape.spiral",
"shape.star",
"shape.threePointArc",
"shapeBuilder.copyRegion",
"shapeBuilder.merge",
"shapeBuilder.regions",
"shaper.expand",
+96 -33
View File
@@ -29,6 +29,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
colors
),
cmd!(
query "color.used",
"Document Colors",
[],
None,
"{selection?: true (false: the objects select.all takes, also while something is selected), limit?: n (only the n most used; default all)} → {colors: [{key, hex, color: the color in its own model ({model, …}), count, swatch?: the global swatch it is linked to (from its first linked use in paint order, a plain use before a gradient stop that mixes the swatch's ink with process inks; left out when only such stops link it), tint?: 0..100 to three decimals (the percent of that swatch's color the same use stores)}] as recolor.colors lists them, selection: true when they are the selection's, uses: the uses of every color, those past limit included} the unique colors of the selection, or with nothing selected or selection false of the objects select.all takes without the hidden and locked objects inside them, most used first; the selection is left as it is",
has_doc,
used
),
cmd!(
"recolor.apply",
"Recolor Artwork",
@@ -952,16 +961,19 @@ fn pick_theme(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"colors": colors.iter().map(key_str).collect::<Vec<_>>(), "objects": theme.objects}))
}
/// A colour the art uses: how often, and the global swatch it is linked to.
/// A color the art uses: how often, and the global swatch of its first linked use in paint order.
struct Used {
color: Color,
count: usize,
swatch: Option<String>,
/// The global swatch of the first linked use that is not a gradient stop mixing the swatch's
/// ink with process inks, with the tint (0..1) its paint stores when the paint gives one.
plain: Option<(String, Option<f32>)>,
}
/// The unique colours of the objects `ids` and the objects inside them, most used first (ties by
/// key): fills, strokes, gradient stops, text, mesh points and the tiles of the patterns used as
/// fills or strokes. With `only`, an object not in it is left out with everything it holds.
/// key): fills, strokes, gradient stops, text, mesh points, the tiles of the patterns used as
/// fills or strokes, and the tiles of the patterns those tiles use. With `only`, an object not in it is left out with everything it holds.
fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) -> Vec<Used> {
fn read<'a>(n: &'a Node, only: Option<&BTreeSet<NodeId>>, out: &mut Vec<&'a Node>) {
if only.is_some_and(|o| !o.contains(&n.id)) {
@@ -974,44 +986,64 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet<NodeId>>) ->
}
let mut index: HashMap<ColorKey, usize> = HashMap::new();
let mut used: Vec<(ColorKey, Used)> = vec![];
let mut count = |c: &Color, link: Option<&str>| {
let mut count_tint = |c: &Color, link: Option<&str>, tint: Option<f32>, mixed: bool| {
let k = ColorKey::of(c);
let i = *index.entry(k).or_insert_with(|| {
used.push((k, Used { color: *c, count: 0, swatch: None }));
used.push((k, Used { color: *c, count: 0, swatch: None, plain: None }));
used.len() - 1
});
let u = &mut used[i].1;
u.count += 1;
if u.swatch.is_none() {
u.swatch = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())).map(str::to_string);
if u.swatch.is_some() && (u.plain.is_some() || mixed) {
return;
}
if let Some(l) = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())) {
if u.swatch.is_none() {
u.swatch = Some(l.to_string());
}
if u.plain.is_none() && !mixed {
u.plain = Some((l.to_string(), tint));
}
}
};
// The patterns used as fills or strokes: their tiles count once each.
// The patterns used as fills or strokes, and the patterns their tiles use: each tile counts
// once, and a pattern whose tile uses itself, directly or through other patterns, counts once.
let mut patterns: Vec<&str> = vec![];
let mut nodes = vec![];
for n in ids.iter().filter_map(|id| d.node(*id)) {
read(n, only, &mut nodes);
}
for m in nodes {
for p in node_paints(m).chain(override_paints(m)) {
match p {
Paint::Solid { color, swatch, .. } => count(color, swatch.as_deref()),
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref())),
Paint::Pattern { pattern, .. } if !patterns.contains(&pattern.as_str()) => patterns.push(pattern),
_ => {}
}
}
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| count(&p.color, None));
}
paints(m, &mut count_tint, &mut patterns);
}
for def in patterns.iter().filter_map(|p| d.pattern(p)) {
def.art.iter().for_each(|n| node_colors(n, &mut count));
let mut next = 0;
while let Some(&name) = patterns.get(next) {
next += 1;
for a in d.pattern(name).map(|def| def.art.as_slice()).unwrap_or_default() {
a.walk(&mut |m| paints(m, &mut count_tint, &mut patterns));
}
}
used.sort_by(|a, b| b.1.count.cmp(&a.1.count).then(a.0.cmp(&b.0)));
used.into_iter().map(|(_, u)| u).collect()
}
/// Count the colors `m` holds itself with `count` (the color, its swatch, the tint the paint
/// stores, and whether it is a gradient stop that mixes the swatch's ink with process inks), and
/// add the patterns it is painted with to `patterns`.
fn paints<'a>(m: &'a Node, count: &mut impl FnMut(&Color, Option<&str>, Option<f32>, bool), patterns: &mut Vec<&'a str>) {
for p in node_paints(m).chain(override_paints(m)) {
match p {
Paint::Solid { color, swatch, tint } => count(color, swatch.as_deref(), Some(*tint), false),
Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref(), Some(s.tint), s.plates.is_some())),
Paint::Pattern { pattern, .. } if !patterns.contains(&pattern.as_str()) => patterns.push(pattern),
_ => {}
}
}
if let NodeKind::Mesh(mesh) = &m.kind {
mesh.points.iter().for_each(|p| count(&p.color, None, None, false));
}
}
/// The colors `n` shows, in paint order ([`node_colors`]), then the colors of the tiles of the
/// patterns it uses as fills or strokes, and of the patterns those tiles use (each pattern once).
fn shown_colors<'a>(d: &'a Document, n: &'a Node) -> Vec<Color> {
@@ -1054,30 +1086,61 @@ fn scope_ids(s: &Session, p: &Value, cmd: &str) -> Result<(Vec<NodeId>, Option<B
let st = s.doc()?;
let ids = match p.get("ids") {
Some(_) => checked_ids_param(s, p, "ids", cmd)?,
None if st.selection.is_empty() => {
let only = super::select::selectable_ids(&st.doc, st.isolation);
return Ok((super::select::selectable(&st.doc, st.isolation), Some(only)));
}
None if st.selection.is_empty() => return Ok(all_art(st)),
None => st.selection.objects.clone(),
};
let mut seen = BTreeSet::new();
Ok((super::edit::outermost(&st.doc, ids).into_iter().filter(|id| seen.insert(*id)).collect(), None))
}
fn colors(s: &mut Session, p: &Value) -> Result<Value> {
let (ids, only) = scope_ids(s, p, "recolor.colors")?;
let st = s.doc()?;
let v: Vec<Value> = used_colors(&st.doc, &ids, only.as_ref())
.iter()
/// The objects Select All takes, and the objects whose colors count ([`scope_ids`] with nothing
/// selected).
fn all_art(st: &crate::DocState) -> (Vec<NodeId>, Option<BTreeSet<NodeId>>) {
let only = super::select::selectable_ids(&st.doc, st.isolation);
(super::select::selectable(&st.doc, st.isolation), Some(only))
}
/// The `colors` list of `recolor.colors` and `color.used` for the objects `ids` (see
/// [`used_colors`]). Each names the swatch of its first linked use. With `with_color`, each has its
/// color in its own model, and the swatch and tint come from its first linked use that is not a
/// gradient stop mixing the swatch's ink with process inks (none when every linked use is one).
fn colors_json(used: &[Used], with_color: bool) -> Vec<Value> {
used.iter()
.map(|u| {
let mut v = json!({"key": key_str(&u.color), "hex": u.color.to_hex(), "count": u.count});
if let Some(w) = &u.swatch {
if with_color {
v["color"] = json!(u.color);
if let Some((w, tint)) = &u.plain {
v["swatch"] = json!(w);
if let Some(t) = tint {
v["tint"] = json!((f64::from(*t) * 100_000.0).round() / 1000.0);
}
}
} else if let Some(w) = &u.swatch {
v["swatch"] = json!(w);
}
v
})
.collect();
Ok(json!({ "colors": v }))
.collect()
}
fn colors(s: &mut Session, p: &Value) -> Result<Value> {
let (ids, only) = scope_ids(s, p, "recolor.colors")?;
let st = s.doc()?;
Ok(json!({ "colors": colors_json(&used_colors(&st.doc, &ids, only.as_ref()), false) }))
}
/// `color.used {selection?, limit?}`: the colors of the selection, or of the art Select All takes.
fn used(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "color.used";
let limit = super::index_opt(p, "limit", C)?.unwrap_or(usize::MAX);
let selection = switch_or(p, "selection", true, C)? && !s.doc()?.selection.is_empty();
let (ids, only) = if selection { scope_ids(s, &json!({}), C)? } else { all_art(s.doc()?) };
let st = s.doc()?;
let used = used_colors(&st.doc, &ids, only.as_ref());
let uses: usize = used.iter().map(|u| u.count).sum();
let shown = used.get(..limit.min(used.len())).unwrap_or_default();
Ok(json!({ "colors": colors_json(shown, true), "selection": selection, "uses": uses }))
}
/// `recolor.weigh`'s rows as given, each with `from` as a list (a `{current: new}` map gives a
+1 -1
View File
@@ -559,7 +559,7 @@ impl Line {
continue;
}
if t < 0.0 && !paints_as_one(&self) {
return self;
continue;
}
let mut tracked = self.clone();
tracked.tracking = t;
+25
View File
@@ -1927,6 +1927,31 @@ fn tracking_near_a_whole_number_is_kept_as_measured_when_rounding_moves_glyphs()
assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap()));
}
#[test]
fn a_tracking_translucent_glyphs_cannot_take_keeps_the_tracking_that_fits() {
// The first three glyphs are tracked 50 and the last 150 further on. A tracking tighter than
// zero is not tried for glyphs that cannot be one object, and the tracked prefix is kept.
let mut s = session();
let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMM", "size": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 2, "tracking": 50})).unwrap();
s.execute("text.setRangeStyle", &json!({"id": id, "start": 2, "end": 3, "tracking": 150})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap();
let kids = children_of(&s, g);
s.edit("test", |d, _| {
for k in &kids {
d.node_mut(NodeId(*k)).unwrap().opacity = 0.5;
}
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g]})).unwrap();
let r = s.execute("type.retype", &json!({})).unwrap();
let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect();
assert_eq!(texts.concat(), "MMMM", "{r}");
assert!(texts.iter().any(|t| t.len() > 1), "the tracked glyphs stay one object: {r}");
}
#[test]
fn overlapping_translucent_glyphs_are_not_tracked_into_one_object() {
let mut s = session();
+14 -6
View File
@@ -11,7 +11,7 @@ use vectorcraft_geom::PathData;
use vectorcraft_tools::builder::is_live_paint;
use super::appearance::{ItemTarget, edit_items, item_target};
use super::paint::{live_paint_parts, live_paint_parts_skipped, painted};
use super::paint::{live_paint_covered, live_paint_parts_skipped, painted};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ok, str_param};
use crate::DocState;
use crate::inspect::{ALIGNS, CAPS, JOINS, StrokeMixed, node_stroke, scale_layer};
@@ -250,10 +250,15 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
} else if item == ItemTarget::Top {
own_stroke_or_leaves(s, p)?
} else {
item.targets(s, p)?
item.targets_for(s, p, false)?
};
// A Live Paint group without edges was still selected or given: the options do not go to new art.
let live_paint = !bucket && item == ItemTarget::Top && !live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, false).is_empty();
let live_paint = !bucket
&& if item == ItemTarget::Top {
!live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, false).is_empty()
} else {
!super::appearance::contents_skipped(s, p, false)?.is_empty()
};
let new_art = bucket || (no_targets(&ids, p) && !live_paint);
let given = !ids.is_empty() || live_paint;
// The art of a graph design in a series keeps the design's stroke.
@@ -453,12 +458,15 @@ impl Session {
}
let Some(first) = st.selection.objects.first() else { return Some(self.new_art_stroke()) };
let first = st.doc.node(*first)?;
// Only an active Appearance row is shown here: it is a row of the first selected object.
if let Some(i) = first.appearance.item_of_kind(self.appearance_item(), false) {
return first.appearance.stroke_at(Some(i)).cloned();
}
// A Live Paint group without edges shows the next selected object's stroke; any other object
// without a painted object shows none.
for id in &st.selection.objects {
// without a painted object shows none. A face or edge selected with its Live Paint group counts
// with the group, wherever it is in the selection.
let covered = live_paint_covered(&st.doc, &st.selection.objects);
for id in st.selection.objects.iter().filter(|id| !covered.contains(*id)) {
let Some(n) = st.doc.node(*id) else { continue };
let mut nodes = vec![];
painted(n, true, true, &mut nodes);
@@ -532,7 +540,7 @@ impl DocState {
} else {
let selected: Vec<&Node> = self.selection.objects.iter().filter_map(|id| self.doc.node(*id)).collect();
// The faces and edges of the selected Live Paint groups: selected as well, they count with their group's.
let covered: std::collections::HashSet<vectorcraft_doc::NodeId> = selected.iter().flat_map(|n| live_paint_parts(n)).collect();
let covered = live_paint_covered(&self.doc, &self.selection.objects);
for n in selected.into_iter().filter(|n| !covered.contains(&n.id)) {
painted(n, true, true, &mut nodes);
}
+104 -8
View File
@@ -17,7 +17,7 @@ use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_color::{Paint, Swatch, SwatchGroup, SwatchLibrary, default_swatches};
use vectorcraft_doc::pattern::pattern_paint;
use super::fileio::{create_dir, extension, read_file, write_file, write_new_file};
use super::fileio::{create_dir, extension, read_file, read_file_head, write_file, write_new_file};
use super::menucmds::squash;
use super::package::free_name;
use super::patternlib;
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Other Library…",
["Window", "Swatch Libraries"],
None,
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and color groups; swatch.library.add brings a pattern swatch's pattern with it. A document with no swatches is an error, and so is a .ai, .eps or PostScript file whose swatches are only the default ones (it has no palette of its own) → {library: id, name, count}",
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and color groups; swatch.library.add brings a pattern swatch's pattern with it. A document's graph designs are offered by Object › Graph › Column… and Marker… (graph.column, graph.marker and graph.design take the library's id) until the app quits. A document with no swatches is an error, and so is a .ai, .eps or PostScript file whose swatches are only the default ones (it has no palette of its own), unless it has graph designs, which then load with no swatches. A file larger than 256 MB is refused before it is read → {library: id, name, count, graphDesigns: the document's graph designs (0 for a library file)}",
always,
load
),
@@ -92,6 +92,45 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// The graph designs of the documents Other Library… loaded (`swatch.library.load`), which the
/// Graph Column and Graph Marker dialogs offer besides the document's own; not saved.
#[derive(Clone, Debug, Default)]
pub struct DesignLibraries {
libs: Vec<DesignLibrary>,
}
/// A document loaded as a swatch library that holds graph designs ([`DesignLibraries`]).
#[derive(Clone, Debug)]
pub struct DesignLibrary {
/// The id `swatch.library.load` gave the swatch library. A User Defined copy of it
/// (`swatch.library.copyToUser`) holds the swatches alone, so the designs stay under this id.
pub id: String,
pub name: String,
/// The designs and the resources their art uses.
pub doc: Arc<vectorcraft_doc::Document>,
}
impl DesignLibraries {
/// The libraries, in the order they were loaded.
pub fn iter(&self) -> impl Iterator<Item = &DesignLibrary> {
self.libs.iter()
}
/// The library loaded as swatch library `id`.
pub fn get(&self, id: &str) -> Option<&DesignLibrary> {
self.libs.iter().find(|l| l.id == id)
}
/// Keep `doc`'s graph designs as library `id` named `name`, in place of the ones loaded as `id`
/// before; with no designs, `id` no longer has any.
fn set(&mut self, id: &str, name: &str, doc: Option<vectorcraft_doc::Document>) {
self.libs.retain(|l| l.id != id);
if let Some(doc) = doc {
self.libs.push(DesignLibrary { id: id.to_string(), name: name.to_string(), doc: Arc::new(doc) });
}
}
}
/// The libraries beyond the built-in ones: User Defined (the library files in the user library
/// folder, as last scanned) and loaded ones (`swatch.library.load`). Graphic style libraries use
/// the same with [`vectorcraft_doc::StyleLibrary`] ([`super::stylelib`]).
@@ -354,12 +393,32 @@ impl<L: LibraryFile> Libraries<L> {
/// or a file with the same extension and bytes as one there, is that User Defined library;
/// others are listed as loaded until the app quits.
pub(crate) fn load(&mut self, p: &Value, cmd: &str, parse: impl FnOnce(&[u8], &str) -> Result<L>) -> Result<(LibraryInfo, Arc<L>)> {
self.load_within(p, cmd, None, parse)
}
/// [`Self::load`], with a file at `path` read up to `max` bytes and refused when it is longer.
pub(crate) fn load_within(
&mut self,
p: &Value,
cmd: &str,
max: Option<usize>,
parse: impl FnOnce(&[u8], &str) -> Result<L>,
) -> Result<(LibraryInfo, Arc<L>)> {
let path = text_param(p, "path", cmd)?;
let data = text_param(p, "data", cmd)?;
let data_base64 = text_param(p, "dataBase64", cmd)?;
let name = text_param(p, "name", cmd)?;
let bytes = match (path, data, data_base64) {
(Some(path), ..) => read_file(path)?,
(Some(path), ..) => match max {
Some(max) => {
let bytes = read_file_head(path, max.saturating_add(1))?;
if bytes.len() > max {
return Err(bad(cmd, too_big_message(max)));
}
bytes
}
None => read_file(path)?,
},
(None, Some(text), _) => text.as_bytes().to_vec(),
(None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(cmd, "bad dataBase64"))?,
_ => return Err(bad(cmd, "give `path`, `data` or `dataBase64`")),
@@ -777,12 +836,40 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// The error for a library file larger than `max` bytes.
fn too_big_message(max: usize) -> String {
format!("the file is larger than {} MB", max >> 20)
}
/// Whether the library `p` gives (`path`, `data` or `dataBase64`) is larger than `max` bytes,
/// checked before the file is read, copied or decoded.
pub(crate) fn library_too_big(p: &Value, cmd: &str, max: usize) -> Result<bool> {
Ok(match text_param(p, "path", cmd)? {
Some(path) => super::fileio::file_stamp(path).is_some_and(|(len, _)| len > max as u64),
None => match text_param(p, "data", cmd)? {
Some(text) => text.len() > max,
// Base64 holds 3 bytes in every 4 characters (padding and white space hold none).
None => {
text_param(p, "dataBase64", cmd)?.is_some_and(|b| b.bytes().filter(|c| *c != b'=' && !c.is_ascii_whitespace()).count() * 3 / 4 > max)
}
},
})
}
fn load(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "swatch.library.load";
let max = super::place::document::MAX_FILE;
if library_too_big(p, C, max)? {
return Err(bad(C, too_big_message(max)));
}
let mut designs = None;
// The document a library with pattern swatches was read from, which holds their patterns.
let mut patterns = None;
let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| {
// A library file, or a document whose swatches become the library.
// The file is read no further than the limit, so a file that grew since it was checked is
// refused too.
let (info, lib) = s.swatch_libraries.load_within(p, C, Some(max), |bytes, file| {
// A library file, or a document whose swatches become the library and whose graph
// designs the Graph Column and Graph Marker dialogs offer.
if palette_io::sniff_bytes(bytes) {
return palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e));
}
@@ -792,10 +879,17 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
}
// A `.ai`, EPS or PostScript file without a palette of its own opens with the default swatches.
let defaults = matches!(loaded.format.id, "ai" | "ait" | "eps" | "ps") && has_only_default_swatches(&loaded.doc);
let lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?;
let mut lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?;
let doc_designs = super::clipboard::resources::graph_design_library(&loaded.doc);
if defaults || lib.is_empty() {
return Err(bad(C, format!("`{file}` has no swatches of its own")));
// A document with graph designs loads for them, with no swatches.
if doc_designs.is_none() {
return Err(bad(C, format!("`{file}` has no swatches of its own")));
}
lib.swatches.clear();
lib.groups.clear();
}
designs = doc_designs;
if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) {
patterns = Some(Arc::new(loaded.doc));
}
@@ -804,7 +898,9 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
if info.category == "loaded" {
s.swatch_libraries.set_pattern_doc(&info.id, patterns);
}
Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()}))
let count = designs.as_ref().map_or(0, |d| d.graph_designs.len());
s.graph_design_libraries.set(&info.id, &info.name, designs);
Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len(), "graphDesigns": count}))
}
/// `d`'s swatches and color groups are exactly the default ones of a color mode, as a new
+13
View File
@@ -424,6 +424,19 @@ fn each_changed_instance(n: &mut Node, name: &str, f: &mut dyn FnMut(&mut Vec<Sy
}
}
/// Each instance's appearance changes to objects of symbol `name`'s art follow those objects after
/// its art changed from `old` outside symbol editing (a graph in it drawn again): a change to an
/// object that is no longer there is dropped ([`follow_objects`]).
pub(crate) fn follow_art_change(d: &mut Document, name: &str, old: &Arc<Node>) {
let Some(new) = d.symbols.iter().find(|s| s.name == name).map(|s| s.art.clone()) else { return };
let parts = |art: &Arc<Node>| match (&art.kind, art.children()) {
(NodeKind::Group { .. }, Some(ch)) => (ch.to_vec(), true),
_ => (vec![art.clone()], false),
};
let (old, new) = (parts(old), parts(&new));
follow_objects(d, name, (&old.0, old.1), (&new.0, new.1));
}
/// Each instance's appearance changes to objects of symbol `name`'s art follow those objects
/// through an edit of the editing layer (see [`follow_paths`]), and keep only the changes the art
/// still draws ([`fit_parts`]). That covers the instances on the layers and in the art of the
+86
View File
@@ -170,6 +170,7 @@ pub const BUILTIN: &[BuiltinSymbolLibrary] = &[
BuiltinSymbolLibrary { id: "inventory-icons", name: "Inventory Icons", make: inventory_icons },
BuiltinSymbolLibrary { id: "skill-icons", name: "Skill Icons", make: skill_icons },
BuiltinSymbolLibrary { id: "weather-icons", name: "Weather Icons", make: weather_icons },
BuiltinSymbolLibrary { id: "nature-icons", name: "Nature Icons", make: nature_icons },
BuiltinSymbolLibrary { id: "media-controls", name: "Media Controls", make: media_controls },
];
@@ -503,6 +504,91 @@ fn weather_icons() -> SymbolLibrary {
SymbolLibrary { name: "Weather Icons".into(), doc }
}
/// Nature Icons: five original silhouettes for diagrams and reusable artwork.
fn nature_icons() -> SymbolLibrary {
let poly = |coords: &[(f64, f64)]| {
let points: Vec<Point> = coords.iter().map(|&(x, y)| Point::new(x, y)).collect();
SubPath::polyline(&points, true)
};
let leaf = PathData::new(vec![
poly(&[(0.0, -20.0), (12.0, -13.0), (17.0, -2.0), (12.0, 10.0), (0.0, 19.0), (-12.0, 10.0), (-17.0, -2.0), (-12.0, -13.0)]),
poly(&[(-1.0, -13.0), (1.0, -13.0), (1.0, 20.0), (-1.0, 20.0)]),
]);
let mut flower_parts = shapes::ellipse(Rect::new(-6.0, -6.0, 6.0, 6.0)).subpaths;
for i in 0..6 {
let angle = i as f64 * std::f64::consts::PI / 3.0;
let (sin, cos) = angle.sin_cos();
let x = 12.0 * cos;
let y = 12.0 * sin;
flower_parts.extend(shapes::ellipse(Rect::new(x - 5.5, y - 5.5, x + 5.5, y + 5.5)).subpaths);
}
let flower = PathData::new(flower_parts);
let tree = PathData::new(vec![
poly(&[(-3.0, 6.0), (3.0, 6.0), (3.0, 20.0), (-3.0, 20.0)]),
poly(&[
(0.0, -21.0),
(12.0, -8.0),
(8.0, -8.0),
(17.0, 4.0),
(11.0, 4.0),
(18.0, 12.0),
(-18.0, 12.0),
(-11.0, 4.0),
(-17.0, 4.0),
(-8.0, -8.0),
(-12.0, -8.0),
]),
]);
let mountain = PathData::new(vec![
poly(&[(-21.0, 17.0), (-6.0, -17.0), (2.0, 0.0), (8.0, -11.0), (21.0, 17.0)]),
poly(&[(-12.0, -4.0), (-6.0, -17.0), (0.0, -4.0), (-5.0, -7.0), (-8.0, -3.0)]),
]);
let wave = PathData::new(
(0..3)
.map(|row| {
let y = row as f64 * 9.0 - 10.0;
poly(&[
(-20.0, y),
(-14.0, y - 4.0),
(-8.0, y - 4.0),
(-2.0, y),
(4.0, y + 4.0),
(10.0, y + 4.0),
(16.0, y),
(20.0, y),
(20.0, y + 3.0),
(16.0, y + 3.0),
(10.0, y + 7.0),
(4.0, y + 7.0),
(-2.0, y + 3.0),
(-8.0, y - 1.0),
(-14.0, y - 1.0),
(-20.0, y + 3.0),
])
})
.collect(),
);
let icons = [
("Leaf", leaf, "#4f9d59"),
("Flower", flower, "#d977a7"),
("Tree", tree, "#287c53"),
("Mountain", mountain, "#768899"),
("Wave", wave, "#388fb8"),
];
let mut doc = Document::new(100.0, 100.0);
for (name, path, hex) in icons {
let fill = Color::from_hex(hex).unwrap_or(Color::BLACK);
let edge = fill.lerp(&Color::BLACK, 0.35);
let id = doc.alloc_id();
let art = Node::path(id, path, Appearance::basic(Paint::solid(fill), Paint::solid(edge), 1.25));
let Ok((art, size, _)) = normalize(art) else { continue };
doc.symbols.push(Symbol { dynamic: false, name: name.into(), art: Arc::new(art) });
set_natural_size(&mut doc, name, Some(size));
}
doc.title = "Nature Icons".into();
SymbolLibrary { name: "Nature Icons".into(), doc }
}
/// Media Controls: play, pause, stop, skip next, shuffle and repeat for audio/video UI art (original, no 9-slice).
fn media_controls() -> SymbolLibrary {
// 1. Play: Right-pointing equilateral triangle.
+3
View File
@@ -356,6 +356,7 @@ pub struct FillAttrs {
impl FillAttrs {
pub const ALL: Self = Self { color: true, transparency: true, overprint: true };
pub const NONE: Self = Self { color: false, transparency: false, overprint: false };
}
impl Default for FillAttrs {
@@ -383,6 +384,8 @@ pub struct StrokeAttrs {
impl StrokeAttrs {
pub const ALL: Self = Self { color: true, transparency: true, overprint: true, weight: true, cap: true, join: true, miter: true, dash: true };
pub const NONE: Self =
Self { color: false, transparency: false, overprint: false, weight: false, cap: false, join: false, miter: false, dash: false };
}
impl Default for StrokeAttrs {
+3
View File
@@ -153,6 +153,9 @@ pub struct Session {
pub(crate) pending_paint: Option<Paint>,
/// User Defined and loaded swatch libraries (Window → Swatch Libraries); not saved.
pub swatch_libraries: cmd::swatchlib::Libraries,
/// The graph designs of the documents loaded as swatch libraries (Window → Swatch Libraries →
/// Other Library…), for the Graph Column and Graph Marker dialogs; not saved.
pub graph_design_libraries: cmd::swatchlib::DesignLibraries,
/// The selected freeform gradient point (`paint.freeform.selectPoint`) and whose gradient it
/// was selected on: read it with [`Session::selected_freeform_point`].
pub(crate) freeform_point: Option<(usize, cmd::gradient::StopOwner)>,
+1
View File
@@ -85,6 +85,7 @@ impl Session {
recent_colors: vec![],
pending_paint: None,
swatch_libraries: Default::default(),
graph_design_libraries: Default::default(),
freeform_point: None,
style_libraries: Default::default(),
symbol_libraries: Default::default(),
+1
View File
@@ -67,6 +67,7 @@ mod expand_symbols;
mod eyedropper;
mod file;
mod fileinfo;
mod fill_area;
mod flatpresets;
mod flatpreview;
mod flatten;
+53
View File
@@ -115,6 +115,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() {
"paint",
"pattern-borders",
"decorative",
"ornamental",
"scatter-shapes",
"stipple",
"game-trails",
@@ -197,6 +198,7 @@ fn every_builtin_library_brush_has_its_kind_and_draws() {
("paint", "art"),
("pattern-borders", "pattern"),
("decorative", "pattern"),
("ornamental", "art"),
("scatter-shapes", "scatter"),
("stipple", "scatter"),
("game-trails", "art"),
@@ -661,6 +663,57 @@ fn decorative_brushes_repeat_distinct_art_and_survive_a_saved_library() {
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
#[test]
fn ornamental_brushes_draw_flourishes_and_survive_a_saved_library() {
let mut s = session();
let (_, lib) = cmd::brushlib::library(&s, "Ornamental").unwrap();
let names = ["Scrollwork", "Filigree Arrow", "Petal Sweep", "Twin Curl"];
assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::<Vec<_>>(), names);
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap();
let mut curve = line_to(20.0);
curve.curve_to((60.0, -25.0), (140.0, 25.0), (180.0, 0.0));
for b in &lib.brushes {
let BrushKind::Art(art) = &b.kind else { panic!("{} is not an art brush", b.name) };
assert_eq!(art.colorization, vectorcraft_brush::Colorization::Tints);
assert_eq!(art.width, 300.0);
for line in [line_to(2.0), line_to(180.0), curve.clone()] {
let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &black_stroke());
let points = anchors(&pieces.iter().collect::<Vec<_>>());
assert!(!points.is_empty() && points.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name);
}
let before = undo_len(&s);
let added = run(&mut s, "brush.addFromLibrary", json!({"library": "ornamental", "name": b.name, "apply": true, "ids": [path]}));
assert_eq!(strs(&added["added"]), [b.name.as_str()]);
assert_eq!(added["applied"], json!([path]));
assert_eq!(undo_len(&s), before + 1);
assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str()));
}
let saved = run(&mut s, "brush.saveLibrary", json!({"names": names}));
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let reopened = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes);
}
/// Filigree Arrow's shaft runs into its head with no gap, so a straight stroke draws one arrow.
#[test]
fn the_filigree_arrow_shaft_meets_its_head() {
let s = session();
let (_, lib) = cmd::brushlib::library(&s, "Ornamental").unwrap();
let BrushKind::Art(art) = &lib.brush("Filigree Arrow").unwrap().kind else { panic!("Filigree Arrow is not an art brush") };
let mut parts = vec![];
art.art.walk(&mut |c| {
if c.path_data().is_some() {
parts.push(c.contains_fn());
}
});
for y in [-0.6, 0.0, 0.6] {
for i in 0..=930 {
let p = vectorcraft_geom::Point::new(4.05 + 0.1 * f64::from(i), y);
assert!(parts.iter().any(|inside| inside(p)), "gap at {p:?}");
}
}
}
#[test]
fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library() {
let mut s = session();
+454
View File
@@ -4283,6 +4283,353 @@ fn live_paint_group_stroke_panel_edits_change_its_edges() {
assert_eq!(node(&s, g).appearance.stroke().map(|st| st.width), Some(1.0));
}
/// A face or edge selected before its Live Paint group counts with the group: the Fill proxy shows
/// the faces' fill and the Stroke panel the edges' stroke, whatever the order of the selection.
#[test]
fn live_paint_group_proxies_do_not_depend_on_the_selection_order() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap();
s.execute("stroke.set", &json!({"weight": 6})).unwrap();
let magenta = serde_json::to_value(Paint::solid(Color::from_hex("#ff00ff").unwrap())).unwrap();
let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id;
s.execute("select.set", &json!({"ids": [edge.0, g.0]})).unwrap();
assert_eq!(s.execute("paint.proxies", &json!({})).unwrap()["fill"], magenta, "an edge first shows the faces' fill");
// A face with a stroke of its own (from a file, say), selected first, shows the edges' stroke.
let face = vectorcraft_tools::builder::faces(&node(&s, g))[0].id;
s.edit("t", |d, _| {
let n = d.node_mut(face).unwrap();
n.appearance.set_stroke(Paint::solid(Color::BLACK));
n.appearance.stroke_at_mut(None).unwrap().width = 2.0;
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [face.0, g.0]})).unwrap();
assert_eq!(s.shown_stroke().map(|st| st.width), Some(6.0), "a face first shows the edges' stroke");
}
/// The Eyedropper onto a whole selected Live Paint group, or reversed onto a clicked one, gives the
/// picked fill attributes to its faces and the picked stroke attributes to its edges; its hidden
/// source paths keep their paint.
#[test]
fn live_paint_group_eyedropper_gives_the_fill_to_faces_and_the_stroke_to_edges() {
for reverse in [false, true] {
let mut s = session();
let g = live(&mut s);
let src = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
s.execute("paint.setFill", &json!({"ids": [src.0], "color": "#ff00ff"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [src.0], "color": "#0000ff"})).unwrap();
s.execute("stroke.set", &json!({"ids": [src.0], "weight": 3})).unwrap();
let (faces0, edges0) = part_looks(&s, g);
let sources0 = sources_looks(&s, g);
if reverse {
s.execute("select.set", &json!({"ids": [src.0]})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": g.0, "reverse": true})).unwrap();
} else {
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap();
}
let (faces1, edges1) = part_looks(&s, g);
let magenta = Paint::solid(Color::from_hex("#ff00ff").unwrap());
let blue = Paint::solid(Color::from_hex("#0000ff").unwrap());
for (f, f0) in faces1.iter().zip(&faces0) {
assert_eq!(f.fill_paint(), magenta, "reverse {reverse}: a face takes the fill");
assert_eq!((f.stroke_paint(), f.stroke_width()), (f0.stroke_paint(), f0.stroke_width()), "reverse {reverse}: a face takes no stroke");
}
for (e, e0) in edges1.iter().zip(&edges0) {
assert_eq!((e.stroke_paint(), e.stroke_width()), (blue.clone(), 3.0), "reverse {reverse}: an edge takes the stroke");
assert_eq!(e.fill_paint(), e0.fill_paint(), "reverse {reverse}: an edge takes no fill");
}
assert_eq!(sources_looks(&s, g), sources0, "reverse {reverse}: the hidden source paths keep their paint");
}
}
/// A whole-appearance Eyedropper pick of a source with several fills and strokes gives each face
/// of a selected Live Paint group every fill row and each edge every stroke row.
#[test]
fn live_paint_group_eyedropper_gives_every_fill_and_stroke_row() {
let mut s = session();
let g = live(&mut s);
let src = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
s.execute("paint.setFill", &json!({"ids": [src.0], "color": "#ff00ff"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [src.0], "color": "#0000ff"})).unwrap();
s.execute("appearance.addFill", &json!({"ids": [src.0]})).unwrap();
s.execute("appearance.addStroke", &json!({"ids": [src.0]})).unwrap();
let kinds = |a: &vectorcraft_doc::Appearance, fill: bool| a.items.iter().filter(|it| it.is_fill() == fill).count();
let source = (*node(&s, src).appearance).clone();
assert_eq!((kinds(&source, true), kinds(&source, false)), (2, 2));
// A face with a stroke row below its fill keeps that row below the picked fills.
let face = vectorcraft_tools::builder::faces(&node(&s, g))[0].id;
s.edit("t", |d, _| {
let n = d.node_mut(face).unwrap();
n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 9.0)));
Ok(())
})
.unwrap();
let (faces0, edges0) = part_looks(&s, g);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap();
let (faces1, edges1) = part_looks(&s, g);
let order: Vec<bool> = faces1[0].items.iter().map(|it| it.is_fill()).collect();
assert_eq!(order.first(), Some(&false), "the face's lower stroke row stays below its fills: {order:?}");
for (f, f0) in faces1.iter().zip(&faces0) {
assert_eq!(kinds(f, true), 2, "a face takes every fill row");
assert_eq!(kinds(f, false), kinds(f0, false), "a face keeps its strokes");
}
for (e, e0) in edges1.iter().zip(&edges0) {
assert_eq!(kinds(e, false), 2, "an edge takes every stroke row");
assert_eq!(kinds(e, true), kinds(e0, true), "an edge keeps its fills");
}
}
/// The Appearance panel's edits of a Live Paint group's contents (`target: "contents"`) follow the
/// group's rule: a new fill goes on its faces, a new stroke on its edges, and its hidden source paths
/// keep their appearance under every contents edit.
#[test]
fn live_paint_group_contents_edits_follow_the_group_rule() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let (faces0, edges0) = part_looks(&s, g);
let sources0 = sources_looks(&s, g);
s.execute("appearance.addFill", &json!({"target": "contents"})).unwrap();
let (faces1, edges1) = part_looks(&s, g);
assert!(faces1.iter().zip(&faces0).all(|(f, f0)| f.items.len() == f0.items.len() + 1), "every face takes a new fill");
assert_eq!(edges1, edges0, "edges take no new fill");
s.execute("appearance.addStroke", &json!({"target": "contents"})).unwrap();
let (faces2, edges2) = part_looks(&s, g);
assert_eq!(faces2, faces1, "faces take no new stroke");
assert!(edges2.iter().zip(&edges1).all(|(e, e0)| e.items.len() == e0.items.len() + 1), "every edge takes a new stroke");
// A stroke row edit of the contents reaches the edges, not the faces.
s.execute("stroke.set", &json!({"target": "contents", "item": 0, "weight": 7})).unwrap();
let (faces3, edges3) = part_looks(&s, g);
assert_eq!(faces3, faces2, "faces keep their rows");
assert!(edges3.iter().all(|e| e.stroke_at(Some(0)).map(|st| st.width) == Some(7.0)), "every edge's stroke row takes the weight");
s.execute("appearance.clear", &json!({"target": "contents"})).unwrap();
assert_eq!(sources_looks(&s, g), sources0, "the hidden source paths keep their appearance");
}
/// Fill edits of a Live Paint group's contents with an `item` (a gradient vector, Invert, Overprint
/// Fill) change its faces and leave an edge's fill row as it is, and Overprint on the whole group goes
/// to the faces' fills and the edges' strokes, leaving the hidden source paths as they are.
#[test]
fn live_paint_group_item_edits_and_overprint_follow_the_group_rule() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.setFill", &json!({"gradient": {}})).unwrap();
// Each edge gets a copy of a face's gradient fill row, below its stroke.
let n = node(&s, g);
let face_row = vectorcraft_tools::builder::faces(&n)[0].appearance.items[0].clone();
let edge_ids: Vec<NodeId> = vectorcraft_tools::builder::edges(&n).iter().map(|e| e.id).collect();
let mut face_ids: Vec<u64> = vectorcraft_tools::builder::faces(&n).iter().map(|f| f.id.0).collect();
face_ids.sort_unstable();
s.edit("t", |d, _| {
for e in &edge_ids {
d.node_mut(*e).unwrap().appearance.items.insert(0, face_row.clone());
}
Ok(())
})
.unwrap();
let (faces0, edges0) = part_looks(&s, g);
let sources0 = sources_looks(&s, g);
let r = s.execute("paint.setGradientGeom", &json!({"stroke": false, "item": 0, "target": "contents", "start": [0, 0], "end": [100, 0]})).unwrap();
let mut changed: Vec<u64> = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect();
changed.sort_unstable();
assert_eq!(changed, face_ids, "only the faces take the vector");
assert_eq!(part_looks(&s, g).1, edges0, "an edge's fill row keeps its vector");
let stops = |a: &vectorcraft_doc::Appearance| match a.fill_paint() {
Paint::Gradient(gr) => gr.gradient.stops.iter().map(|st| st.color).collect::<Vec<_>>(),
_ => vec![],
};
let before: Vec<_> = part_looks(&s, g).0.iter().map(stops).collect();
s.execute("paint.invert", &json!({"stroke": false, "item": 0, "target": "contents"})).unwrap();
for (f, b) in part_looks(&s, g).0.iter().zip(&before) {
assert_eq!(stops(f), b.iter().rev().copied().collect::<Vec<_>>(), "the black-to-white stops of a face's fill are inverted");
}
assert_ne!(part_looks(&s, g).0, faces0);
assert_eq!(part_looks(&s, g).1, edges0, "an edge's fill row is not inverted");
s.execute("object.setOverprint", &json!({"fill": true, "item": 0, "target": "contents"})).unwrap();
let (faces1, edges1) = part_looks(&s, g);
assert!(faces1.iter().all(|f| f.items[0].overprint()), "the faces' fill overprints");
assert_eq!(edges1, edges0, "an edge's fill row does not overprint");
s.execute("object.setOverprint", &json!({"fill": true, "stroke": true})).unwrap();
let (_, edges2) = part_looks(&s, g);
assert!(edges2.iter().all(|e| e.items.iter().all(|it| it.overprint() != it.is_fill())), "only the edges' strokes overprint");
assert_eq!(sources_looks(&s, g), sources0, "the hidden source paths keep their flags");
}
/// A face selected before an ordinary group that holds its Live Paint group counts with that group:
/// the Stroke panel shows the edges' stroke.
#[test]
fn live_paint_group_inside_a_selected_group_keeps_the_proxies_independent_of_order() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("stroke.set", &json!({"weight": 6})).unwrap();
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let face = vectorcraft_tools::builder::faces(&node(&s, g))[0].id;
s.edit("t", |d, _| {
let n = d.node_mut(face).unwrap();
n.appearance.set_stroke(Paint::solid(Color::BLACK));
n.appearance.stroke_at_mut(None).unwrap().width = 2.0;
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [face.0, outer.0]})).unwrap();
assert_eq!(s.shown_stroke().map(|st| st.width), Some(6.0), "a face first shows the edges' stroke");
assert!(!s.active().unwrap().stroke_mixed().weight, "the face's own stroke does not make the weight mixed");
// An unfilled edge selected with the outer group does not make the faces' fill mixed.
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id;
s.execute("select.set", &json!({"ids": [edge.0, outer.0]})).unwrap();
let r = s.execute("paint.proxies", &json!({})).unwrap();
assert_eq!(r["fill"], serde_json::to_value(Paint::solid(Color::from_hex("#ff0000").unwrap())).unwrap());
assert_eq!(r["fillMixed"], false, "the edge counts with its group");
}
/// The Eyedropper picks up a whole Live Paint group as its faces' fill under its edges' stroke, and
/// `append` onto a whole group adds the picked fills and strokes without the picked effects.
#[test]
fn live_paint_group_eyedropper_picks_up_the_group_and_appends_without_effects() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap();
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
s.execute("stroke.set", &json!({"weight": 5})).unwrap();
s.edit("t", |d, _| {
d.node_mut(g).unwrap().opacity = 0.5;
Ok(())
})
.unwrap();
let target = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": target.0, "reverse": true})).unwrap();
let a = (*node(&s, target).appearance).clone();
assert_eq!(a.fill_paint(), Paint::solid(Color::from_hex("#ff00ff").unwrap()), "the faces' fill");
assert_eq!((a.stroke_paint(), a.stroke_width()), (Paint::solid(Color::from_hex("#0000ff").unwrap()), 5.0), "the edges' stroke");
assert_eq!(node(&s, target).opacity, 0.5, "the group's own opacity");
// A Live Paint group with no face and no edge is not picked up: the next selected object is.
let empty = rect(&mut s, 600.0, 0.0, 50.0, 50.0);
s.execute("select.set", &json!({"ids": [empty.0]})).unwrap();
let e = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let en = node(&s, e);
let parts: Vec<NodeId> =
vectorcraft_tools::builder::faces(&en).iter().chain(vectorcraft_tools::builder::edges(&en).iter()).map(|p| p.id).collect();
assert!(!parts.is_empty());
s.edit("t", |d, _| {
d.node_mut(e).unwrap().children_mut().unwrap().retain(|c| !parts.contains(&c.id));
Ok(())
})
.unwrap();
assert!(vectorcraft_tools::builder::is_live_paint(&node(&s, e)));
let other = rect(&mut s, 700.0, 0.0, 50.0, 50.0);
s.execute("paint.setFill", &json!({"ids": [other.0], "color": "#00ff00"})).unwrap();
s.execute("select.set", &json!({"ids": [e.0, other.0]})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": target.0, "reverse": true})).unwrap();
assert_eq!(node(&s, target).appearance.fill_paint(), Paint::solid(Color::from_hex("#00ff00").unwrap()), "the next selected object's fill");
// Append a source with a drop shadow onto the whole group.
let src = rect(&mut s, 500.0, 0.0, 50.0, 50.0);
s.execute("select.set", &json!({"ids": [src.0]})).unwrap();
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "item": null})).unwrap();
assert!(!node(&s, src).appearance.effects.is_empty());
let (faces0, edges0) = part_looks(&s, g);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": src.0, "append": true})).unwrap();
let (faces1, edges1) = part_looks(&s, g);
for (p, p0) in faces1.iter().chain(&edges1).zip(faces0.iter().chain(&edges0)) {
assert_eq!(p.effects, p0.effects, "a face or edge takes no effect");
}
assert!(faces1.iter().zip(&faces0).all(|(f, f0)| f.items.len() > f0.items.len()), "every face takes the fill");
}
/// Reversed onto a clicked object, an empty Live Paint group first in the selection passes to the next
/// selected Live Paint group, whose faces' fill and edges' stroke are both picked up.
#[test]
fn live_paint_group_eyedropper_reversed_skips_an_empty_group_for_the_next_whole_group() {
let mut s = session();
let g = live(&mut s);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap();
s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap();
s.execute("stroke.set", &json!({"weight": 5})).unwrap();
let empty = rect(&mut s, 600.0, 0.0, 50.0, 50.0);
s.execute("select.set", &json!({"ids": [empty.0]})).unwrap();
let e = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap());
let en = node(&s, e);
let parts: Vec<NodeId> =
vectorcraft_tools::builder::faces(&en).iter().chain(vectorcraft_tools::builder::edges(&en).iter()).map(|p| p.id).collect();
s.edit("t", |d, _| {
d.node_mut(e).unwrap().children_mut().unwrap().retain(|c| !parts.contains(&c.id));
Ok(())
})
.unwrap();
let target = rect(&mut s, 400.0, 0.0, 50.0, 50.0);
s.execute("appearance.copyFrom", &json!({"source": target.0, "reverse": true, "ids": [e.0, g.0]})).unwrap();
let a = (*node(&s, target).appearance).clone();
assert_eq!(a.fill_paint(), Paint::solid(Color::from_hex("#ff00ff").unwrap()), "the faces' fill");
assert_eq!((a.stroke_paint(), a.stroke_width()), (Paint::solid(Color::from_hex("#0000ff").unwrap()), 5.0), "the edges' stroke");
}
/// An Eyedropper pick whose source is the selected Live Paint group leaves the group's own faces and
/// edges as they are.
#[test]
fn live_paint_group_eyedropper_does_not_target_its_own_source_group() {
let mut s = session();
let g = live(&mut s);
s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "color": "#ff0000"})).unwrap();
s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50], "color": "#00ff00"})).unwrap();
let before = part_looks(&s, g);
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
s.execute("appearance.copyFrom", &json!({"source": g.0})).unwrap();
assert_eq!(part_looks(&s, g), before);
}
/// A Live Paint group left with only its hidden source paths is still a selection: a stroke edit of its
/// contents changes nothing and leaves the settings for new art as they are.
#[test]
fn live_paint_group_with_only_source_paths_leaves_new_art_alone_for_a_contents_edit() {
let mut s = session();
let g = live(&mut s);
let n = node(&s, g);
let parts: Vec<NodeId> = vectorcraft_tools::builder::faces(&n).iter().chain(vectorcraft_tools::builder::edges(&n).iter()).map(|p| p.id).collect();
s.edit("t", |d, _| {
d.children_mut(Some(g)).unwrap().retain(|c| !parts.contains(&c.id));
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let (paint0, stroke0) = (s.paint.clone(), s.new_art_stroke());
s.execute("stroke.setAdvanced", &json!({"target": "contents", "item": 0, "arrowScale": [200, 150]})).unwrap();
assert_eq!((s.paint.clone(), s.new_art_stroke()), (paint0, stroke0), "new art keeps its stroke");
}
/// Adding a fill or a stroke to the contents of a Live Paint group left with only its hidden source paths
/// succeeds and changes nothing, while an empty selection is still refused.
#[test]
fn live_paint_group_with_only_source_paths_ignores_add_fill_and_add_stroke_of_its_contents() {
let mut s = session();
let g = live(&mut s);
let n = node(&s, g);
let parts: Vec<NodeId> = vectorcraft_tools::builder::faces(&n).iter().chain(vectorcraft_tools::builder::edges(&n).iter()).map(|p| p.id).collect();
s.edit("t", |d, _| {
d.children_mut(Some(g)).unwrap().retain(|c| !parts.contains(&c.id));
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [g.0]})).unwrap();
let before = node(&s, g);
for cmd in ["appearance.addFill", "appearance.addStroke"] {
s.execute(cmd, &json!({"target": "contents"})).unwrap();
assert_eq!(node(&s, g), before, "{cmd} changes nothing");
}
s.execute("select.none", &json!({})).unwrap();
assert!(s.execute("appearance.addFill", &json!({"target": "contents"})).is_err(), "no selection is still refused");
}
/// A selected Live Paint group with no part of the edited kind is still a selection: a stroke edit
/// of a group without edges, or a fill gradient edit of a group without faces, changes nothing and
/// leaves the settings for new art as they are.
@@ -4304,6 +4651,8 @@ fn live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone() {
s.execute("stroke.set", &json!({"weight": 4})).unwrap();
s.execute("stroke.weightUp", &json!({})).unwrap();
s.execute("stroke.setAdvanced", &json!({"arrowScale": [200, 150]})).unwrap();
// A stroke row edit of the group's contents finds no edge either.
s.execute("stroke.set", &json!({"target": "contents", "item": 0, "weight": 9})).unwrap();
assert_eq!((s.paint.clone(), s.new_art_stroke()), (paint0, stroke0), "new art keeps its stroke");
assert_eq!(part_looks(&s, g), looks);
@@ -9280,6 +9629,111 @@ fn image_trace_built_in_presets_cannot_be_saved_over_or_deleted() {
assert_eq!(six["params"], serde_json::to_value(vectorcraft_trace::preset("6 Colors").unwrap()).unwrap());
}
/// Saved tracing presets go out to a .vctracepresets file and come back with their names and
/// settings; a hand-written file in the documented layout imports too.
#[test]
fn image_trace_presets_export_and_import_round_trip() {
let mut s = session();
assert!(s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string().contains("no saved tracing presets"));
s.execute("imageTrace.presets.save", &json!({"name": "Poster", "preset": "6 Colors", "params": {"noise": 40, "ignoreWhite": true}})).unwrap();
s.execute("imageTrace.presets.save", &json!({"name": "Ink", "params": {"threshold": 90, "fills": false, "strokes": true}})).unwrap();
let e = s.execute("imageTrace.presets.export", &json!({"names": ["Default"]})).unwrap_err().to_string();
assert!(e.contains("only saved presets are exported"), "{e}");
assert!(s.execute("imageTrace.presets.export", &json!({"names": ["Nope"]})).is_err());
let all = s.execute("imageTrace.presets.export", &json!({})).unwrap();
assert_eq!(all["count"], 2);
let one = s.execute("imageTrace.presets.export", &json!({"names": ["poster", "Poster"]})).unwrap();
assert_eq!(one["count"], 1);
let file: Value = serde_json::from_str(all["data"].as_str().unwrap()).unwrap();
assert_eq!((file["format"].as_str(), file["version"].as_u64()), (Some("vctracepresets"), Some(1)));
let saved = s.prefs.trace_presets.clone();
// Into a session without them: the same names and settings, and a new revision the panel follows.
let mut t = session();
let before = t.trace_presets_revision();
let r = t.execute("imageTrace.presets.import", &json!({"data": all["data"]})).unwrap();
assert_eq!(r, json!({"imported": ["Poster", "Ink"], "replaced": [], "skipped": []}));
assert_eq!(t.prefs.trace_presets, saved);
assert_eq!(t.trace_presets_revision(), before + 2);
// A file written by hand in the documented layout: missing settings are Default's.
let hand = r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Hand", "params": {"mode": "grayscale", "colors": 12}}]}"#;
t.execute("imageTrace.presets.import", &json!({ "dataBase64": vectorcraft_format::base64_encode(hand.as_bytes()) })).unwrap();
let hand = t.trace_preset("hand").unwrap().params.clone();
assert_eq!((hand.mode, hand.colors, hand.threshold), (vectorcraft_trace::Mode::Grayscale, 12, 128));
}
/// Export writes no file that import would refuse (more than 1,000 presets, or more than 4 MiB),
/// and no more than 1,000 tracing presets can be saved.
#[test]
fn image_trace_presets_export_keeps_to_what_import_reads() {
let mut s = session();
let params = vectorcraft_trace::preset("Default").unwrap();
let preset = |name: String| crate::cmd::TracePreset { name, params: params.clone() };
s.prefs.trace_presets = (1..=1001).map(|i| preset(format!("P{i}"))).collect();
let e = s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string();
assert!(e.contains("more than one file holds (1000)"), "{e}");
s.prefs.trace_presets.pop();
let all = s.execute("imageTrace.presets.export", &json!({})).unwrap();
assert_eq!(all["count"], 1000);
let mut t = session();
assert_eq!(t.execute("imageTrace.presets.import", &json!({"data": all["data"]})).unwrap()["imported"].as_array().map(Vec::len), Some(1000));
// No more can be saved or imported then, so every saved preset still fits in one file; a
// saved preset can still change, and a file of saved names still replaces them.
let e = t.execute("imageTrace.presets.save", &json!({"name": "One More"})).unwrap_err().to_string();
assert!(e.contains("delete one first"), "{e}");
t.execute("imageTrace.presets.save", &json!({"name": "P1", "params": {"noise": 9}})).unwrap();
let one = json!({"format": "vctracepresets", "version": 1, "presets": [{"name": "Fresh", "params": {}}]}).to_string();
let e = t.execute("imageTrace.presets.import", &json!({ "data": one })).unwrap_err().to_string();
assert!(e.contains("more than 1000 saved"), "{e}");
let again = json!({"format": "vctracepresets", "version": 1, "presets": [{"name": "P2", "params": {}}]}).to_string();
assert_eq!(t.execute("imageTrace.presets.import", &json!({"data": again, "replace": true})).unwrap()["replaced"], json!(["P2"]));
assert_eq!(t.prefs.trace_presets.len(), 1000);
s.prefs.trace_presets = vec![preset("x".repeat(4 << 20))];
let e = s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string();
assert!(e.contains("larger than 4 MiB"), "{e}");
}
/// A saved preset of the same name is skipped unless `replace` is on; a file with a fault, or one
/// too large, changes nothing.
#[test]
fn image_trace_presets_import_checks_the_whole_file_first() {
let mut s = session();
s.execute("imageTrace.presets.save", &json!({"name": "Poster", "params": {"noise": 40}})).unwrap();
let file = |rows: Value| json!({"format": "vctracepresets", "version": 1, "presets": rows}).to_string();
let data = file(json!([{"name": "poster", "params": {"noise": 7}}, {"name": "Fresh", "params": {}}]));
let r = s.execute("imageTrace.presets.import", &json!({ "data": data })).unwrap();
assert_eq!(r, json!({"imported": ["Fresh"], "replaced": [], "skipped": ["poster"]}));
assert_eq!(s.trace_preset("Poster").unwrap().params.noise, 40);
let r = s.execute("imageTrace.presets.import", &json!({"data": data, "replace": true})).unwrap();
assert_eq!(r, json!({"imported": [], "replaced": ["Poster", "Fresh"], "skipped": []}));
assert_eq!(s.trace_preset("Poster").unwrap().params.noise, 7);
assert!(s.execute("imageTrace.presets.import", &json!({"data": data, "replace": "yes"})).is_err());
let saved = s.prefs.trace_presets.clone();
let revision = s.trace_presets_revision();
let bad_files = [
(file(json!([{"name": "New One", "params": {}}, {"name": "[Default]", "params": {}}])), "built-in preset"),
(file(json!([{"name": "custom", "params": {}}])), "built-in preset"),
(file(json!([{"name": "Twice", "params": {}}, {"name": "twice", "params": {}}])), "two presets named"),
(file(json!([{"name": " ", "params": {}}])), "has no name"),
(file(json!([{"name": "No Params"}])), "has no `params`"),
(file(json!([{"name": "Neither", "params": {"fills": false, "strokes": false}}])), "Create needs fills"),
(file(json!([{"name": "Typo", "params": {"nosie": 3}}])), "nosie"),
(json!({"format": "vctracepresets", "version": 2, "presets": []}).to_string(), "newer"),
(json!({"format": "vcflattener", "version": 1, "presets": []}).to_string(), "not a tracing presets file"),
("{".to_string(), "not a tracing presets file"),
(file(Value::Array(vec![json!({"name": "x", "params": {}}); 1001])), "more than 1000"),
(" ".repeat((4 << 20) + 1), "larger than 4 MiB"),
];
for (data, why) in bad_files {
let e = s.execute("imageTrace.presets.import", &json!({ "data": data })).unwrap_err().to_string();
assert!(e.contains(why), "{why}: {e}");
}
let big = vectorcraft_format::base64_encode(&vec![b' '; (4 << 20) + 1]);
assert!(s.execute("imageTrace.presets.import", &json!({ "dataBase64": big })).unwrap_err().to_string().contains("larger than 4 MiB"));
assert!(s.execute("imageTrace.presets.import", &json!({})).is_err());
assert_eq!(s.prefs.trace_presets, saved, "nothing changed");
assert_eq!(s.trace_presets_revision(), revision);
}
/// Saved tracing presets are kept with the preferences, are not a preference key, and survive
/// resetting the preferences.
#[test]
+29
View File
@@ -204,6 +204,35 @@ fn the_circle_is_not_moved_onto_the_pixel_grid() {
assert!(!node(&s, id).extras().pixel_aligned);
}
/// `anchors: "points"` puts an anchor exactly at each point, with one more on each half of a
/// diameter's circle; the circle is a plain path, not pixel-aligned, and one undo step. Any other
/// `anchors` value is an error and draws nothing.
#[test]
fn anchors_at_the_points_puts_an_anchor_at_each_point() {
let mut s = session();
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
let undo = undo_len(&s);
let points = [Point::new(0.3, 0.2), Point::new(80.6, 0.1), Point::new(0.4, 60.7)];
let pairs: Vec<Value> = points.iter().map(|p| json!([p.x, p.y])).collect();
let id = id_of(&s.execute(C, &json!({ "points": pairs, "anchors": "points" })).unwrap());
let n = node(&s, id);
let anchors: Vec<Point> = n.path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect();
assert!(points.iter().all(|p| anchors.contains(p)), "{anchors:?}");
assert!(matches!(n.kind, NodeKind::Path { live: None, .. }), "{:?}", n.kind);
assert!(!n.extras().pixel_aligned);
assert_eq!(undo_len(&s), undo + 1);
let id = id_of(&s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": "points" })).unwrap());
let anchors: Vec<Point> = node(&s, id).path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect();
assert_eq!(anchors.len(), 4, "{anchors:?}");
assert_eq!((anchors[0], anchors[2]), (Point::new(0.0, 0.0), Point::new(100.0, 0.0)));
let (count, undo) = (object_count(&s), undo_len(&s));
for bad in [json!("corners"), json!(true), json!(4), Value::Null] {
let e = s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": bad })).unwrap_err().to_string();
assert!(e.contains("`anchors` must be one of standard, points"), "{e}");
}
assert_eq!((object_count(&s), undo_len(&s)), (count, undo));
}
fn view() -> ViewInfo {
ViewInfo { smart_guides: false, ..ViewInfo::default() }
}
+827
View File
@@ -0,0 +1,827 @@
//! Tests for Fill Area (`shapeBuilder.copyRegion` and the `fillArea` tool).
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::Node;
use vectorcraft_geom::{FillRule, PathData, Point};
use vectorcraft_tools::{Cursor, Mods, Overlay, PointerEvent, PointerKind};
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
fn id_of(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn node(s: &Session, id: NodeId) -> Node {
s.doc().unwrap().doc.node(id).cloned().unwrap()
}
fn outline(s: &Session, id: NodeId) -> (PathData, FillRule) {
vectorcraft_tools::builder::node_outline(&node(s, id)).expect("path")
}
fn area(s: &Session, id: NodeId) -> f64 {
let (p, r) = outline(s, id);
vectorcraft_pathops::area(&p, r)
}
fn line(s: &mut Session, a: (f64, f64), b: (f64, f64)) -> NodeId {
id_of(&s.execute("shape.line", &json!({"x1": a.0, "y1": a.1, "x2": b.0, "y2": b.1})).unwrap())
}
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap())
}
/// Two diagonals and a crossbar: they enclose a triangle of 900 pt² above the crossbar.
fn triangle(s: &mut Session) -> [NodeId; 3] {
[line(s, (0.0, 0.0), (100.0, 100.0)), line(s, (100.0, 0.0), (0.0, 100.0)), line(s, (-10.0, 80.0), (110.0, 80.0))]
}
/// The ids of the default layer's children, back to front.
fn stack(s: &Session) -> Vec<NodeId> {
let d = &s.doc().unwrap().doc;
d.children(d.default_layer()).map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default()
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn deselect(s: &mut Session) {
s.execute("select.set", &json!({"ids": []})).unwrap();
}
/// Four circles in a 2×2 grid, each touching its neighbors, enclose a diamond nothing fills. With
/// nothing selected, a click in it adds the diamond and leaves the circles as they were.
#[test]
fn fill_area_adds_the_diamond_four_circles_enclose_and_keeps_them() {
let mut s = session();
let mut circles = vec![];
for (x, y) in [(0.0, 0.0), (100.0, 0.0), (0.0, 100.0), (100.0, 100.0)] {
circles.push(id_of(&s.execute("shape.ellipse", &json!({"x": x, "y": y, "width": 100, "height": 100})).unwrap()));
}
deselect(&mut s);
let before: Vec<_> = circles.iter().map(|c| outline(&s, *c)).collect();
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [100, 100]})).unwrap();
let new = id_of(&r);
assert!((area(&s, new) - 2146.0).abs() < 10.0, "{}", area(&s, new));
assert_eq!(stack(&s).len(), 5, "the four circles and the diamond");
let after: Vec<_> = circles.iter().map(|c| outline(&s, *c)).collect();
assert_eq!(after, before, "the circles keep their geometry");
assert_eq!(s.doc().unwrap().selection.objects, vec![new], "the new path is selected");
}
/// The overlap of two filled squares is an area too: the new path covers it, and both squares stay
/// whole (a Shape Builder merge there cuts it out of them).
#[test]
fn fill_area_copies_the_overlap_of_two_filled_squares() {
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0);
deselect(&mut s);
let (oa, ob) = (outline(&s, a), outline(&s, b));
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [75, 50]})).unwrap();
let new = id_of(&r);
assert!((area(&s, new) - 5000.0).abs() < 1.0, "{}", area(&s, new));
assert_eq!((outline(&s, a), outline(&s, b)), (oa, ob));
assert_eq!(stack(&s), vec![a, b, new], "above the front-most square");
assert_eq!(r["above"], json!(b.0));
}
/// Three lines bound a triangle; the new path has the current fill and stroke.
#[test]
fn fill_area_fills_the_triangle_three_lines_bound_with_the_current_paint() {
let mut s = session();
let lines = triangle(&mut s);
deselect(&mut s);
s.execute("paint.setFill", &json!({"color": "#336699"})).unwrap();
s.execute("paint.setStroke", &json!({"color": "#993300"})).unwrap();
let (fill, stroke) = (s.paint.fill.clone(), s.paint.stroke.clone());
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).unwrap();
let new = id_of(&r);
assert!((area(&s, new) - 900.0).abs() < 1e-6, "{}", area(&s, new));
let n = node(&s, new);
assert_eq!(n.appearance.fill_paint(), fill);
assert_eq!(n.appearance.stroke_paint(), stroke);
assert_eq!(stack(&s), vec![lines[0], lines[1], lines[2], new]);
// `fill` and `stroke` override the current paint.
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "fill": "#00ff00", "stroke": {"none": true}})).unwrap();
let n = node(&s, id_of(&r));
assert_eq!(n.appearance.fill_paint(), Paint::solid(Color::rgb(0.0, 1.0, 0.0)));
assert_eq!(n.appearance.stroke_paint(), Paint::None);
}
/// The new path takes the current stroke weight.
#[test]
fn fill_area_takes_the_current_stroke_weight() {
let mut s = session();
triangle(&mut s);
deselect(&mut s);
s.execute("paint.setStroke", &json!({"color": "#993300"})).unwrap();
s.paint.stroke_width = 4.0;
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).unwrap();
assert_eq!(node(&s, id_of(&r)).appearance.stroke_width(), 4.0);
}
/// `ids` names the objects or layers whose paths bound areas: without the crossbar the triangle is
/// open, and naming the layer takes every path in it.
#[test]
fn fill_area_ids_limit_the_paths_that_bound_areas() {
let mut s = session();
let lines = triangle(&mut s);
deselect(&mut s);
let two = json!({"point": [50, 70], "ids": [lines[0].0, lines[1].0]});
assert!(s.execute("shapeBuilder.copyRegion", &two).is_err());
let all = json!({"point": [50, 70], "ids": [lines[0].0, lines[1].0, lines[2].0]});
let r = s.execute("shapeBuilder.copyRegion", &all).unwrap();
assert!((area(&s, id_of(&r)) - 900.0).abs() < 1e-6);
let layer = s.doc().unwrap().doc.default_layer().unwrap();
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "ids": [layer.0]})).unwrap();
assert!((area(&s, id_of(&r)) - 900.0).abs() < 1e-6);
}
/// The new path goes above the group, Live Paint group or clipping group that holds the paths
/// along the area, never inside it, and the group keeps its members.
#[test]
fn fill_area_stacks_above_the_group_that_holds_the_paths() {
let mut s = session();
let lines = triangle(&mut s);
let ids: Vec<u64> = lines.iter().map(|l| l.0).collect();
s.execute("select.set", &json!({"ids": ids})).unwrap();
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
deselect(&mut s);
let members = |s: &Session, g: NodeId| -> Vec<NodeId> { node(s, g).children().unwrap().iter().map(|n| n.id).collect() };
let before = members(&s, g);
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).unwrap();
assert_eq!(stack(&s), vec![g, id_of(&r)]);
assert_eq!(r["above"], json!(g.0));
assert_eq!(members(&s, g), before);
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let b = rect(&mut s, 50.0, 0.0, 100.0, 100.0);
let lp = id_of(&s.execute("livePaint.make", &json!({"ids": [a.0, b.0]})).unwrap());
deselect(&mut s);
let before = members(&s, lp);
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [75, 50]})).unwrap();
assert!((area(&s, id_of(&r)) - 5000.0).abs() < 1.0, "{}", area(&s, id_of(&r)));
assert_eq!(stack(&s), vec![lp, id_of(&r)]);
assert_eq!(members(&s, lp), before);
let mut s = session();
let lines = triangle(&mut s);
let mask = rect(&mut s, -20.0, -20.0, 140.0, 140.0);
let ids: Vec<u64> = lines.iter().map(|l| l.0).chain([mask.0]).collect();
s.execute("select.set", &json!({"ids": ids})).unwrap();
s.execute("object.clippingMask.make", &json!({})).unwrap();
let clip = s.doc().unwrap().selection.objects[0];
deselect(&mut s);
let before = members(&s, clip);
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).unwrap();
assert_eq!(stack(&s), vec![clip, id_of(&r)]);
assert_eq!(members(&s, clip), before);
}
/// In isolation mode only the isolated group's paths bound areas, for the command and the tool: a
/// click in an area that art outside the group encloses adds nothing, and the new path goes inside
/// the group, above the path along the area.
#[test]
fn fill_area_stays_inside_the_isolated_group() {
let mut s = session();
let outside =
[line(&mut s, (200.0, 0.0), (300.0, 100.0)), line(&mut s, (300.0, 0.0), (200.0, 100.0)), line(&mut s, (190.0, 80.0), (310.0, 80.0))];
let lines = triangle(&mut s);
let ids: Vec<u64> = lines.iter().map(|l| l.0).collect();
s.execute("select.set", &json!({"ids": ids})).unwrap();
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.execute("object.isolate", &json!({"id": g.0})).unwrap();
deselect(&mut s);
let members = |s: &Session| -> Vec<NodeId> { node(s, g).children().unwrap().iter().map(|n| n.id).collect() };
let (undo, kids) = (undo_len(&s), stack(&s));
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [250, 70]})).is_err(), "art outside the isolated group");
let named: Vec<u64> = outside.iter().map(|l| l.0).collect();
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [250, 70], "ids": named})).is_err(), "named art outside it");
assert_eq!((undo_len(&s), stack(&s), members(&s)), (undo, kids.clone(), lines.to_vec()));
let v = ViewInfo::default();
s.select_tool("fillArea", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Move, 250.0, 70.0), v).unwrap();
assert!(
!s.overlays(v).iter().any(|o| matches!(o, Overlay::Path { color: [0xff, 0x2a, 0x2a], .. })),
"no area outside the isolated group is outlined"
);
s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 70.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 70.0), v).unwrap();
assert_eq!((undo_len(&s), stack(&s), members(&s)), (undo, kids.clone(), lines.to_vec()));
s.pointer(&PointerEvent::new(PointerKind::Move, 50.0, 70.0), v).unwrap();
let red = s.overlays(v).into_iter().filter(|o| matches!(o, Overlay::Path { color: [0xff, 0x2a, 0x2a], .. })).count();
assert_eq!(red, 1, "the isolated group's area is outlined");
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 70.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 50.0, 70.0), v).unwrap();
let new = s.doc().unwrap().selection.objects[0];
assert_eq!(s.doc().unwrap().doc.parent_of(new), Some(g));
assert_eq!(members(&s), [lines.as_slice(), &[new]].concat());
assert_eq!(stack(&s), kids);
assert!((area(&s, new) - 900.0).abs() < 1.0, "{}", area(&s, new));
// An isolated object that no longer exists counts as no isolation, for the tool as for the
// command: the area outside the group fills.
s.doc_mut().unwrap().isolation = Some(NodeId(999_999));
s.pointer(&PointerEvent::new(PointerKind::Move, 250.0, 70.0), v).unwrap();
let red = s.overlays(v).into_iter().filter(|o| matches!(o, Overlay::Path { color: [0xff, 0x2a, 0x2a], .. })).count();
assert_eq!(red, 1, "the area outside the group is outlined");
s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 70.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 70.0), v).unwrap();
let new = s.doc().unwrap().selection.objects[0];
assert_eq!(s.doc().unwrap().doc.parent_of(new), s.doc().unwrap().doc.default_layer());
}
/// While a compound path is isolated, Fill Area finds no area, for the command and the tool, and
/// changes nothing: the compound path cannot hold the new path. The same goes for an isolated
/// Objects on Path group, a group with a Transform effect and a group that is a clipping mask.
#[test]
fn fill_area_finds_nothing_while_a_compound_path_is_isolated() {
let mut s = session();
let outer = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let inner = rect(&mut s, 25.0, 25.0, 50.0, 50.0);
s.execute("select.set", &json!({"ids": [outer.0, inner.0]})).unwrap();
let c = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
deselect(&mut s);
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [10, 10]})).is_ok(), "the ring fills outside isolation");
s.execute("edit.undo", &json!({})).unwrap();
s.doc_mut().unwrap().isolation = Some(c);
let (undo, kids) = (undo_len(&s), stack(&s));
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [10, 10]})).is_err());
let v = ViewInfo::default();
s.select_tool("fillArea", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Move, 10.0, 10.0), v).unwrap();
assert!(!s.overlays(v).iter().any(|o| matches!(o, Overlay::Path { color: [0xff, 0x2a, 0x2a], .. })));
s.pointer(&PointerEvent::new(PointerKind::Down, 10.0, 10.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 10.0, 10.0), v).unwrap();
assert_eq!((undo_len(&s), stack(&s)), (undo, kids));
// An Objects on Path group moves its members along the path, so a new path in it would not
// stay where the area is.
let mut s = session();
let a = rect(&mut s, 0.0, 0.0, 40.0, 40.0);
let b = rect(&mut s, 100.0, 0.0, 40.0, 40.0);
let path = line(&mut s, (0.0, 200.0), (300.0, 200.0));
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let g = id_of(&s.execute("object.objectsOnPath.attach", &json!({"path": path.0})).unwrap());
deselect(&mut s);
let c = s.doc().unwrap().doc.node(a).unwrap().geometric_bounds().unwrap().center();
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [c.x, c.y]})).is_ok(), "the square fills outside isolation");
s.execute("edit.undo", &json!({})).unwrap();
s.doc_mut().unwrap().isolation = Some(g);
let (undo, kids) = (undo_len(&s), stack(&s));
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [c.x, c.y]})).is_err());
assert_eq!((undo_len(&s), stack(&s)), (undo, kids));
// A group with a Transform effect moves what is in it, so a new path in it would not be drawn
// where the area is.
let mut s = session();
let lines = triangle(&mut s);
let ids: Vec<u64> = lines.iter().map(|l| l.0).collect();
s.execute("select.set", &json!({"ids": ids})).unwrap();
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
s.execute("effect.apply", &json!({"effect": "distort.transform", "params": {"moveH": 100}, "ids": [g.0], "item": null})).unwrap();
deselect(&mut s);
s.doc_mut().unwrap().isolation = Some(g);
let (undo, kids) = (undo_len(&s), stack(&s));
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).is_err());
assert_eq!((undo_len(&s), stack(&s), node(&s, g).children().unwrap().len()), (undo, kids, 3));
// A group that is a clipping mask clips and is not painted, so it takes no new path.
let mut s = session();
let back = rect(&mut s, -20.0, -20.0, 140.0, 140.0);
let edge = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
s.execute("select.set", &json!({"ids": [back.0, edge.0]})).unwrap();
let clip = id_of(&s.execute("object.clippingMask.make", &json!({})).unwrap());
s.execute("select.set", &json!({"ids": [edge.0]})).unwrap();
let mask = id_of(&s.execute("object.group", &json!({})).unwrap());
// A filled square drawn in the mask group bounds an area of its own.
s.doc_mut().unwrap().isolation = Some(mask);
let square = rect(&mut s, 10.0, 10.0, 80.0, 80.0);
assert_eq!(s.doc().unwrap().doc.parent_of(square), Some(mask));
deselect(&mut s);
let first = node(&s, clip).children().unwrap()[0].id;
assert_eq!(first, mask, "the group is the clipping mask");
let (undo, kids) = (undo_len(&s), stack(&s));
let members = node(&s, mask).children().unwrap().len();
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).is_err());
assert_eq!((undo_len(&s), stack(&s), node(&s, mask).children().unwrap().len()), (undo, kids, members));
// The clipping group itself, and a group of the art it clips, take no new path either: the
// mask would hide or cut it.
s.doc_mut().unwrap().isolation = None;
s.execute("select.set", &json!({"ids": [back.0]})).unwrap();
let clipped = id_of(&s.execute("object.group", &json!({})).unwrap());
assert_eq!(s.doc().unwrap().doc.parent_of(clipped), Some(clip));
deselect(&mut s);
for iso in [clip, clipped] {
s.doc_mut().unwrap().isolation = Some(iso);
let (undo, kids) = (undo_len(&s), stack(&s));
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [5, 5]})).is_err(), "{iso:?}");
assert_eq!((undo_len(&s), stack(&s)), (undo, kids), "{iso:?}");
}
}
/// The new path goes directly above the front-most object along the area, not above art that
/// lies elsewhere, and paths on other layers bound areas too.
#[test]
fn fill_area_takes_paths_on_every_layer_and_stacks_above_the_area() {
let mut s = session();
let first = s.doc().unwrap().doc.default_layer();
let l1 = line(&mut s, (0.0, 0.0), (100.0, 100.0));
let l2 = line(&mut s, (100.0, 0.0), (0.0, 100.0));
let far = rect(&mut s, 400.0, 400.0, 50.0, 50.0);
let other = id_of(&s.execute("layer.new", &json!({"name": "Other"})).unwrap());
let l3 = line(&mut s, (-10.0, 80.0), (110.0, 80.0));
let top = rect(&mut s, 500.0, 400.0, 50.0, 50.0);
deselect(&mut s);
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).unwrap();
let new = id_of(&r);
let d = &s.doc().unwrap().doc;
assert_eq!(d.parent_of(new), Some(other));
let kids: Vec<NodeId> = d.children(Some(other)).unwrap().iter().map(|n| n.id).collect();
assert_eq!(kids, vec![l3, new, top]);
let kids: Vec<NodeId> = d.children(first).unwrap().iter().map(|n| n.id).collect();
assert_eq!(kids, vec![l1, l2, far]);
}
/// An area far larger than the paths near the point: four long lines bound a 400 pt square whose
/// middle no path's bounds hold, and a small triangle inside it is a hole in the area.
#[test]
fn fill_area_finds_an_area_that_reaches_far_from_the_point() {
let mut s = session();
line(&mut s, (-20.0, 0.0), (420.0, 0.0));
line(&mut s, (-20.0, 400.0), (420.0, 400.0));
line(&mut s, (0.0, -20.0), (0.0, 420.0));
line(&mut s, (400.0, -20.0), (400.0, 420.0));
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [200, 200]})).unwrap();
assert!((area(&s, id_of(&r)) - 160_000.0).abs() < 1.0, "{}", area(&s, id_of(&r)));
for (a, b) in [((150.0, 250.0), (250.0, 350.0)), ((250.0, 250.0), (150.0, 350.0)), ((140.0, 330.0), (260.0, 330.0))] {
line(&mut s, a, b);
}
deselect(&mut s);
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).unwrap();
assert!((area(&s, id_of(&r)) - (160_000.0 - 900.0)).abs() < 1.0, "the square less the triangle: {}", area(&s, id_of(&r)));
}
/// Distant art with more segments than one Shape Builder map takes does not stop four lines from
/// bounding the square between them: the search maps the lines near the point first, and a window
/// that reaches the distant art leaves it out.
#[test]
fn fill_area_finds_a_nearby_area_beside_a_huge_distant_path() {
for (at, huge_x) in [(0.0, 20_000.0), (100.0, 1_300.0)] {
let mut s = session();
let (lo, hi) = (at, at + 800.0);
line(&mut s, (lo - 20.0, lo), (hi + 20.0, lo));
line(&mut s, (lo - 20.0, hi), (hi + 20.0, hi));
line(&mut s, (lo, lo - 20.0), (lo, hi + 20.0));
line(&mut s, (hi, lo - 20.0), (hi, hi + 20.0));
let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS;
let pts: Vec<Point> = (0..=n).map(|k| Point::new(huge_x + 400.0 * k as f64 / n as f64, 500.0 + (k % 2) as f64)).collect();
let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
s.edit("t", |d, _| {
let id = d.alloc_id();
let top = d.children(d.default_layer()).map_or(0, |c| c.len());
d.insert(d.default_layer(), top, Node::path(id, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look))?;
Ok(id)
})
.unwrap();
deselect(&mut s);
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [at + 400.0, at + 400.0]})).unwrap();
assert!((area(&s, id_of(&r)) - 640_000.0).abs() < 1.0, "{huge_x}: {}", area(&s, id_of(&r)));
}
}
/// A path with too many segments near a long, flat area stays out of the map, and the area's far
/// ends still bound it.
#[test]
fn fill_area_finds_a_long_area_beside_a_huge_path() {
let mut s = session();
line(&mut s, (-10.0, -20.0), (810.0, -20.0));
line(&mut s, (-10.0, 20.0), (810.0, 20.0));
line(&mut s, (0.0, -30.0), (0.0, 30.0));
line(&mut s, (800.0, -30.0), (800.0, 30.0));
line(&mut s, (-10.0, 0.0), (810.0, 0.0));
let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS;
let pts: Vec<Point> = (0..=n).map(|k| Point::new(300.0 + 200.0 * k as f64 / n as f64, 60.0 + (k % 2) as f64 * 0.5)).collect();
let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
s.edit("t", |d, _| {
let id = d.alloc_id();
let top = d.children(d.default_layer()).map_or(0, |c| c.len());
d.insert(d.default_layer(), top, Node::path(id, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look))?;
Ok(id)
})
.unwrap();
deselect(&mut s);
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [400, 0.5]})).unwrap();
assert!((area(&s, id_of(&r)) - 16_000.0).abs() < 1.0, "{}", area(&s, id_of(&r)));
}
/// A path with too many segments that crosses the area cannot be left out, and the paths together
/// are past the segment limit: the square it cuts is not filled across it, whether four lines or one
/// filled rectangle bound the square.
#[test]
fn fill_area_does_not_fill_across_a_huge_path_it_left_out() {
for closed in [false, true] {
let mut s = session();
if closed {
rect(&mut s, 0.0, 0.0, 400.0, 400.0);
} else {
line(&mut s, (-20.0, 0.0), (420.0, 0.0));
line(&mut s, (-20.0, 400.0), (420.0, 400.0));
line(&mut s, (0.0, -20.0), (0.0, 420.0));
line(&mut s, (400.0, -20.0), (400.0, 420.0));
}
let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS;
let pts: Vec<Point> = (0..=n).map(|k| Point::new(-20.0 + 440.0 * k as f64 / n as f64, 300.0)).collect();
let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
s.edit("t", |d, _| {
let id = d.alloc_id();
let top = d.children(d.default_layer()).map_or(0, |c| c.len());
d.insert(d.default_layer(), top, Node::path(id, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look))?;
Ok(id)
})
.unwrap();
deselect(&mut s);
let (undo, kids) = (undo_len(&s), stack(&s));
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [200, 100]})).is_err(), "closed: {closed}");
assert_eq!((undo_len(&s), stack(&s)), (undo, kids));
}
}
/// A path with too many segments whose box holds the square, but no segment of it comes near: its
/// subpaths lie far apart on either side of the square, or one curve arcs around the square and its
/// box holds the square. It is left out and the square is filled.
#[test]
fn fill_area_fills_an_area_that_a_left_out_paths_box_holds_but_its_segments_miss() {
// A cubic from (-1000, 1500) up over the square to (1400, 1500); at its top it is at y -750.
let mut arc = vectorcraft_geom::SubPath::polyline(&[Point::new(-1000.0, 1500.0), Point::new(1400.0, 1500.0)], false);
arc.anchors[0].h_out = Point::new(-1000.0, -1500.0);
arc.anchors[1].h_in = Point::new(1400.0, -1500.0);
let far = vectorcraft_geom::SubPath::polyline(&[Point::new(2000.0, 1500.0), Point::new(2100.0, 1500.0)], false);
for second in [far, arc] {
let mut s = session();
line(&mut s, (-20.0, 0.0), (420.0, 0.0));
line(&mut s, (-20.0, 400.0), (420.0, 400.0));
line(&mut s, (0.0, -20.0), (0.0, 420.0));
line(&mut s, (400.0, -20.0), (400.0, 420.0));
let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS;
let pts: Vec<Point> = (0..=n).map(|k| Point::new(-2000.0 + 400.0 * k as f64 / n as f64, -1000.0 + (k % 2) as f64)).collect();
let path = PathData::new(vec![vectorcraft_geom::SubPath::polyline(&pts, false), second.clone()]);
let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
s.edit("t", |d, _| {
let id = d.alloc_id();
let top = d.children(d.default_layer()).map_or(0, |c| c.len());
d.insert(d.default_layer(), top, Node::path(id, path, look))?;
Ok(id)
})
.unwrap();
deselect(&mut s);
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [200, 200]})).unwrap();
assert!((area(&s, id_of(&r)) - 160_000.0).abs() < 1.0, "{second:?}: {}", area(&s, id_of(&r)));
}
}
/// Puts `path` with `look` in front on the current layer.
fn insert_path(s: &mut Session, path: PathData, look: vectorcraft_doc::Appearance) -> NodeId {
s.edit("t", |d, _| {
let id = d.alloc_id();
let top = d.children(d.default_layer()).map_or(0, |c| c.len());
d.insert(d.default_layer(), top, Node::path(id, path, look))?;
Ok(id)
})
.unwrap()
}
/// A path with too many segments in the empty corner of a filled L, well clear of both arms, is
/// left out and does not stop the L from being filled, though the L's box holds it.
#[test]
fn fill_area_fills_an_l_whose_empty_corner_holds_a_left_out_path() {
let mut s = session();
let l = [(0.0, 0.0), (400.0, 0.0), (400.0, 100.0), (100.0, 100.0), (100.0, 400.0), (0.0, 400.0)].map(|(x, y)| Point::new(x, y));
let solid = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0);
insert_path(&mut s, PathData::single(vectorcraft_geom::SubPath::polyline(&l, true)), solid);
let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS;
let pts: Vec<Point> = (0..=n).map(|k| Point::new(250.0 + 100.0 * k as f64 / n as f64, 250.0 + (k % 2) as f64)).collect();
let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
insert_path(&mut s, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look);
deselect(&mut s);
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).unwrap();
assert!((area(&s, id_of(&r)) - 70_000.0).abs() < 1.0, "{}", area(&s, id_of(&r)));
}
/// A filled contour with too many segments on a higher layer surrounds a small square, its outline
/// far from it: it is left out of the map, and the new path still goes above it, since it covers
/// the area.
#[test]
fn fill_area_stacks_above_a_left_out_path_that_covers_the_area() {
let mut s = session();
let layer = s.doc().unwrap().doc.default_layer();
rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let over = id_of(&s.execute("layer.new", &json!({"name": "Over"})).unwrap());
let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS + 1;
let pts: Vec<Point> = (0..n)
.map(|k| {
let a = k as f64 * std::f64::consts::TAU / n as f64;
Point::new(50.0 + 3000.0 * a.cos(), 50.0 + 3000.0 * a.sin())
})
.collect();
let solid = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0);
let contour = insert_path(&mut s, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, true)), solid);
deselect(&mut s);
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).unwrap();
assert!((area(&s, id_of(&r)) - 10_000.0).abs() < 1.0, "{}", area(&s, id_of(&r)));
assert_eq!(r["above"], json!(contour.0));
let d = &s.doc().unwrap().doc;
assert_eq!(d.parent_of(id_of(&r)), Some(over));
assert_ne!(d.parent_of(id_of(&r)), layer);
}
/// With Gap Detection off, a long line on a higher layer 0.75 pt from a square's edge neither
/// touches nor covers the square, so the new path stays above the square.
#[test]
fn fill_area_does_not_stack_above_a_line_that_does_not_touch_the_area() {
let mut s = session();
let layer = s.doc().unwrap().doc.default_layer();
let square = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
id_of(&s.execute("layer.new", &json!({"name": "Other"})).unwrap());
line(&mut s, (-5000.0, -0.75), (5000.0, -0.75));
deselect(&mut s);
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50]})).unwrap();
assert_eq!(r["above"], json!(square.0));
assert_eq!(s.doc().unwrap().doc.parent_of(id_of(&r)), layer);
}
/// With Gap Detection on, a square on a higher layer within the gap of the area's corners does not
/// bound the area, so the new path stays above the square that does.
#[test]
fn fill_area_gap_does_not_stack_above_a_nearby_path() {
let mut s = session();
let first = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let layer = s.doc().unwrap().doc.default_layer();
let other = id_of(&s.execute("layer.new", &json!({"name": "Other"})).unwrap());
rect(&mut s, 102.0, 0.0, 100.0, 100.0);
deselect(&mut s);
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 50], "gap": 3})).unwrap();
let d = &s.doc().unwrap().doc;
assert_eq!(d.parent_of(id_of(&r)), layer);
assert_ne!(d.parent_of(id_of(&r)), Some(other));
assert_eq!(r["above"], json!(first.0));
}
/// An object listed in `ids` with the layer that holds it counts once, so the new path still goes
/// above the front-most of two overlapping squares.
#[test]
fn fill_area_ids_count_an_object_and_its_layer_once() {
let mut s = session();
let back = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let front = rect(&mut s, 50.0, 0.0, 100.0, 100.0);
deselect(&mut s);
let layer = s.doc().unwrap().doc.default_layer().unwrap();
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [75, 50], "ids": [layer.0, back.0]})).unwrap();
assert_eq!(stack(&s), vec![back, front, id_of(&r)]);
}
/// A flat window that reaches a path with too many segments leaves that path out and grows to the
/// paths it had not picked: a crossbar that no path near the point leads to still splits the area.
#[test]
fn fill_area_keeps_paths_a_capped_window_had_not_picked() {
let mut s = session();
// Four lines bound a box; a line through the point and a crossbar higher up cut it.
line(&mut s, (50.0, -60.0), (50.0, 410.0));
line(&mut s, (350.0, -60.0), (350.0, 410.0));
line(&mut s, (40.0, -50.0), (360.0, -50.0));
line(&mut s, (40.0, 400.0), (360.0, 400.0));
line(&mut s, (0.0, 100.0), (400.0, 100.0));
line(&mut s, (40.0, 30.0), (360.0, 30.0));
let n = vectorcraft_pathops::SHAPE_BUILDER_MAX_SEGMENTS;
let pts: Vec<Point> = (0..=n).map(|k| Point::new(380.0 + 20.0 * k as f64 / n as f64, 100.0 + (k % 2) as f64 * 0.5)).collect();
let look = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
s.edit("t", |d, _| {
let id = d.alloc_id();
let top = d.children(d.default_layer()).map_or(0, |c| c.len());
d.insert(d.default_layer(), top, Node::path(id, PathData::single(vectorcraft_geom::SubPath::polyline(&pts, false)), look))?;
Ok(id)
})
.unwrap();
deselect(&mut s);
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [200, 99.5]})).unwrap();
assert!((area(&s, id_of(&r)) - 21_000.0).abs() < 1.0, "between the crossbar and the line: {}", area(&s, id_of(&r)));
}
/// Two diagonals and a crossbar about 3 pt short of each: the area closes only with a gap of 3 pt
/// or more, and a gap out of 0 to 72 pt is an error.
#[test]
fn fill_area_gap_closes_small_gaps() {
let mut s = session();
line(&mut s, (0.0, 0.0), (100.0, 100.0));
line(&mut s, (100.0, 0.0), (0.0, 100.0));
line(&mut s, (24.0, 80.0), (76.0, 80.0));
deselect(&mut s);
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).is_err());
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "gap": 2})).is_err());
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "gap": 3})).unwrap();
let a = area(&s, id_of(&r));
assert!(a > 850.0 && a < 900.0, "the triangle and its two bridges: {a}");
for gap in [json!(-1), json!(73), json!("3")] {
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "gap": gap})).is_err(), "{gap}");
}
}
/// Locked and hidden paths do not bound an area: the triangle fills while its crossbar is unlocked
/// and visible, and not once the crossbar is locked or hidden.
#[test]
fn fill_area_skips_locked_and_hidden_paths() {
for how in ["object.lock", "object.hide"] {
let mut s = session();
let lines = triangle(&mut s);
deselect(&mut s);
let r = s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).unwrap();
assert!((area(&s, id_of(&r)) - 900.0).abs() < 1e-6, "{how}");
s.execute("edit.undo", &json!({})).unwrap();
s.execute(how, &json!({"ids": [lines[2].0]})).unwrap();
deselect(&mut s);
let (undo, kids) = (undo_len(&s), stack(&s));
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).is_err(), "{how}");
assert_eq!((undo_len(&s), stack(&s)), (undo, kids), "{how}");
}
}
/// A point in no enclosed area changes nothing and records no undo step; bad params are errors. A
/// point inside the triangle fills it.
#[test]
fn fill_area_outside_every_area_changes_nothing() {
let mut s = session();
triangle(&mut s);
deselect(&mut s);
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70]})).is_ok());
s.execute("edit.undo", &json!({})).unwrap();
let (undo, kids) = (undo_len(&s), stack(&s));
for p in [json!({"point": [500, 500]}), json!({"point": [50, 90]}), json!({"point": [-500, -500]})] {
assert!(s.execute("shapeBuilder.copyRegion", &p).is_err(), "{p}");
}
for p in [json!({}), json!({"point": [50]}), json!({"point": [50, 70], "fill": "nope"}), json!({"point": [50, 70], "stroke": 3})] {
assert!(s.execute("shapeBuilder.copyRegion", &p).is_err(), "{p}");
}
for paint in [json!({"swatch": 123}), json!({"color": 5}), json!({"color": "nope"})] {
for key in ["fill", "stroke"] {
let p = json!({"point": [50, 70], key: paint});
assert!(s.execute("shapeBuilder.copyRegion", &p).is_err(), "{p}");
}
}
assert!(s.execute("shapeBuilder.copyRegion", &json!({"point": [50, 70], "ids": [999_999]})).is_err());
assert_eq!((undo_len(&s), stack(&s)), (undo, kids));
}
/// The tool outlines the area under the pointer, shows the bucket over it, and a click adds the
/// path; a click outside every area records nothing. It uses the Shape Builder's Gap Detection.
#[test]
fn fill_area_tool_drives_the_command() {
let mut s = session();
line(&mut s, (0.0, 0.0), (100.0, 100.0));
line(&mut s, (100.0, 0.0), (0.0, 100.0));
line(&mut s, (24.0, 80.0), (76.0, 80.0));
deselect(&mut s);
let v = ViewInfo::default();
s.select_tool("fillArea", v).unwrap();
assert_eq!(s.tool_id(), "fillArea");
s.pointer(&PointerEvent::new(PointerKind::Move, 50.0, 70.0), v).unwrap();
assert!(s.overlays(v).is_empty(), "the gap leaves the triangle open");
assert_eq!(s.cursor(Point::new(50.0, 70.0), Mods::default(), v), Cursor::LivePaintBucket);
let (undo, kids) = (undo_len(&s), stack(&s));
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 70.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 50.0, 70.0), v).unwrap();
assert_eq!((undo_len(&s), stack(&s)), (undo, kids), "nothing to fill");
// The Shape Builder's options reach the active Fill Area tool.
s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "values": {"gapDetection": true, "gapLength": 3}})).unwrap();
assert_eq!(s.tool_options_of("fillArea")["gapLength"], json!(3.0));
s.pointer(&PointerEvent::new(PointerKind::Move, 50.0, 70.0), v).unwrap();
let red: Vec<_> = s.overlays(v).into_iter().filter(|o| matches!(o, Overlay::Path { color: [0xff, 0x2a, 0x2a], .. })).collect();
assert_eq!(red.len(), 1, "the area is outlined in red");
assert_eq!(s.cursor(Point::new(50.0, 70.0), Mods::default(), v), Cursor::LivePaintBucketFace);
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 70.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 50.0, 70.0), v).unwrap();
assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.copyRegion");
assert_eq!(stack(&s).len(), 4);
assert_eq!(undo_len(&s), undo + 1);
assert_eq!(s.tool_id(), "fillArea");
assert!(s.set_tool_option_cmd(&json!({"tool": "fillArea", "values": {"highlightColor": "#ff0000"}})).is_err());
assert!(s.set_tool_option_cmd(&json!({"tool": "fillArea", "values": {"gapLength": "wide"}})).is_err());
// Setting them on Fill Area sets them for the Shape Builder too.
s.set_tool_option_cmd(&json!({"tool": "fillArea", "values": {"gapLength": 5, "openFilledAsClosed": false}})).unwrap();
let opts = s.tool_options_of("shapeBuilder");
assert_eq!((opts["gapLength"].clone(), opts["openFilledAsClosed"].clone()), (json!(5.0), json!(false)));
}
/// The hover search for a document of more than 128 segments runs on another thread: nothing is
/// outlined until the tool is polled, and a click finds the area at once.
#[test]
fn fill_area_tool_hovers_a_large_document_on_another_thread() {
let mut s = session();
s.execute("shape.polygon", &json!({"cx": 300, "cy": 300, "radius": 100, "sides": 200})).unwrap();
deselect(&mut s);
let v = ViewInfo::default();
s.select_tool("fillArea", v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 300.0), v).unwrap();
assert!(s.tool_waiting());
assert!(s.overlays(v).is_empty());
// The pointer moves on inside the area before the search is done: its result still serves.
s.pointer(&PointerEvent::new(PointerKind::Move, 305.0, 300.0), v).unwrap();
s.tool_poll(v, false).unwrap();
s.tool_poll(v, true).unwrap();
assert!(!s.tool_waiting());
assert_eq!(s.overlays(v).len(), 1, "the polygon is outlined");
// Leaving the area takes the outline away at once, while the next search runs.
s.pointer(&PointerEvent::new(PointerKind::Move, 500.0, 500.0), v).unwrap();
assert!(s.overlays(v).is_empty());
s.tool_poll(v, true).unwrap();
assert!(s.overlays(v).is_empty());
s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 300.0), v).unwrap();
s.tool_poll(v, true).unwrap();
assert_eq!(s.overlays(v).len(), 1);
// A click while a search runs waits for it: the pointer leaves the area, which starts a
// search, and the press inside the area comes before any poll.
s.pointer(&PointerEvent::new(PointerKind::Move, 500.0, 500.0), v).unwrap();
assert!(s.tool_waiting());
let undo = undo_len(&s);
s.pointer(&PointerEvent::new(PointerKind::Down, 310.0, 300.0), v).unwrap();
assert!(!s.tool_waiting(), "the press waited for the search");
s.pointer(&PointerEvent::new(PointerKind::Up, 310.0, 300.0), v).unwrap();
assert_eq!(undo_len(&s), undo + 1);
}
/// A press that is dropped before the release (a long or canceled touch) takes the new path back
/// and records no undo step.
#[test]
fn fill_area_tool_dropped_press_adds_nothing() {
let mut s = session();
triangle(&mut s);
deselect(&mut s);
let v = ViewInfo::default();
s.select_tool("fillArea", v).unwrap();
let (undo, kids) = (undo_len(&s), stack(&s));
s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 70.0), v).unwrap();
assert_eq!(stack(&s).len(), kids.len() + 1, "the path shows during the press");
s.drop_tool_press(v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 50.0, 70.0), v).unwrap();
assert_eq!((undo_len(&s), stack(&s)), (undo, kids));
}
/// The outline under a still pointer goes when the document changes, and the canvas hovers the
/// tool again then.
#[test]
fn fill_area_tool_drops_a_hover_the_document_no_longer_has() {
let mut s = session();
rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let v = ViewInfo::default();
s.select_tool("fillArea", v).unwrap();
assert!(s.tool_wants_rehover());
s.pointer(&PointerEvent::new(PointerKind::Move, 50.0, 50.0), v).unwrap();
assert_eq!(s.overlays(v).len(), 1);
s.execute("edit.clear", &json!({})).unwrap();
assert!(s.overlays(v).is_empty());
assert_eq!(s.cursor(Point::new(50.0, 50.0), Mods::default(), v), Cursor::LivePaintBucket);
}
/// Moving the pointer from an area with a hole into the area that fills the hole outlines the
/// inner area instead.
#[test]
fn fill_area_tool_hover_moves_from_an_area_into_its_hole() {
let mut s = session();
line(&mut s, (-20.0, 0.0), (420.0, 0.0));
line(&mut s, (-20.0, 400.0), (420.0, 400.0));
line(&mut s, (0.0, -20.0), (0.0, 420.0));
line(&mut s, (400.0, -20.0), (400.0, 420.0));
for (a, b) in [((150.0, 250.0), (250.0, 350.0)), ((250.0, 250.0), (150.0, 350.0)), ((140.0, 330.0), (260.0, 330.0))] {
line(&mut s, a, b);
}
deselect(&mut s);
let v = ViewInfo::default();
s.select_tool("fillArea", v).unwrap();
let outlined = |s: &mut Session| -> Vec<f64> {
s.overlays(v)
.into_iter()
.filter_map(|o| match o {
Overlay::Path { path, .. } => Some(kurbo::Shape::bounding_box(&path).width()),
_ => None,
})
.collect()
};
s.pointer(&PointerEvent::new(PointerKind::Move, 50.0, 50.0), v).unwrap();
let w = outlined(&mut s);
assert!(w.len() == 1 && (w[0] - 400.0).abs() < 1e-6, "the square: {w:?}");
s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 320.0), v).unwrap();
let w = outlined(&mut s);
assert!(w.len() == 1 && (w[0] - 60.0).abs() < 1e-6, "the triangle in its hole: {w:?}");
}
+264
View File
@@ -127,6 +127,25 @@ fn c_flips_and_brackets_size_the_last_sharp_arc() {
assert!(!s.tool_claims_key(ToolKey::Letter('c'), view()));
}
/// The drawing end (where the Quick Pen toolbar sits beside) is the path's last point with the
/// direction it arrives in: none before the first click, no direction for one point, and none
/// once Escape ends the path.
#[test]
fn the_drawing_end_is_the_last_point_and_its_direction() {
let mut s = session();
quick_pen(&mut s);
assert_eq!(s.tool_drawing_end(view()), None);
click(&mut s, 100.0, 100.0);
assert_eq!(s.tool_drawing_end(view()), Some((pt(100.0, 100.0), None)));
click(&mut s, 100.0, 200.0);
let (p, dir) = s.tool_drawing_end(view()).unwrap();
assert_eq!(p, pt(100.0, 200.0));
let dir = dir.unwrap();
assert!(dir.x.abs() < 1e-9 && dir.y > 0.99, "arrives heading down: {dir:?}");
key(&mut s, ToolKey::Escape);
assert_eq!(s.tool_drawing_end(view()), None);
}
/// Alt tapped during a drag draws the piece with the next action: a continuous arc becomes a
/// sharp-corner arc with a corner where it starts, and the path goes on drawing after it.
#[test]
@@ -183,6 +202,251 @@ fn escape_ends_the_path_and_a_drag_places_the_piece() {
assert_eq!(paths(&s).len(), 2);
}
/// The piece a press draws ends where the press is let go, past the last drag too, and a press let
/// go a drag's distance away with no drag in between places it there as well.
#[test]
fn the_piece_ends_where_the_press_is_let_go() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 180.0, 120.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 150.0), v).unwrap();
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(250.0, 150.0));
let undo = undo_steps(&s);
s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 340.0, 100.0), v).unwrap();
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(340.0, 100.0));
assert_eq!(undo_steps(&s), undo + 1);
}
/// C and `[` `]` during a drag change the sharp-corner arc being dragged, within the press's one
/// undo step.
#[test]
fn c_and_brackets_during_a_drag_change_the_arc_being_dragged() {
let mut s = session();
quick_pen(&mut s);
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
click(&mut s, 100.0, 300.0);
let undo = undo_steps(&s);
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 300.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 300.0), v).unwrap();
assert!(s.tool_claims_key(ToolKey::Letter('c'), view()));
key(&mut s, ToolKey::Letter('c'));
assert!(only_path(&s).anchors.get(1).unwrap().p.distance(pt(200.0, 400.0)) < 1e-9, "flipped while dragging");
key(&mut s, ToolKey::BracketLeft);
assert_eq!(s.tool_options()["turn"], 165.0);
// A 165° arc is two segments, and its middle point lies the arc's sagitta below the chord
// (a 180° arc's lies 100 below).
let half = 82.5f64.to_radians();
let mid_165 = pt(200.0, 300.0 + 100.0 / half.sin() * (1.0 - half.cos()));
assert_eq!(only_path(&s).anchors.len(), 3);
assert!(only_path(&s).anchors.get(1).unwrap().p.distance(mid_165) < 1e-6, "the dragged arc is 165°");
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), v).unwrap();
let sp = only_path(&s);
assert_eq!(sp.anchors.len(), 3);
assert!(sp.anchors.get(1).unwrap().p.distance(mid_165) < 1e-6, "the flip and the size stay after the release");
assert_eq!(undo_steps(&s), undo + 1);
}
/// An edit made by another command during a drag ends the path: the next drag does not draw over
/// the edit, the piece stays as last shown, and the next click starts a new path.
#[test]
fn an_edit_during_a_drag_ends_the_path() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let id = paths(&s)[0].0;
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap();
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 250.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap();
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
assert_eq!(ends, [pt(90.0, 90.0), pt(200.0, 100.0), pt(200.0, 200.0)], "the edit and the piece as last shown");
click(&mut s, 400.0, 400.0);
assert_eq!(paths(&s).len(), 2, "a new path");
}
/// With Real-time Drawing off, a sharp-corner arc let go past the last drag is placed where it was
/// let go, and C then flips that arc.
#[test]
fn a_deferred_arc_let_go_past_the_last_drag_flips() {
let mut s = session();
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
quick_pen(&mut s);
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
click(&mut s, 100.0, 300.0);
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 300.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 270.0, 300.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), v).unwrap();
let sp = only_path(&s);
assert_eq!(sp.anchors.len(), 3);
assert_eq!(sp.anchors.last().unwrap().p, pt(300.0, 300.0));
let mid = sp.anchors.get(1).unwrap().p;
key(&mut s, ToolKey::Letter('c'));
let flipped = only_path(&s);
assert_eq!(flipped.anchors.len(), 3);
assert!(flipped.anchors.get(1).unwrap().p.distance(pt(200.0, 600.0 - mid.y)) < 1e-9, "flipped across the chord");
}
/// An edit made by another command to the path's look during a drag ends the path too.
#[test]
fn a_look_edit_during_a_drag_ends_the_path() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let id = paths(&s)[0].0;
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap();
s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#00ff00"})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap();
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(200.0, 200.0)], "the piece as last shown");
click(&mut s, 400.0, 400.0);
assert_eq!(paths(&s).len(), 2, "a new path");
}
/// An edit made by another command to another object during a drag stays and ends the path: the
/// press previews no more, its piece stays as last shown, and the next click starts a new path.
#[test]
fn an_edit_to_another_object_during_a_drag_stays() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 50, "height": 50})).unwrap();
let rect = s.doc().unwrap().selection.objects[0];
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap();
s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#00ff00"})).unwrap();
let edited = s.doc().unwrap().doc.node(rect).unwrap().clone();
s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap();
assert_eq!(*s.doc().unwrap().doc.node(rect).unwrap(), edited, "the other object's edit stays");
let pen = paths(&s).into_iter().find(|(id, _)| *id != rect).unwrap().1;
let ends: Vec<Point> = pen.subpaths[0].anchors.iter().map(|a| a.p).collect();
assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(200.0, 200.0)], "the piece as last shown");
click(&mut s, 400.0, 400.0);
assert_eq!(paths(&s).len(), 3, "a new path");
}
/// With Real-time Drawing off, a drag during which another command edits the path adds no piece,
/// and the edit stays.
#[test]
fn an_edit_during_a_deferred_drag_stays() {
let mut s = session();
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let id = paths(&s)[0].0;
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap();
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 250.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap();
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
assert_eq!(ends, [pt(90.0, 90.0), pt(200.0, 100.0)], "the edit, and no piece");
}
/// An edit made by another command to another object during a click stays, and the path goes on:
/// a click previews its piece only when the press begins.
#[test]
fn an_edit_to_another_object_during_a_click_stays() {
let mut s = session();
s.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 50, "height": 50})).unwrap();
let rect = s.doc().unwrap().selection.objects[0];
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0), v).unwrap();
s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#00ff00"})).unwrap();
let edited = s.doc().unwrap().doc.node(rect).unwrap().clone();
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0), v).unwrap();
assert_eq!(*s.doc().unwrap().doc.node(rect).unwrap(), edited, "the other object's edit stays");
click(&mut s, 300.0, 200.0);
let all = paths(&s);
assert_eq!(all.len(), 2, "no new path");
let pen = all.into_iter().find(|(id, _)| *id != rect).unwrap().1;
let ends: Vec<Point> = pen.subpaths[0].anchors.iter().map(|a| a.p).collect();
assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(200.0, 200.0), pt(300.0, 200.0)]);
}
/// An edit made by another command during a click (a press let go where it went down) ends the
/// path too: the next click starts a new path instead of drawing over the edit.
#[test]
fn an_edit_during_a_click_ends_the_path() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let id = paths(&s)[0].0;
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap();
s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 180.0), v).unwrap();
click(&mut s, 400.0, 400.0);
assert_eq!(paths(&s).len(), 2, "a new path");
let ends: Vec<Point> = paths(&s)[0].1.subpaths[0].anchors.iter().map(|a| a.p).collect();
assert_eq!(ends, [pt(90.0, 90.0), pt(200.0, 100.0), pt(200.0, 180.0)], "the edit stays");
}
/// With Align New Objects to Pixel Grid on, the path the tool draws is pixel-aligned: its points
/// move onto the grid, and the next click and drag still go on drawing the same path.
#[test]
fn a_pixel_aligned_path_goes_on_drawing() {
let mut s = session();
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let ends = |s: &Session| only_path(s).anchors.iter().map(|a| a.p).collect::<Vec<Point>>();
let two = ends(&s);
assert_eq!(two.len(), 2);
assert_eq!(two[0].y, two[1].y, "a level line");
press(&mut s, &[(300.0, 150.0), (310.0, 170.0), (320.0, 200.0)]);
let three = ends(&s);
assert_eq!(three.len(), 3, "one path of three points");
assert_eq!(three[..2], two[..], "the points before the piece stay as they were");
assert!(three[2].distance(pt(320.0, 200.0)) <= 1.0, "the drag's piece ends near where it was let go: {:?}", three[2]);
click(&mut s, 400.0, 100.0);
let four = ends(&s);
assert_eq!(four.len(), 4);
assert_eq!(four[..3], three[..]);
}
/// A dropped press takes back only its own piece, and with Real-time Drawing off a drag places its
/// piece on the release: in both cases the next click goes on drawing the same path.
#[test]
fn a_dropped_press_and_a_deferred_drag_keep_the_path() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 320.0, 150.0), v).unwrap();
s.drop_tool_press(v).unwrap();
assert_eq!(only_path(&s).anchors.len(), 2, "the dropped piece is gone");
click(&mut s, 300.0, 200.0);
assert_eq!(only_path(&s).anchors.len(), 3, "the path goes on");
s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap();
press(&mut s, &[(400.0, 200.0), (420.0, 250.0), (450.0, 300.0)]);
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(450.0, 300.0));
click(&mut s, 500.0, 100.0);
assert_eq!(only_path(&s).anchors.len(), 5, "the path goes on after the deferred piece");
}
/// An anchor moved by another command ends the path being drawn: C does not flip the old arc back
/// over the edit, and the next click starts a new path instead of rebuilding the old one.
#[test]
+168
View File
@@ -133,6 +133,174 @@ fn colors_with_nothing_selected_leave_out_what_select_all_leaves_out() {
assert_eq!(hexes(&run(&mut s, "recolor.colors", json!({"ids": [hidden.0]}))), ["#0000ff"]);
}
#[test]
fn used_colors_list_the_most_used_first_with_their_colors() {
let mut s = session();
let reds: Vec<NodeId> = (0..3).map(|_| rect(&mut s, json!("#ff0000"))).collect();
let blue = rect(&mut s, json!({"c": 100, "m": 100, "y": 0, "k": 0}));
run(&mut s, "select.set", json!({"ids": []}));
let r = run(&mut s, "color.used", json!({}));
assert_eq!(r["selection"], false, "{r}");
let colors = r["colors"].as_array().unwrap();
assert_eq!(colors.len(), 2, "{r}");
assert_eq!((colors[0]["key"].as_str(), colors[0]["hex"].as_str(), colors[0]["count"].as_u64()), (Some("rgb 255 0 0"), Some("#ff0000"), Some(3)));
assert_eq!(colors[1]["count"], 1);
let first = run(&mut s, "color.used", json!({"limit": 1}));
assert_eq!(first["colors"], json!([colors[0]]), "`limit` keeps the most used");
assert_eq!((r["uses"].clone(), first["uses"].clone()), (json!(4), json!(4)), "`uses` counts every color");
// `color` is the color in its own model, which the paint commands take back.
assert_eq!(colors[1]["color"]["model"], "cmyk", "{r}");
assert!(close(color_value(&colors[1]["color"]).unwrap(), fill(&s, blue)));
// The selection's colors while something is selected; `selection: false` reads all the art.
run(&mut s, "select.set", json!({"ids": [blue.0]}));
let r = run(&mut s, "color.used", json!({}));
assert_eq!((r["selection"].clone(), r["colors"].as_array().unwrap().len()), (json!(true), 1), "{r}");
let all = run(&mut s, "color.used", json!({"selection": false}));
assert_eq!((all["selection"].clone(), all["colors"][0]["count"].clone()), (json!(false), json!(3)), "{all}");
assert_eq!(s.doc().unwrap().selection.objects, [blue], "the selection is left as it was");
// A hidden object's color is left out with nothing selected, as Select All leaves it out.
run(&mut s, "object.hide", json!({"ids": [reds[0].0]}));
assert_eq!(run(&mut s, "color.used", json!({"selection": false}))["colors"][0]["count"], 2);
let e = s.execute("color.used", &json!({"selection": "no"})).unwrap_err().to_string();
assert!(e.contains("`selection` must be true or false"), "{e}");
assert!(s.execute("color.used", &json!({"ids": [blue.0]})).is_err(), "an unknown key is refused");
}
#[test]
fn used_colors_name_the_swatch_and_tint_a_color_is_linked_to() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
let tinted = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [tinted.0], "swatch": "Ink", "tint": 40}));
run(&mut s, "select.set", json!({"ids": []}));
let r = run(&mut s, "color.used", json!({}));
let c = &r["colors"][0];
assert_eq!(c["swatch"].as_str(), Some("Ink"), "{r}");
assert!((c["tint"].as_f64().unwrap() - 40.0).abs() < 1e-4, "{r}");
// recolor.colors keeps its own fields.
assert_eq!(run(&mut s, "recolor.colors", json!({}))["colors"][0].get("tint"), None);
// A swatch of paper white looks the same at every tint; the tint comes from the paint.
run(&mut s, "swatch.new", json!({"name": "Paper", "color": {"c": 0, "m": 0, "y": 0, "k": 0}, "spot": true}));
let paper = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [paper.0], "swatch": "Paper", "tint": 33.333}));
run(&mut s, "select.set", json!({"ids": [paper.0]}));
let c = run(&mut s, "color.used", json!({}))["colors"][0].clone();
assert_eq!(c["swatch"].as_str(), Some("Paper"), "{c}");
// The tint is the paint's own, unrounded.
let vectorcraft_color::Paint::Solid { tint, .. } = s.doc().unwrap().doc.node(paper).unwrap().appearance.fill_paint() else {
panic!("a solid fill")
};
assert_eq!((c["tint"].as_f64().unwrap() / 100.0) as f32, tint, "{c}");
assert!((tint - 0.33333).abs() < 1e-5);
// A pattern's tile keeps its tint as well.
run(&mut s, "select.set", json!({"ids": [paper.0]}));
run(&mut s, "object.pattern.make", json!({"name": "Sheet", "width": 20, "height": 20}));
run(&mut s, "object.pattern.done", json!({}));
let filled = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [filled.0], "swatch": "Sheet"}));
run(&mut s, "select.set", json!({"ids": [filled.0]}));
let c = run(&mut s, "color.used", json!({}))["colors"][0].clone();
assert_eq!(c["swatch"].as_str(), Some("Paper"), "{c}");
assert_eq!((c["tint"].as_f64().unwrap() / 100.0) as f32, tint, "{c}");
}
#[test]
fn used_colors_read_the_tiles_of_patterns_used_inside_pattern_tiles() {
let mut s = session();
let red = rect(&mut s, json!("#ff0000"));
run(&mut s, "select.set", json!({"ids": [red.0]}));
run(&mut s, "object.pattern.make", json!({"name": "Inner", "width": 20, "height": 20}));
run(&mut s, "object.pattern.done", json!({}));
let middle = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [middle.0], "swatch": "Inner"}));
run(&mut s, "select.set", json!({"ids": [middle.0]}));
run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 20, "height": 20}));
run(&mut s, "object.pattern.done", json!({}));
let square = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [square.0], "swatch": "Outer"}));
// The inner tile's square is stroked with the outer pattern, so the two patterns use each other.
let outer = s.doc().unwrap().doc.node(square).unwrap().appearance.fill_paint().clone();
let st = s.doc_mut().unwrap();
let doc = std::sync::Arc::make_mut(&mut st.doc);
let tile = doc.pattern_mut("Inner").unwrap().art.first_mut().unwrap();
std::sync::Arc::make_mut(tile).appearance.set_stroke(outer);
run(&mut s, "select.set", json!({"ids": [square.0]}));
let r = run(&mut s, "color.used", json!({}));
let colors = r["colors"].as_array().unwrap();
assert_eq!(colors.iter().map(|c| (c["hex"].as_str(), c["count"].as_u64())).collect::<Vec<_>>(), [(Some("#ff0000"), Some(1))], "{r}");
}
#[test]
fn used_colors_give_no_swatch_for_a_stop_that_mixes_its_ink_with_process_inks() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint};
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
let shape = rect(&mut s, json!("#000000"));
let mixed = Color::Cmyk { c: 0.3, m: 0.5, y: 0.3, k: 0.0 };
let stop = |color, plates| GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates, ..GradientStop::new(0.0, color) };
let mut end = stop(Color::Cmyk { c: 0.0, m: 0.5, y: 0.3, k: 0.0 }, None);
end.offset = 1.0;
let g = Gradient::new(GradientKind::Linear, vec![stop(mixed, Some([0.3, 0.0, 0.0, 0.0])), end]);
let st = s.doc_mut().unwrap();
std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g))));
let r = run(&mut s, "color.used", json!({}));
let entry = |key: &str| r["colors"].as_array().unwrap().iter().find(|c| c["key"] == key).cloned().unwrap();
let mix = entry("cmyk 30 50 30 0");
assert_eq!((mix.get("swatch"), mix.get("tint")), (None, None), "{r}");
assert_eq!(entry("cmyk 0 50 30 0")["swatch"], "Ink", "{r}");
// recolor.colors keeps the swatch it lists.
let listed = run(&mut s, "recolor.colors", json!({}));
assert!(listed["colors"].as_array().unwrap().iter().all(|c| c["swatch"] == "Ink"), "{listed}");
}
#[test]
fn used_colors_take_the_swatch_of_a_plain_use_painted_after_a_mixed_stop_of_the_same_color() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint};
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
let shape = rect(&mut s, json!("#000000"));
let plain = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [plain.0], "swatch": "Ink", "tint": 50}));
let ink = fill(&s, plain);
// The stop below the plain fill has the same color, and process plates that add nothing.
let stop = GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates: Some([0.0; 4]), ..GradientStop::new(0.0, ink) };
let mut end = stop.clone();
end.offset = 1.0;
let g = Gradient::new(GradientKind::Linear, vec![stop, end]);
let st = s.doc_mut().unwrap();
std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g))));
run(&mut s, "select.set", json!({"ids": []}));
let r = run(&mut s, "color.used", json!({}));
let c = r["colors"].as_array().unwrap().iter().find(|c| c["count"] == 3).cloned().unwrap();
assert_eq!((c["swatch"].as_str(), c["tint"].as_f64()), (Some("Ink"), Some(50.0)), "{r}");
}
#[test]
fn recolor_colors_keeps_the_swatch_of_the_first_linked_use_when_a_mixed_stop_comes_first() {
use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint};
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
run(&mut s, "swatch.new", json!({"name": "Other", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true}));
let shape = rect(&mut s, json!("#000000"));
let plain = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [plain.0], "swatch": "Other", "tint": 50}));
let ink = fill(&s, plain);
// The stop below the plain fill has the same color, linked to another swatch, with process
// plates that add nothing.
let stop = GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates: Some([0.0; 4]), ..GradientStop::new(0.0, ink) };
let mut end = stop.clone();
end.offset = 1.0;
let g = Gradient::new(GradientKind::Linear, vec![stop, end]);
let st = s.doc_mut().unwrap();
std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g))));
run(&mut s, "select.set", json!({"ids": []}));
let three = |r: &Value| r["colors"].as_array().unwrap().iter().find(|c| c["count"] == 3).cloned().unwrap();
let used = run(&mut s, "color.used", json!({}));
assert_eq!(three(&used)["swatch"], "Other", "{used}");
let listed = run(&mut s, "recolor.colors", json!({}));
assert_eq!(three(&listed)["swatch"], "Ink", "recolor.colors names the first linked use: {listed}");
}
#[test]
fn colors_with_nothing_selected_leave_out_hidden_and_locked_objects_in_groups() {
let mut s = session();
+34 -1
View File
@@ -84,7 +84,7 @@ fn the_builtin_library_is_original_art_generated_in_code() {
let mut s = Session::new();
let list = run(&mut s, "symbol.libraries", json!({}));
let libs = list["libraries"].as_array().unwrap();
assert_eq!(libs.len(), 7, "{libs:?}");
assert_eq!(libs.len(), 8, "{libs:?}");
assert_eq!((libs[0]["id"].as_str(), libs[0]["category"].as_str()), (Some("basic-shapes"), Some("builtIn")));
assert_eq!(
(libs[1]["id"].as_str(), libs[1]["name"].as_str(), libs[1]["category"].as_str()),
@@ -108,6 +108,10 @@ fn the_builtin_library_is_original_art_generated_in_code() {
);
assert_eq!(
(libs[6]["id"].as_str(), libs[6]["name"].as_str(), libs[6]["category"].as_str()),
(Some("nature-icons"), Some("Nature Icons"), Some("builtIn"))
);
assert_eq!(
(libs[7]["id"].as_str(), libs[7]["name"].as_str(), libs[7]["category"].as_str()),
(Some("media-controls"), Some("Media Controls"), Some("builtIn"))
);
let lib = run(&mut s, "symbol.library", json!({"library": "basic shapes"}));
@@ -249,6 +253,35 @@ fn weather_icons_library_lists_and_places() {
}
}
#[test]
fn nature_icons_library_places_and_survives_save() {
let mut s = session();
let listed = run(&mut s, "symbol.libraries", json!({}));
let entry = listed["libraries"].as_array().unwrap().iter().find(|l| l["id"] == "nature-icons").unwrap();
assert_eq!((entry["name"].as_str(), entry["count"].as_u64()), (Some("Nature Icons"), Some(5)));
let library = run(&mut s, "symbol.library", json!({"library": "nature-icons"}));
let names: Vec<&str> = library["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap()).collect();
assert_eq!(names, ["Leaf", "Flower", "Tree", "Mountain", "Wave"]);
for (i, name) in names.iter().enumerate() {
let symbol = &library["symbols"][i];
let size = symbol["size"].as_array().unwrap();
assert!(size.iter().all(|n| n.as_f64().is_some_and(|n| n.is_finite() && n > 0.0)), "{name}");
let added = run(
&mut s,
"symbol.addFromLibrary",
json!({"library": "nature-icons", "name": name, "place": true, "x": 100.0 + 80.0 * i as f64, "y": 100.0}),
);
assert_eq!(added["added"], json!([name]));
let id = NodeId(added["placed"].as_u64().unwrap());
assert!(matches!(doc(&s).node(id).map(|n| &n.kind), Some(NodeKind::SymbolInstance { symbol, .. }) if symbol == *name));
assert_eq!(doc(&s).symbol_nine_slice(name), None);
}
let saved = run(&mut s, "symbol.saveLibrary", json!({"names": ["Leaf", "Flower", "Tree", "Mountain", "Wave"]}));
let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap();
let reopened = vectorcraft_format::load(&bytes).unwrap();
assert_eq!(reopened.symbols.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), names);
}
#[test]
fn media_controls_library_lists_and_places() {
let mut s = session();
+15
View File
@@ -856,6 +856,12 @@ impl Session {
self.ruler_origin = None;
}
/// A guide is being dragged out of a ruler ([`Session::ruler_guide`]): its first event came
/// and its release has not.
pub fn ruler_guide_dragging(&self) -> bool {
self.ruler_guide.is_some()
}
/// Time passed while the pointer button is held (`dt` seconds; see [`Tool::tick`]): the
/// desktop app ticks every frame of a press, agents with `holdMs` on a pointer event.
pub fn tool_tick(&mut self, dt: f64, view: ViewInfo) -> Result<Vec<UiRequest>> {
@@ -1256,6 +1262,12 @@ impl Session {
self.with_tool_cx(view, |t, cx| t.ends_on_escape(cx))
}
/// The point a path the active tool is drawing goes on from, and the direction the path
/// arrives there in (see `Tool::drawing_end`).
pub fn tool_drawing_end(&mut self, view: ViewInfo) -> Option<(Point, Option<vectorcraft_geom::Vec2>)> {
self.with_tool_cx(view, |t, cx| t.drawing_end(cx))
}
pub fn overlays(&mut self, view: ViewInfo) -> Vec<Overlay> {
// The Blend tool's first pick is not marked after an edit that dropped it.
self.tell_tool_history_moved();
@@ -1478,6 +1490,9 @@ impl Session {
}
// Every value is checked before any is set, so an invalid one changes nothing.
vectorcraft_tools::builder::check_builder_options(id, &values)?;
if id == vectorcraft_tools::circle::ID {
vectorcraft_tools::circle::check_options(&values)?;
}
vectorcraft_tools::symbolism::check_options(id, &values)?;
if id == vectorcraft_tools::cropimage::ID {
use vectorcraft_tools::cropimage as crop;
+8 -20
View File
@@ -3,8 +3,6 @@
//! Format Specification, version 7.0, §5.3, §5.4 and §6), and the colors they write in place of
//! the paint they can't hold.
use std::fmt::Write;
use vectorcraft_color::{Color, Gradient};
use vectorcraft_doc::{LAYER_COLORS, LayerColor, LineCap, LineJoin, StrokeLayer};
use vectorcraft_geom::{Affine, Anchor, AnchorKind, PathData, Point, Shape, SubPath};
@@ -184,25 +182,15 @@ pub(crate) fn window_samples(samples: &[u8], w: u32, channels: usize, [x0, y0, x
/// The stroke's width, cap, join, miter limit and dashes: `w J j M d`.
pub(crate) fn line_style(s: &mut String, st: &StrokeLayer) {
let cap = match st.cap {
LineCap::Butt => 0,
LineCap::Round => 1,
LineCap::Square => 2,
LineCap::Butt => ps::LineCap::Butt,
LineCap::Round => ps::LineCap::Round,
LineCap::Square => ps::LineCap::Square,
};
let join = match st.join {
LineJoin::Miter => 0,
LineJoin::Round => 1,
LineJoin::Bevel => 2,
LineJoin::Miter => ps::LineJoin::Miter,
LineJoin::Round => ps::LineJoin::Round,
LineJoin::Bevel => ps::LineJoin::Bevel,
};
ps::push_num(s, st.width);
let _ = write!(s, " w {cap} J {join} j ");
ps::push_num(s, if st.miter_limit.is_finite() { st.miter_limit.max(1.0) } else { 10.0 });
s.push_str(" M [");
let dash = st.dash.as_ref().filter(|d| d.is_dashed());
if let Some(d) = dash {
ps::push_nums(s, &d.pattern);
s.pop();
}
s.push_str("] ");
ps::push_num(s, dash.map_or(0.0, |d| d.offset));
s.push_str(" d\n");
let dash = st.dash.as_ref().filter(|d| d.is_dashed()).map(|d| (d.pattern.as_slice(), d.offset));
ps::push_line_style(s, st.width, cap, join, st.miter_limit, dash);
}
+60 -298
View File
@@ -1,253 +1,17 @@
//! The scanner: PostScript source into objects (numbers, names, strings, procedures), with the
//! position the program's own data (`currentfile`) is read from.
//!
//! Backed by `craft_ps::read::lex`.
use std::rc::Rc;
use craft_ps::read::lex::{LexError, Number, Token};
use super::obj::{Obj, PsError, Res};
use crate::ps;
/// Deepest procedure nesting the scanner reads.
const MAX_NESTING: usize = 256;
pub(crate) use craft_ps::read::lex::{IMMEDIATE, hex_decode};
pub(crate) struct Lexer<'a> {
src: &'a [u8],
pos: usize,
/// The whitespace character that ended the last token is still unread (data the program
/// reads from itself starts after it).
fresh: bool,
/// The last object read has immediately evaluated names (`//name`) in it, read as executable
/// names starting with [`IMMEDIATE`] for the interpreter to replace by their values.
pub immediate: bool,
}
/// How an immediately evaluated name (`//name`) is read, until the interpreter replaces it.
pub(crate) const IMMEDIATE: &str = "//";
fn is_space(b: u8) -> bool {
matches!(b, b' ' | b'\t' | b'\r' | b'\n' | b'\x0c' | b'\0')
}
fn is_delim(b: u8) -> bool {
matches!(b, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%')
}
fn syntax<T>(what: &str) -> Res<T> {
Err(PsError::Ps("syntaxerror", what.to_string()))
}
impl<'a> Lexer<'a> {
pub fn new(src: &'a [u8]) -> Self {
Self { src, pos: 0, fresh: false, immediate: false }
}
/// What is left to read.
pub fn rest(&self) -> &'a [u8] {
self.src.get(self.pos..).unwrap_or_default()
}
/// What is left to read as data: after the whitespace that ended the last token (a CR LF
/// pair counts as one).
pub fn data(&mut self) -> &'a [u8] {
if std::mem::take(&mut self.fresh) {
match self.peek() {
Some(b'\r') => {
self.pos += 1;
if self.peek() == Some(b'\n') {
self.pos += 1;
}
}
Some(b) if is_space(b) => self.pos += 1,
_ => {}
}
}
self.rest()
}
/// Skip `n` bytes (the data a filter or `readstring` took).
pub fn advance(&mut self, n: usize) {
self.fresh = false;
self.pos = self.pos.saturating_add(n).min(self.src.len());
}
fn peek(&self) -> Option<u8> {
self.src.get(self.pos).copied()
}
fn skip_space(&mut self) {
while let Some(b) = self.peek() {
if is_space(b) {
self.pos += 1;
} else if b == b'%' {
while let Some(c) = self.peek() {
if c == b'\n' || c == b'\r' {
break;
}
self.pos += 1;
}
} else {
break;
}
}
}
/// The next object at the top level (`None` at the end of the file).
pub fn next(&mut self) -> Res<Option<Obj>> {
self.immediate = false;
let t = self.token(0);
self.fresh = true;
t
}
fn token(&mut self, depth: usize) -> Res<Option<Obj>> {
self.skip_space();
let Some(b) = self.peek() else { return Ok(None) };
self.pos += 1;
Ok(Some(match b {
b'(' => Obj::string(self.string()?),
b'<' => match self.peek() {
Some(b'<') => {
self.pos += 1;
Obj::Exec(Rc::from("<<"))
}
Some(b'~') => {
self.pos += 1;
Obj::string(self.ascii85()?)
}
_ => Obj::string(self.hex()?),
},
b'>' => {
if self.peek() != Some(b'>') {
return syntax(">");
}
self.pos += 1;
Obj::Exec(Rc::from(">>"))
}
b'[' => Obj::Exec(Rc::from("[")),
b']' => Obj::Exec(Rc::from("]")),
b'{' => {
if depth >= MAX_NESTING {
return Err(PsError::Limit("procedures nested too deeply"));
}
let mut items = vec![];
loop {
self.skip_space();
match self.peek() {
None => return syntax("{"),
Some(b'}') => {
self.pos += 1;
break;
}
_ => match self.token(depth + 1)? {
Some(o) => items.push(o),
None => return syntax("{"),
},
}
}
Obj::proc(items)
}
b'}' | b')' => return syntax(&char::from(b).to_string()),
b'/' => {
// `//name` stands for the name's value when it is read.
let immediate = self.peek() == Some(b'/');
if immediate {
self.pos += 1;
self.immediate = true;
}
let name = self.word();
if immediate { Obj::Exec(Rc::from(format!("{IMMEDIATE}{name}").as_str())) } else { Obj::Name(Rc::from(name.as_str())) }
}
_ => {
self.pos -= 1;
let w = self.word();
number(&w).unwrap_or_else(|| Obj::Exec(Rc::from(w.as_str())))
}
}))
}
/// A regular token's characters.
fn word(&mut self) -> String {
let start = self.pos;
while let Some(b) = self.peek() {
if is_space(b) || is_delim(b) {
break;
}
self.pos += 1;
}
String::from_utf8_lossy(self.src.get(start..self.pos).unwrap_or_default()).into_owned()
}
/// A literal string after its `(`.
fn string(&mut self) -> Res<Vec<u8>> {
let mut out = vec![];
let mut depth = 0usize;
loop {
let Some(b) = self.peek() else { return syntax("(") };
self.pos += 1;
match b {
b'(' => {
depth += 1;
out.push(b);
}
b')' if depth == 0 => return Ok(out),
b')' => {
depth -= 1;
out.push(b);
}
b'\\' => {
let Some(e) = self.peek() else { return syntax("(") };
self.pos += 1;
match e {
b'n' => out.push(b'\n'),
b'r' => out.push(b'\r'),
b't' => out.push(b'\t'),
b'b' => out.push(8),
b'f' => out.push(12),
b'\r' => {
if self.peek() == Some(b'\n') {
self.pos += 1;
}
}
b'\n' => {}
b'0'..=b'7' => {
let mut v = u32::from(e - b'0');
for _ in 0..2 {
match self.peek() {
Some(d @ b'0'..=b'7') => {
v = v * 8 + u32::from(d - b'0');
self.pos += 1;
}
_ => break,
}
}
out.push((v & 0xff) as u8);
}
other => out.push(other),
}
}
_ => out.push(b),
}
}
}
/// A hexadecimal string after its `<`.
fn hex(&mut self) -> Res<Vec<u8>> {
let end = self.rest().iter().position(|b| *b == b'>').ok_or(PsError::Ps("syntaxerror", "<".into()))?;
let body = self.rest().get(..end).unwrap_or_default();
let out = hex_decode(body).ok_or(PsError::Ps("syntaxerror", "<".into()))?;
self.advance(end + 1);
Ok(out)
}
/// An ASCII85 string after its `<~`.
fn ascii85(&mut self) -> Res<Vec<u8>> {
let end = find(self.rest(), b"~>").ok_or(PsError::Ps("syntaxerror", "<~".into()))?;
let text = String::from_utf8_lossy(self.rest().get(..end + 2).unwrap_or_default()).into_owned();
self.advance(end + 2);
ps::ascii85_decode(&text).ok_or(PsError::Ps("syntaxerror", "<~".into()))
}
}
/// Where `needle` first starts in `hay`.
/// Where `needle` first starts in `hay` (uses `memmem` so large inputs stay linear-time).
pub(crate) fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
if needle.is_empty() {
return Some(0);
@@ -255,39 +19,66 @@ pub(crate) fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
memchr::memmem::find(hay, needle)
}
/// Hexadecimal digits (whitespace ignored, an odd last digit padded with 0); `None` on others.
pub(crate) fn hex_decode(body: &[u8]) -> Option<Vec<u8>> {
// Callers pass an already-delimited body. Do not let the filter decoder's EOD
// handling silently accept a stray terminator or discard bytes after it.
if body.contains(&b'>') {
return None;
pub(crate) struct Lexer<'a> {
inner: craft_ps::read::lex::Lexer<'a>,
/// The last object read has immediately evaluated names (`//name`) in it, read as executable
/// names starting with [`IMMEDIATE`] for the interpreter to replace by their values.
pub immediate: bool,
}
impl<'a> Lexer<'a> {
pub fn new(src: &'a [u8]) -> Self {
Self { inner: craft_ps::read::lex::Lexer::new(src), immediate: false }
}
/// What is left to read.
pub fn rest(&self) -> &'a [u8] {
self.inner.rest()
}
/// What is left to read as data: after the whitespace that ended the last token (a CR LF
/// pair counts as one).
pub fn data(&mut self) -> &'a [u8] {
self.inner.data()
}
/// Skip `n` bytes (the data a filter or `readstring` took).
pub fn advance(&mut self, n: usize) {
self.inner.advance(n);
}
/// The next object at the top level (`None` at the end of the file).
pub fn next(&mut self) -> Res<Option<Obj>> {
let res = self.inner.next().map(|opt| opt.map(into_obj)).map_err(into_err);
self.immediate = self.inner.immediate;
res
}
}
fn into_err(err: LexError) -> PsError {
match err {
LexError::Syntax(what) => PsError::Ps("syntaxerror", what),
LexError::Limit(msg) => PsError::Limit(msg),
}
}
fn into_obj(tok: Token) -> Obj {
match tok {
Token::Int(i) => Obj::Int(i),
Token::Real(r) => Obj::Real(r),
Token::Name(n) => Obj::Name(Rc::from(n.as_str())),
Token::Exec(n) => Obj::Exec(Rc::from(n.as_str())),
Token::Str(s) => Obj::string(s),
Token::Proc(items) => Obj::proc(items.into_iter().map(into_obj).collect()),
}
craft_stream_codecs::asciihex::decode(body, body.len().div_ceil(2)).ok()
}
/// A number token (`12`, `-3.5`, `.5`, `1e-3`, `16#ff`), or `None`.
pub(crate) fn number(w: &str) -> Option<Obj> {
let first = w.bytes().next()?;
if !(first.is_ascii_digit() || matches!(first, b'+' | b'-' | b'.')) {
return None;
match craft_ps::read::lex::number(w)? {
Number::Int(i) => Some(Obj::Int(i)),
Number::Real(r) => Some(Obj::Real(r)),
}
if let Ok(i) = w.parse::<i64>() {
return Some(Obj::Int(i));
}
if let Some((base, digits)) = w.split_once('#') {
let base: u32 = base.parse().ok().filter(|b| (2..=36).contains(b))?;
// `from_str_radix` accepts a leading sign; a PostScript radix number has digits only.
if digits.starts_with(['+', '-']) {
return None;
}
return i64::from_str_radix(digits, base).ok().map(Obj::Int);
}
// Rust reads `inf` and `nan`; PostScript doesn't.
if w.bytes().any(|b| b.is_ascii_alphabetic() && !matches!(b, b'e' | b'E')) {
return None;
}
let v: f64 = w.parse().ok()?;
v.is_finite().then_some(Obj::Real(v))
}
#[cfg(test)]
@@ -300,33 +91,4 @@ mod tests {
assert!(number("16#-ff").is_none());
assert!(matches!(number("16#ff"), Some(Obj::Int(255))));
}
#[test]
fn shared_hex_decode_keeps_body_boundaries_and_odd_nibbles() {
assert_eq!(hex_decode(b" 4\t1\n4\r2\x0c4\0"), Some(vec![0x41, 0x42, 0x40]));
assert_eq!(hex_decode(b""), Some(vec![]));
for invalid in [b"41>42".as_slice(), b">", b"4g", b"4\x0b1", b"\xff"] {
assert_eq!(hex_decode(invalid), None);
}
// Every byte pairs with each possible nibble, including all whitespace
// and invalid-byte combinations; this is the former body-only contract.
for first in 0..=255u8 {
for second in 0..=255u8 {
let input = [first, second];
let mut digits = Vec::new();
let mut valid = true;
for b in input {
if is_space(b) {
continue;
}
match char::from(b).to_digit(16) {
Some(d) => digits.push(d as u8),
None => valid = false,
}
}
let expected =
if !valid { None } else { Some(digits.chunks(2).map(|pair| (pair[0] << 4) | pair.get(1).copied().unwrap_or(0)).collect()) };
assert_eq!(hex_decode(&input), expected, "{input:?}");
}
}
}
}
+31 -36
View File
@@ -5,9 +5,6 @@
use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind};
use vectorcraft_geom::{Affine, Rect};
/// Largest EPSI bitmap side read (pixels).
const MAX_EPSI: usize = 8192;
/// A preview's document and how the user is told about it.
pub(super) struct Preview {
pub document: Document,
@@ -89,41 +86,39 @@ fn metafile_doc(wmf: &[u8], frame: Rect) -> Option<Document> {
/// The EPSI preview in `ps`'s comments (`%%BeginPreview: width height depth lines`, hex rows,
/// 0 white and the largest value black).
/// The shared decoder intentionally tolerates blank preview lines and CR-only line endings;
/// unlike the former local parser, neither changes the decoded samples.
fn epsi(ps: &[u8]) -> Option<image::RgbaImage> {
let text = String::from_utf8_lossy(ps);
let mut lines = text.lines();
let head = lines.find_map(|l| l.strip_prefix("%%BeginPreview:"))?;
let n: Vec<usize> = head.split_whitespace().map_while(|w| w.parse().ok()).collect();
let [w, h, depth, ..] = n[..] else { return None };
if !(1..=MAX_EPSI).contains(&w) || !(1..=MAX_EPSI).contains(&h) || ![1, 2, 4, 8].contains(&depth) {
return None;
let bitmap = craft_eps::epsi(ps)?;
let rgba = bitmap.gray.into_iter().flat_map(|g| [g, g, g, 255]).collect();
image::RgbaImage::from_raw(bitmap.width, bitmap.height, rgba)
}
#[cfg(test)]
mod tests {
use super::epsi;
#[test]
fn shared_epsi_depths_keep_row_padding_and_opaque_grayscale() {
for (depth, row, gray) in [(1, "40", [255, 0, 255]), (2, "18", [255, 170, 85]), (4, "05a0", [255, 170, 85]), (8, "0055aa", [255, 170, 85])] {
let source = format!("%%BeginPreview: 3 2 {depth} 2\n% {row}\n% {row}\n%%EndPreview\n");
let image = epsi(source.as_bytes()).expect("ordinary EPSI preview");
assert_eq!(image.dimensions(), (3, 2));
let expected: Vec<u8> = gray.into_iter().cycle().take(6).flat_map(|g| [g, g, g, 255]).collect();
assert_eq!(image.as_raw(), &expected, "depth {depth}");
}
}
let row = (w * depth).div_ceil(8);
let mut hex = Vec::with_capacity((row * h * 2).min(ps.len()));
for l in lines {
if l.starts_with("%%EndPreview") || hex.len() >= row * h * 2 {
break;
#[test]
fn shared_epsi_intentionally_accepts_blank_and_cr_only_lines() {
let ordinary = "%%BeginPreview: 3 2 2 2\n% 18\n% e4\n%%EndPreview\n";
let expected = epsi(ordinary.as_bytes()).expect("ordinary preview");
for source in [ordinary.replace('\n', "\r"), ordinary.replace("% e4", "\n% e4")] {
let image = epsi(source.as_bytes()).expect("documented shared decoder tolerance");
assert_eq!(image, expected);
}
hex.extend(l.strip_prefix('%')?.bytes().filter(u8::is_ascii_hexdigit));
}
hex.truncate(row * h * 2);
// A trailing half byte would decode padded with zero: the preview is cut short, so none.
if hex.len() % 2 != 0 {
return None;
}
let bytes = super::lex::hex_decode(&hex)?;
// A preview with its samples missing is none, not a blank image of the size it claims.
if bytes.len() < row * h {
return None;
}
let max = (1u32 << depth) - 1;
let mut img = image::RgbaImage::new(w as u32, h as u32);
for (x, y, px) in img.enumerate_pixels_mut() {
let bit = y as usize * row * 8 + x as usize * depth;
let byte = u32::from(bytes.get(bit / 8).copied().unwrap_or(0));
let v = (byte >> (8 - depth - bit % 8)) & max;
let grey = (255 - v * 255 / max) as u8;
*px = image::Rgba([grey, grey, grey, 255]);
let gray = [255, 170, 85, 0, 85, 170];
let rgba: Vec<u8> = gray.into_iter().flat_map(|g| [g, g, g, 255]).collect();
assert_eq!(expected.as_raw(), &rgba);
}
Some(img)
}
+30 -1
View File
@@ -3,7 +3,10 @@
use vectorcraft_geom::{BezPath, FillRule};
pub(crate) use craft_ps::write::{bytes, deflate, inflate, matrix, num, push_num, push_num_places, push_nums, string, written};
pub(crate) use craft_ps::write::{
LineCap, LineJoin, ShadingKind, bytes, deflate, inflate, matrix, num, push_image_array_ref, push_inline_image, push_line_style, push_num,
push_num_places, push_nums, push_reusable_image_ref, push_reusable_image_resource, push_shading, string, written,
};
/// The procedures the page uses, in `VCdict`.
pub(crate) const PROLOG: &str = "/VCdict 64 dict def
@@ -121,4 +124,30 @@ mod tests {
assert_eq!(places(2.5, 7), "2.5");
assert_eq!(places(f64::NAN, 7), "0");
}
#[test]
fn shared_scene_syntax_preserves_vc_names_and_shading() {
let mut line = String::new();
super::push_line_style(&mut line, 3.0, super::LineCap::Square, super::LineJoin::Round, 4.0, Some((&[5.0, 1.5], 0.5)));
assert_eq!(line, "3 w 2 J 1 j 4 M [5 1.5] 0.5 d\n");
let mut shading = String::new();
super::push_shading(
&mut shading,
super::ShadingKind::Axial,
"/DeviceCMYK",
&[0.0, 0.0, 100.0, 0.0],
4,
&[(0.0, vec![0.0, 1.0, 1.0, 0.0]), (1.0, vec![1.0, 0.0, 1.0, 0.0])],
);
assert!(shading.contains("/ShadingType 2 /ColorSpace /DeviceCMYK"));
assert!(shading.ends_with(">> shfill\n"));
let mut inline = String::new();
super::push_inline_image(&mut inline, "VCsrc", "", "<< /ImageType 1", "/FlateDecode", "image", "~>\n");
assert_eq!(
inline,
"{ /VCsrc currentfile /ASCII85Decode filter def\n<< /ImageType 1\n/DataSource VCsrc /FlateDecode filter >> image\nVCsrc flushfile } exec\n~>\n"
);
}
}
+12 -63
View File
@@ -50,8 +50,6 @@ const SPREAD_CAPPED: &str =
"gradients that repeat or reflect are written with at most 256 runs of their stops (at most 16384 stops); they pad past those";
/// Wedges a conic gradient is written as: one a degree.
const CONIC_WEDGE_COUNT: usize = 360;
/// Decimals of a smooth shading's stitching function bounds (stop offsets, 0 to 1).
const BOUNDS_PLACES: u32 = 7;
/// The most colorants a DeviceN color space may have (PostScript's limit).
const MAX_DEVICE_N: usize = 32;
const MISSING_PATTERN: &str = "missing patterns are written as mid-grey";
@@ -63,8 +61,6 @@ const MAX_BODY: usize = 256 << 20;
/// Most compressed bytes in one string of an image's samples at Level 2 (under PostScript's
/// 65,535-byte string limit).
const IMAGE_CHUNK: usize = 48 << 10;
/// The start of the procedure that reads an image's data from the lines after it.
const INLINE_SOURCE: &str = "{ /VCsrc currentfile /ASCII85Decode filter def\n";
/// An image as written: what sets up its color, its image dictionary and its compressed samples.
/// Placed once, it is written where it is drawn, its data following the operators that read it.
@@ -108,33 +104,20 @@ impl ImageCode {
/// The operators and data that draw the image where it is placed.
fn push_inline(&self, s: &mut String) {
s.push_str(&self.prelude);
s.push_str(INLINE_SOURCE);
s.push_str(&self.dict);
s.push_str(&self.inline_read());
s.push_str(&self.ascii);
}
/// The end of the procedure [`ImageCode::push_inline`] writes. The procedure is read whole
/// before it runs: the image data follows it, and flushing the ASCII85 filter afterwards reads
/// past its end marker.
fn inline_read(&self) -> String {
format!("\n/DataSource VCsrc {} filter >> {}\nVCsrc flushfile }} exec\n", self.filter, self.op)
ps::push_inline_image(s, "VCsrc", &self.prelude, &self.dict, self.filter, self.op, &self.ascii);
}
/// The operators that draw the image `VCim<i>` holds, for an image placed more than once.
fn reference(&self, i: usize, level: Level) -> String {
let mut s = String::new();
let name = format!("VCim{i}");
match level {
// The stream is read again from its start.
Level::Three => {
format!("{}VCim{i} resetfile\n{}\n/DataSource VCim{i} {} filter >> {}\n", self.prelude, self.dict, self.filter, self.op)
}
Level::Three => ps::push_reusable_image_ref(&mut s, &name, &self.prelude, &self.dict, self.filter, self.op),
// A procedure gives the strings in turn, then an empty string: the end of the data.
Level::Two => format!(
"{}/VCi 0 def\n{}\n/DataSource {{VCi VCim{i} length lt {{VCim{i} VCi get /VCi VCi 1 add def}} {{()}} ifelse}} {} filter >> {}\n",
self.prelude, self.dict, self.filter, self.op
),
Level::Two => ps::push_image_array_ref(&mut s, "VCi", &name, &self.prelude, &self.dict, self.filter, self.op),
}
s
}
/// The setup's definition of `VCim<i>`: the image's compressed samples, once.
@@ -145,11 +128,7 @@ impl ImageCode {
// The stream reads all of its data when it is made, so the data follows the
// procedure that makes it.
let intent = if self.op == "imagemask" { 1 } else { 0 };
let _ = writeln!(
s,
"{{ /VCsrc currentfile /ASCII85Decode filter def\n/VCim{i} VCsrc << /Intent {intent} /AsyncRead false /CloseSource false >> /ReusableStreamDecode filter def\nVCsrc flushfile }} exec"
);
s.push_str(&self.ascii);
ps::push_reusable_image_resource(&mut s, "VCsrc", &format!("VCim{i}"), intent, &self.ascii);
}
Level::Two => {
let _ = writeln!(s, "/VCim{i} [");
@@ -1489,44 +1468,12 @@ impl<'a> Scene<'a> {
/// A Level 3 smooth shading of `kind` (2 axial, 3 radial) at `coords`, extended both ways.
fn shading(&mut self, kind: u8, space: &GradientSpace, coords: &[f64], stops: &[(f64, Vec<f32>)]) {
let n = space.n();
let comps = |c: &[f32]| -> String {
let mut s = String::from("[");
push_nums(&mut s, &c.iter().take(n).map(|v| f64::from(*v)).collect::<Vec<_>>());
s.pop();
s.push(']');
s
};
let segments: Vec<_> = stops.windows(2).filter(|w| w[1].0 > w[0].0).collect();
let interp = |w: &&[(f64, Vec<f32>)]| format!("<< /FunctionType 2 /Domain [0 1] /C0 {} /C1 {} /N 1 >>", comps(&w[0].1), comps(&w[1].1));
let function = match segments.as_slice() {
[one] => interp(one),
many => {
let mut f = String::from("<< /FunctionType 3 /Domain [0 1] /Functions [\n");
for w in many {
f.push_str(&interp(w));
f.push('\n');
}
f.push_str("] /Bounds [");
// Seven decimals: a gradient's stops repeated hundreds or thousands of times
// (`Gradient::padded_over`) keep their places in each run.
for w in many.iter().skip(1) {
ps::push_num_places(&mut f, w[0].0, BOUNDS_PLACES);
f.push(' ');
}
f.push_str("] /Encode [");
f.push_str(&"0 1 ".repeat(many.len()));
f.push_str("] >>");
f
}
};
let kind = if kind == 3 { ps::ShadingKind::Radial } else { ps::ShadingKind::Axial };
let name = match space {
GradientSpace::Process(s) => s.name(),
GradientSpace::Inks(name, _) => name,
};
let _ = write!(self.body, "<< /ShadingType {kind} /ColorSpace {name} /Coords [");
push_nums(&mut self.body, coords);
let _ = writeln!(self.body, "] /Extend [true true]\n/Function {function} >> shfill");
ps::push_shading(&mut self.body, kind, name, coords, space.n(), stops);
}
/// The bands of each stretch between stops: how many, for colours `a` to `b` over `length`
@@ -2090,7 +2037,9 @@ impl<'a> Scene<'a> {
/// `data`, not yet placed.
fn image_code(prelude: String, dict: String, filter: &'static str, op: &'static str, data: Vec<u8>) -> ImageCode {
let mut code = ImageCode { prelude, dict, filter, op, ascii: ps::ascii85(&data), data, uses: 0, inline_len: 0, ref_len: 0 };
code.inline_len = code.prelude.len() + INLINE_SOURCE.len() + code.dict.len() + code.inline_read().len() + code.ascii.len();
let mut inline = String::new();
ps::push_inline_image(&mut inline, "VCsrc", &code.prelude, &code.dict, code.filter, code.op, "");
code.inline_len = inline.len() + code.ascii.len();
code
}
+102
View File
@@ -367,6 +367,61 @@ pub fn circle_through_points(points: &[Point]) -> Option<(Point, f64)> {
circle.filter(|(c, r)| c.is_finite() && r.is_finite() && *r > 0.0)
}
/// The circle at `center` with `radius` as a closed path whose anchors are `points` (points on the
/// circle, as [`circle_through_points`] gives it) plus as many more as split each arc between two
/// of them into equal parts of at most a quarter turn. The path starts at the first point and runs
/// as [`ellipse`] does (left, top, right on the page); each curve's handles are 4/3·tan(θ/4) of
/// the radius along the tangents at its ends (θ, its turn). Two points with `center` at their
/// midpoint give four anchors. A point given twice is one anchor; with no points it starts at the
/// left, as [`ellipse`] does.
pub fn circle_with_anchors_at(center: Point, radius: f64, points: &[Point]) -> PathData {
let quarter = PI / 2.0;
let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x);
let start = points.first().map_or(PI, |p| angle(*p));
// (turn from the first point, the point itself).
let mut placed: Vec<(f64, Point)> = points.iter().map(|p| ((angle(*p) - start).rem_euclid(TAU), *p)).collect();
placed.sort_by(|a, b| a.0.total_cmp(&b.0));
placed.dedup_by(|a, b| a.1 == b.1);
// Two points with the center at their midpoint are the ends of a diameter: the second is half a
// turn from the first, also where rounding moves the angle from the center off it.
if let [(_, a), (turn, b)] = placed.as_mut_slice()
&& a.midpoint(*b) == center
{
*turn = PI;
}
if placed.is_empty() {
placed.push((0.0, Point::new(center.x - radius, center.y)));
}
let on_circle = |t: f64| Point::new(center.x + radius * (start + t).cos(), center.y + radius * (start + t).sin());
// Every anchor: (turn, position), the given points where they are and the others on the circle.
let mut turns: Vec<(f64, Point)> = Vec::new();
for (i, &(t, p)) in placed.iter().enumerate() {
turns.push((t, p));
let next = placed.get(i + 1).map_or(TAU, |n| n.0);
let gap = next - t;
// At most 4 parts for the whole turn: a gap is never more than a full turn.
let parts = (gap / quarter - 1e-9).ceil().clamp(1.0, 4.0);
for k in 1..parts as u32 {
let tk = t + gap * f64::from(k) / parts;
turns.push((tk, on_circle(tk)));
}
}
let n = turns.len();
let anchors = (0..n)
.filter_map(|i| {
let &(t, p) = turns.get(i)?;
let prev = if i == 0 { turns.last()?.0 - TAU } else { turns.get(i - 1)?.0 };
let next = turns.get(i + 1).map_or(TAU, |n| n.0);
// The unit tangent along the run (y down: increasing angle).
let a = start + t;
let tangent = Vec2::new(-a.sin(), a.cos());
let handle = |turn: f64| radius * 4.0 / 3.0 * (turn / 4.0).tan();
Some(Anchor { p, h_in: p - tangent * handle(t - prev), h_out: p + tangent * handle(next - t), kind: AnchorKind::Smooth })
})
.collect();
PathData::single(SubPath::new(anchors, true))
}
/// Regular polygon with `sides` (≥ 3), first vertex straight up from the centre.
pub fn polygon(center: Point, radius: f64, sides: u32, rotation_deg: f64) -> PathData {
let n = sides.max(3);
@@ -1146,6 +1201,53 @@ mod tests {
}
}
/// The anchors are the given points exactly, plus enough more that no curve turns more than a
/// quarter; every anchor and every curve's middle lies on the circle, and the path starts at
/// the first point.
#[test]
fn a_circle_with_its_anchors_at_given_points() {
use kurbo::ParamCurve;
let (a, b, c) = (Point::new(8.0, 0.0), Point::new(0.0, 6.0), Point::ORIGIN);
let center = Point::new(4.0, 3.0);
for (points, count) in [(&[a, b][..], 4), (&[a, b, c][..], 5), (&[b, a, c, b][..], 5), (&[][..], 4)] {
let path = circle_with_anchors_at(center, 5.0, points);
let sub = &path.subpaths[0];
assert!(sub.closed, "{points:?}");
assert_eq!(sub.anchors.len(), count, "{points:?}: {sub:?}");
for p in points {
assert!(sub.anchors.iter().any(|q| q.p == *p), "{p:?} is an anchor: {sub:?}");
}
if let Some(first) = points.first() {
assert_eq!(sub.anchors[0].p, *first);
}
for q in &sub.anchors {
assert!((q.p.distance(center) - 5.0).abs() < 1e-9, "{q:?}");
}
for seg in path.to_bezpath().segments() {
let turn = {
let (p0, p1) = (seg.start() - center, seg.end() - center);
p0.cross(p1).atan2(p0.dot(p1))
};
assert!(turn > 0.0 && turn <= PI / 2.0 + 1e-9, "{turn} for {seg:?}");
assert!((seg.eval(0.5).distance(center) - 5.0).abs() < 5.0 * 1e-3, "{seg:?}");
}
}
}
/// The two ends of a diameter give four anchors, also where the midpoint rounds off it: at
/// x = 10⁶, steps of 2⁻³³ put the second point more than half a turn from the first, seen from
/// the rounded center.
#[test]
fn a_diameter_gives_four_anchors_where_its_midpoint_rounds() {
let u = 2f64.powi(-33);
let (a, b) = (Point::new(1_000_000.0, 0.0), Point::new(1_000_000.0 + 9.0 * u, 8.0 * u));
let (center, radius) = circle_through_points(&[a, b]).expect("a circle");
let path = circle_with_anchors_at(center, radius, &[a, b]);
let sub = &path.subpaths[0];
assert_eq!(sub.anchors.len(), 4, "{sub:?}");
assert_eq!((sub.anchors[0].p, sub.anchors[2].p), (a, b));
}
/// Nearly on one line: a point 10⁻⁴ off a chord 2000 long still gives the circle (its sagitta
/// formula `r = (h² + (L/2)²) / 2h`), and its center sits on the chord's perpendicular
/// bisector; a point 10⁻¹² off it does not.
+28 -3
View File
@@ -699,6 +699,25 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{} show every Contextual Task Bar action and chip that Bar Actions turned off, as the bar's More Options › Reset Bar Actions does; returns the ids shown again",
),
(
"window.quickPenToolbar",
"Quick Pen Toolbar",
"",
"{} show or hide the toolbar the Quick Pen tool shows on the canvas (toggles; returns whether it shows), as Window › Quick Pen Toolbar and the toolbar's More Options › Hide Toolbar do; selecting the Quick Pen tool shows it again",
),
(
"window.quickPenToolbar.pin",
"Pin Toolbar Position",
"",
"{pinned?: bool} keep the Quick Pen toolbar where it is in the canvas window instead of following the drawing (true), let it follow the drawing again from where it is (false) or toggle (omitted), as the toolbar's More Options menu does; returns the new state",
),
("window.quickPenToolbar.reset", "Reset Toolbar Position", "", "{} unpin the Quick Pen toolbar and put it back beside the drawing"),
(
"tool.quickPen.flipArc",
"Flip Arc",
"",
"{} flip the last sharp-corner arc of the path the Quick Pen tool is drawing to the other side of its chord, as C and the toolbar's Flip Arc button do, as one undo step; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active, no path is being drawn or the last piece is not a sharp-corner arc",
),
(
"window.dock",
"Panels",
@@ -1156,7 +1175,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"tool.options",
"Tool Options…",
"",
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOpti Line truncated
"{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's To Line truncated
),
(
"ui.colorGuideOptions",
@@ -1330,6 +1349,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{params?: tracing settings (default: the Default preset's), rename?: a saved preset's name} the Image Trace panel's Manage Presets: open Save as New Preset… for those settings, or with `rename`, Rename… for that saved preset (dialog `imageTracePreset`, field `name`: a new \"Tracing Preset N\" or the preset's name); OK runs imageTrace.presets.save with the name (as `newName` when renaming), and the panel shows the preset it made from its settings",
),
(
"ui.tracingPresetsDialog",
"Tracing Presets…",
"",
"{selected?: preset name (default Default)} open Edit → Tracing Presets (dialog `tracingPresets`, field `selected`): the built-in presets (in brackets, read-only) and the saved ones, with the selected one's settings. New… (from the selected preset) and Edit… (a saved one) open the preset editor (dialog `tracingPreset`, fields `name` and `params`, the tracing settings): OK runs imageTrace.presets.save and returns to Tracing Presets, and a name of a built-in preset, Custom or another saved preset keeps the editor open; Cancel returns with nothing saved. Delete runs imageTrace.presets.delete; Import… runs imageTrace.presets.import, and when saved presets have names in the file, asks (dialog `tracingPresetsReplace`) whether to replace them (OK) or keep them (Cancel); Export… runs imageTrace.presets.export on every saved preset",
),
(
"ui.flattenerPreview",
"Flattener Preview",
@@ -1579,7 +1604,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.colorWheel",
"Color Wheel Options",
"",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, vision}",
"{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors}",
),
(
"ui.savePdfDialog",
@@ -1907,7 +1932,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.hpglOptionsDialog",
"HP-GL Options Dialog",
"",
"{path?, useArtboards?, range?, hpglVersion?, curveTolerance?, origin?, pens?, sortPaths?, insideFirst?} open HP-GL Options (dialog `hpglOptions`: fields = these document.export options over the ones used last; pens null is One Pen per Color); OK checks them, remembers them and writes path (else asks). Export As… → HP-GL opens it too",
"{path?, useArtboards?, range?, hpglVersion?, curveTolerance?, origin?, pens?, sortPaths?, insideFirst?} open HP-GL Options (dialog `hpglOptions`: fields = these document.export options over the ones used last; pens null is One Pen per Color); OK checks them, remembers them and writes path (else asks); OK after another document has become active closes the dialog and writes nothing. Export As… → HP-GL opens it too",
),
(
"file.saveForWeb",
+3
View File
@@ -56,6 +56,9 @@ serde_json = { workspace = true }
krilla = { workspace = true, features = ["simple-text"] }
# How many times the symbol list is read to find symbols by name.
vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] }
# The counters vectorcraft-engine's tests turn on, also when this crate is tested without
# vectorcraft-engine (`cargo xtask ci shard`).
vectorcraft-pdf = { path = ".", features = ["read-count"] }
# An independent raster oracle for gradient placement in PDF forms. These are test-only macOS
# bindings; the exporter stays portable Rust and does not depend on an OS PDF renderer.
+39 -6
View File
@@ -262,6 +262,12 @@ fn spend(work: &mut usize, steps: usize) -> Result<(), String> {
/// The triangles covering one face: `contours` (outlines one way round, holes the other) on the
/// plane across `normal` (its Newell normal).
pub(crate) fn triangulate(contours: &[Vec<V3>], normal: V3, work: &mut usize) -> Result<Vec<[V3; 3]>, String> {
triangulate_keeping(contours, normal, work, false)
}
/// [`triangulate`], keeping the corners that lie straight between their neighbors as triangle
/// corners when `keep_straight` is set.
fn triangulate_keeping(contours: &[Vec<V3>], normal: V3, work: &mut usize, keep_straight: bool) -> Result<Vec<[V3; 3]>, String> {
// Cut the face on the coordinate plane it is least slanted to, turned so outlines run
// counterclockwise.
let (ax, ay, az) = (normal.0.abs(), normal.1.abs(), normal.2.abs());
@@ -332,11 +338,30 @@ pub(crate) fn triangulate(contours: &[Vec<V3>], normal: V3, work: &mut usize) ->
let (hole, rest) = holes[k..].split_first().ok_or_else(too_complex)?;
ring = bridge(ring, hole, rest, work)?;
}
clip(&ring, &mut out, work)?;
clip(&ring, &mut out, work, keep_straight)?;
}
Ok(out)
}
/// The triangles covering `rings`, a flat face in the art's plane (outlines with a positive signed
/// area, holes negative), cut as a mesh's faces are: each hole bridged to the outline around it,
/// then ear clipped. Every corner of the rings that lies straight between its neighbors (a corner
/// a neighboring cell shares) stays a triangle corner. Each triangle runs the way its outline does,
/// and a triangle with no area that way round is left out. The steps add to `work`, and the cut
/// stops as soon as `work` passes `budget`. `None` when a hole crosses an outline or another hole,
/// or when `work` passes `budget`.
pub(crate) fn flat_triangles(rings: &[Vec<Point>], work: &mut usize, budget: usize) -> Option<Vec<[Point; 3]>> {
let contours: Vec<Vec<V3>> = rings.iter().map(|r| r.iter().map(|q| V3(q.x, q.y, 0.0)).collect()).collect();
// Counted up from MAX_WORK less the budget, the cut's own checks stop it at the budget.
let start = MAX_WORK - budget.min(MAX_WORK);
let mut spent = start.saturating_add(*work);
let triangles = triangulate_keeping(&contours, V3(0.0, 0.0, 1.0), &mut spent, true);
*work = spent.saturating_sub(start);
let triangles = triangles.ok()?;
let triangles = triangles.into_iter().map(|t| t.map(|v| Point::new(v.0, v.1)));
Some(triangles.filter(|[a, b, c]| (*b - *a).cross(*c - *a) > 0.0).collect())
}
/// Do segments `a`–`b` and `c`–`d` cross (touching at a shared end does not count)?
fn crosses(a: (f64, f64), b: (f64, f64), c: (f64, f64), d: (f64, f64)) -> bool {
let same = |p: (f64, f64), q: (f64, f64)| (p.0 - q.0).hypot(p.1 - q.1) < 1e-9;
@@ -401,9 +426,10 @@ fn bridge(ring: Vec<Corner>, hole: &[Corner], others: &[Vec<Corner>], work: &mut
}
/// Cut `ring` (counterclockwise, possibly joined to its holes by bridges) into triangles by ear
/// clipping. A corner in line with its neighbors goes without a triangle. If no ear is left (a
/// ring that crosses itself), the rest is cut as a fan.
fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize) -> Result<(), String> {
/// clipping. A corner in line with its neighbors goes without a triangle, unless `keep_straight`
/// is set and it lies straight between them: it then stays a corner of the triangles beside it. If
/// no ear is left (a ring that crosses itself), the rest is cut as a fan.
fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize, keep_straight: bool) -> Result<(), String> {
let n = ring.len();
if n < 3 {
return Ok(());
@@ -419,8 +445,10 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize) -> Result<(),
let turn = cross(pa, pb, pc);
let scale = (pb.x - pa.x).hypot(pb.y - pa.y) * (pc.x - pb.x).hypot(pc.y - pb.y);
let mut ear = false;
let drop = turn.abs() <= 1e-12 * scale.max(1e-300);
if !drop && turn > 0.0 {
let flat = turn.abs() <= 1e-12 * scale.max(1e-300);
let straight = keep_straight && flat && (pb.x - pa.x) * (pc.x - pb.x) + (pb.y - pa.y) * (pc.y - pb.y) > 0.0;
let drop = flat && !straight;
if !flat && turn > 0.0 {
spend(work, left)?;
ear = true;
let mut k = next[c];
@@ -430,6 +458,11 @@ fn clip(ring: &[Corner], out: &mut Vec<[V3; 3]>, work: &mut usize) -> Result<(),
ear = false;
break;
}
// A kept corner on the ear's new edge would be left off every triangle.
if keep_straight && touches((p.x, p.y), (pc.x, pc.y), (pa.x, pa.y)) {
ear = false;
break;
}
k = next[k];
}
}
+62
View File
@@ -173,6 +173,68 @@ fn a_bridge_through_another_corner_touches_it() {
assert!(!super::touches((5.0, 1.0), (0.0, 0.0), (10.0, 0.0)));
}
#[test]
fn flat_triangles_keep_corners_that_lie_along_an_edge() {
// A square with a hole, its edges carrying corners midway, as a cell shares with its finer
// neighbors: every corner is a corner of some triangle, and the triangles cover the face.
let p = |x: f64, y: f64| Point::new(x, y);
let outline = vec![p(5.0, 0.0), p(10.0, 0.0), p(10.0, 5.0), p(10.0, 10.0), p(5.0, 10.0), p(0.0, 10.0), p(0.0, 5.0), p(0.0, 0.0)];
let hole = vec![p(1.0, 4.0), p(1.0, 6.0), p(2.0, 6.0), p(2.0, 4.0)];
let mut work = 0;
let triangles = flat_triangles(&[outline.clone(), hole], &mut work, usize::MAX).unwrap();
let area = |t: &[Point; 3]| ((t[1].x - t[0].x) * (t[2].y - t[0].y) - (t[1].y - t[0].y) * (t[2].x - t[0].x)) / 2.0;
assert!(triangles.iter().all(|t| area(t) > 0.0));
assert!((triangles.iter().map(area).sum::<f64>() - 98.0).abs() < 1e-9);
for q in &outline {
assert!(triangles.iter().any(|t| t.contains(q)), "{q:?} is no triangle's corner");
}
assert!(work > 0);
}
#[test]
fn flat_triangles_keep_corners_on_the_edge_an_ear_would_cut() {
// The first ear's new edge runs along the bottom, through its two middle corners.
let p = |x: f64, y: f64| Point::new(x, y);
let outline = vec![p(0.0, 3.0), p(0.0, 0.0), p(1.0, 0.0), p(2.0, 0.0), p(3.0, 0.0)];
let mut work = 0;
let triangles = flat_triangles(std::slice::from_ref(&outline), &mut work, usize::MAX).unwrap();
let area = |t: &[Point; 3]| ((t[1].x - t[0].x) * (t[2].y - t[0].y) - (t[1].y - t[0].y) * (t[2].x - t[0].x)) / 2.0;
assert!((triangles.iter().map(area).sum::<f64>() - 4.5).abs() < 1e-9);
for q in &outline {
assert!(triangles.iter().any(|t| t.contains(q)), "{q:?} is no triangle's corner");
}
}
#[test]
fn flat_triangles_pass_over_an_ear_whose_new_edge_runs_through_a_dent() {
// The first ear's new edge, from (0, 4) to (4, 0), runs through the dent's corner at (2, 2).
let p = |x: f64, y: f64| Point::new(x, y);
let outline = vec![p(0.0, 0.0), p(4.0, 0.0), p(4.0, 4.0), p(2.0, 2.0), p(0.0, 4.0)];
let mut work = 0;
let triangles = flat_triangles(std::slice::from_ref(&outline), &mut work, usize::MAX).unwrap();
let area = |t: &[Point; 3]| ((t[1].x - t[0].x) * (t[2].y - t[0].y) - (t[1].y - t[0].y) * (t[2].x - t[0].x)) / 2.0;
assert!((triangles.iter().map(area).sum::<f64>() - 12.0).abs() < 1e-9);
for t in &triangles {
for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
for q in &outline {
assert!(!super::touches((q.x, q.y), (a.x, a.y), (b.x, b.y)), "{q:?} lies inside the edge {a:?} to {b:?}");
}
}
}
}
#[test]
fn flat_triangles_stop_at_their_budget() {
let p = |x: f64, y: f64| Point::new(x, y);
let outline = vec![p(0.0, 0.0), p(10.0, 0.0), p(10.0, 10.0), p(0.0, 10.0)];
let hole = vec![p(1.0, 4.0), p(1.0, 6.0), p(2.0, 6.0), p(2.0, 4.0)];
let mut all = 0;
assert!(flat_triangles(&[outline.clone(), hole.clone()], &mut all, usize::MAX).is_some());
let mut work = 0;
assert!(flat_triangles(&[outline, hole], &mut work, all - 1).is_none());
assert!(work >= all, "{work} of {all}");
}
#[test]
fn a_beveled_extrusion_stays_closed() {
let mut b = BezPath::new();
+16 -4
View File
@@ -30,10 +30,10 @@ use build::{Camera, cuts, edge_distance, newell, section};
pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces};
pub use build::{extrude, extrude_side_size, extrude_surfaces, plane};
pub use face_map::{FaceMap, MeshFace, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face};
#[cfg(test)]
use inflate::GRID_WORK;
pub(crate) use inflate::inflate_faces;
#[cfg(test)]
use inflate::{FLAT_BUDGET, FLAT_WORK, GRID_WORK, MAX_FLAT_CORNERS, MAX_FLAT_WORK};
#[cfg(test)]
pub(crate) use inflate::{INFLATED, PUFFED, SOLVE_FIRST};
pub use inflate::{inflate, inflate_each, inflate_together};
#[cfg(test)]
@@ -354,11 +354,15 @@ pub struct Inflate {
pub taper: f64,
/// A closed back (a solid) or none, so the inflated front is a shell open behind.
pub cap: bool,
/// Graphics are mapped onto the front or the puffed back: the pieces of those faces are drawn
/// as triangles, each carrying where its corners lie in the art's plane ([`Facet::surface`]).
/// Off by default, which leaves the facets without one.
pub map_surface: bool,
}
impl Default for Inflate {
fn default() -> Self {
Self { depth: 0.0, volume: 50.0, both_sides: false, twist: 0.0, taper: 1.0, cap: true }
Self { depth: 0.0, volume: 50.0, both_sides: false, twist: 0.0, taper: 1.0, cap: true, map_surface: false }
}
}
@@ -414,8 +418,15 @@ pub struct Facet {
pub end: Option<PlanarFace>,
/// For a piece of Extrude & Bevel's side built for graphics ([`Extrude::map_surface`]): where
/// its corners lie on the side unrolled flat, for a graphic mapped onto it. x runs along the
/// outline and y from the front toward the back ([`crate::SurfaceCell`]).
/// outline and y from the front toward the back ([`crate::SurfaceCell`]). For a piece of
/// Inflate's front or puffed back built for graphics ([`Inflate::map_surface`]): where its
/// corners lie in the art's plane, as offsets from the center of the bounds the solid was built
/// with. The back's corners are where they were in the art before the twist and taper turned
/// and scaled it.
pub surface: Option<crate::SurfaceCell>,
/// The face of Inflate's solid that a facet with a [`Facet::surface`] is a piece of: its front
/// or its puffed back. `None` for every other facet, Extrude & Bevel's side included.
pub membrane: Option<PlanarFace>,
/// The face's plane in view space and the projection it was drawn with, for its depth at a
/// point of the drawing ([`Facet::depth_at`]). `None` for a face whose corners lie more than
/// 0.001 pt off one plane (a piece of a twisted wall) or reach the eye.
@@ -514,6 +525,7 @@ impl Facet {
away: false,
// Revolve's graphics are drawn from its faces, before they become facets.
surface: None,
membrane: None,
plane: face.plane,
#[cfg(test)]
view: vec![],
+1
View File
@@ -232,6 +232,7 @@ impl<'a> Builder<'a> {
away: behind,
end: None,
surface: None,
membrane: None,
plane,
cell: None,
#[cfg(test)]
+98 -13
View File
@@ -1,7 +1,7 @@
use super::build::{Builder, Built, Camera, Keep, Order, Turn, check_bounds, cuts, fit, newell, outward};
use super::membrane::{Edges, MAX_MATERIAL_SEGMENTS, Membrane, cell_triangles, clip, crossings, filled, material};
use super::rings::{MAX_SOLID_POINTS, TOO_COMPLEX_SURFACE, curve_pieces, signed_area, solid_rings};
use super::{Facet, FillRule, Inflate, MAX_FACES, MAX_SOLID_FACES, PathData, Point, Rect, V3, Vec2, View};
use super::{Facet, FillRule, Inflate, MAX_FACES, MAX_SOLID_FACES, PathData, PlanarFace, Point, Rect, V3, Vec2, View};
/// The slices the sides are cut into: more to follow a twist or taper.
fn slices(o: &Inflate) -> usize {
@@ -196,6 +196,44 @@ thread_local! {
pub(crate) static INFLATED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// The grid work of the last solid this thread inflated in full, for the tests.
pub(super) static GRID_WORK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// The work of cutting cells with holes for graphics in the last solid this thread inflated
/// in full, for the tests.
pub(super) static FLAT_WORK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// The work the next solids of this thread may take cutting cells with holes for graphics,
/// for the tests.
pub(super) static FLAT_BUDGET: std::cell::Cell<usize> = const { std::cell::Cell::new(MAX_FLAT_WORK) };
}
/// Most work one inflated surface may take cutting the cells graphics are mapped onto that
/// [`cell_triangles`] can't take (a hole inside the cell, or a ring of more corners), all its
/// cells together ([`crate::mesh::flat_triangles`]).
pub(super) const MAX_FLAT_WORK: usize = 1 << 26;
/// Most corners the pieces of one such cell may have.
pub(super) const MAX_FLAT_CORNERS: usize = 4096;
/// The work cutting cells with holes for graphics may take.
fn flat_budget() -> usize {
#[cfg(test)]
return FLAT_BUDGET.with(std::cell::Cell::get);
#[cfg(not(test))]
MAX_FLAT_WORK
}
/// Marks the facet the builder `b` added after it held `before` facets, if it added one, as a piece
/// of `face` (Inflate's front or puffed back) whose corners lie at the art points `points`, as
/// offsets from `center` ([`Facet::surface`]). `outward` is the triangle's normal pointing out of
/// the solid: the piece shows the outside of the surface when it was neither turned around to show
/// its inside (on a shell open behind) nor kept turned away.
fn mark_surface(b: &mut Builder<'_>, before: usize, points: [Point; 3], center: Point, outward: V3, face: PlanarFace) {
if b.facets.len() <= before {
return;
}
let Some(f) = b.facets.last_mut() else { return };
let Some(page) = f.contours.first().filter(|c| c.len() == 3).cloned() else { return };
let shows = !f.away && f.normal[0] * outward.0 + f.normal[1] * outward.1 + f.normal[2] * outward.2 > 0.0;
f.surface = Some(crate::SurfaceCell { page, uv: points.iter().map(|q| Point::new(q.x - center.x, q.y - center.y)).collect(), outward: shows });
f.membrane = Some(face);
}
/// The facets of one inflated shape, for a camera that allows for a puff `reach` high (or the
@@ -241,6 +279,8 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee
};
let smooth = view.shade && view.has_colored_lights();
let camera = Camera::new(view, bounds, o.depth + 2.0 * height.max(reach));
// A graphic's offsets are from the center of the bounds the solid is built with.
let center = bounds.center();
// Without its back cap the object is a shell open behind, its inside showing.
let mut b = Builder::new(&camera, o.cap, false, keep);
let half = o.depth / 2.0;
@@ -260,6 +300,8 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee
// builds the topology of every outline ring near its cell, so a self-crossing outline cost its
// crossings again in every cell it spans. Past it, cells take their clipped pieces.
let material_left = std::cell::Cell::new(MAX_MATERIAL_SEGMENTS);
// The work of cutting cells with holes for graphics, all the cells together ([`MAX_FLAT_WORK`]).
let mut flat_work = 0usize;
// Every ring's bounds, and the crossings of the last few rows the cells' centres lie on (a
// row of cells has at most seven, at its three levels).
let ring_bounds: Vec<Option<Rect>> =
@@ -410,22 +452,63 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee
out
})
.collect();
if height > 0.0
&& smooth
&& let Some(triangles) = cell_triangles(&pieces)
{
// Smooth shading draws the pieces as triangles, and so do graphics mapped onto
// the front or back: each triangle then carries where its corners lie in the
// art's plane.
let smoothed = height > 0.0 && smooth;
let triangles = match (smoothed || o.map_surface).then(|| cell_triangles(&pieces)) {
// A cell graphics are mapped onto that the quick cut can't take (a hole
// inside it, or a ring of more corners) is cut with its holes, against one
// budget for the whole surface. Drawn whole instead, its piece would show
// no graphics.
Some(None) if o.map_surface => {
if pieces.iter().map(Vec::len).fold(0usize, usize::saturating_add) > MAX_FLAT_CORNERS {
return Err(TOO_COMPLEX_SURFACE.into());
}
let budget = flat_budget();
let holed = crate::mesh::flat_triangles(&pieces, &mut flat_work, budget);
if flat_work > budget {
return Err(TOO_COMPLEX_SURFACE.into());
}
Some(holed.ok_or_else(|| TOO_COMPLEX_SURFACE.to_string())?)
}
quick => quick.flatten(),
};
if let Some(triangles) = triangles {
let order = if flat { Order::Last } else { Order::Depth };
for points in triangles {
let front = points.map(|q| camera.place(q, half + lift(q)));
b.smooth_triangle(front, points.map(|q| camera.rotate(normal(q))), false)?;
let before = b.facets.len();
let outward = newell(&[front.to_vec()]);
if smoothed {
b.smooth_triangle(front, points.map(|q| camera.rotate(normal(q))), false)?;
} else {
b.face(vec![front.to_vec()], outward, order)?;
}
if o.map_surface {
mark_surface(&mut b, before, points, center, outward, PlanarFace::Front);
}
if o.both_sides && o.cap {
let back = points.map(|q| camera.place(back_turn.apply(q), -half - lift(q) * back_turn.scale));
let normals = points.map(|q| {
let n = normal(q);
// A uniform taper scales all three coordinates equally;
// twist turns the back normal about the shape's z-axis.
camera.rotate(V3(back_turn.cos * n.0 - back_turn.sin * n.1, back_turn.sin * n.0 + back_turn.cos * n.1, -n.2))
});
b.smooth_triangle(back, normals, true)?;
let before = b.facets.len();
let n = newell(&[back.to_vec()]);
// The back winds the same way round as the front, so its outward
// normal is reversed.
let outward = V3(-n.0, -n.1, -n.2);
if smoothed {
let normals = points.map(|q| {
let n = normal(q);
// A uniform taper scales all three coordinates equally;
// twist turns the back normal about the shape's z-axis.
camera.rotate(V3(back_turn.cos * n.0 - back_turn.sin * n.1, back_turn.sin * n.0 + back_turn.cos * n.1, -n.2))
});
b.smooth_triangle(back, normals, true)?;
} else {
b.face(vec![back.to_vec()], outward, order)?;
}
if o.map_surface {
mark_surface(&mut b, before, points, center, outward, PlanarFace::Back);
}
}
}
continue;
@@ -507,6 +590,8 @@ fn inflated(p: Puff, bounds: Rect, o: Inflate, view: View, reach: f64, keep: Kee
}
#[cfg(test)]
GRID_WORK.with(|w| w.set(edges.work()));
#[cfg(test)]
FLAT_WORK.with(|w| w.set(flat_work));
if edges.spent() {
return Err(TOO_COMPLEX_SURFACE.into());
}
+117 -1
View File
@@ -457,6 +457,122 @@ fn inflate_leaves_holes_open() {
assert!(close(area(&f), 100.0 * 100.0 - 40.0 * 40.0, 1e-3), "{}", area(&f));
}
#[test]
fn inflate_marks_where_each_piece_lies_in_the_art_for_graphics() {
let (p, r) = shape(&square(0.0, 0.0, 100.0));
let on = |o: Inflate, view: View| inflate(&p, FillRule::EvenOdd, r, Inflate { map_surface: true, ..o }, view).unwrap();
// Without the request no piece carries a surface point.
assert!(inflate(&p, FillRule::EvenOdd, r, Inflate::default(), front()).unwrap().iter().all(|f| f.surface.is_none() && f.membrane.is_none()));
// Straight on, every piece is a front triangle whose corners lie where the art does, as
// offsets from the center of the bounds, and together they cover the shape.
let f = on(Inflate::default(), front());
let marked: Vec<&Facet> = f.iter().filter(|f| f.surface.is_some()).collect();
assert!(marked.len() > 20, "{}", marked.len());
assert!(close(marked.iter().map(|f| signed_area(&f.contours[0]).abs()).sum::<f64>(), 100.0 * 100.0, 1e-3));
for f in &marked {
let s = f.surface.as_ref().unwrap();
assert_eq!(f.membrane, Some(PlanarFace::Front));
assert!(s.outward);
for (page, uv) in s.page.iter().zip(&s.uv) {
assert!(close(page.x, uv.x + 50.0, 1e-6) && close(page.y, uv.y + 50.0, 1e-6), "{page:?} {uv:?}");
}
}
// Both sides puffs a back: seen from behind its pieces show their outside, and under Twist
// they keep the untwisted art points while the pieces turn on the page.
let behind = View { rotation_y: 180.0, ..front() };
let back = |o: Inflate| {
on(o, behind)
.into_iter()
.filter(|f| f.membrane == Some(PlanarFace::Back) && f.surface.as_ref().is_some_and(|s| s.outward))
.collect::<Vec<_>>()
};
let plain = back(Inflate { both_sides: true, ..Inflate::default() });
assert!(!plain.is_empty());
let twisted = back(Inflate { both_sides: true, twist: 30.0, ..Inflate::default() });
assert!(!twisted.is_empty());
let uv_extent =
|f: &[Facet]| f.iter().flat_map(|f| f.surface.as_ref().unwrap().uv.clone()).fold(Rect::new(0.0, 0.0, 0.0, 0.0), |r, q| r.union_pt(q));
assert!(close(uv_extent(&twisted).width(), 100.0, 1e-6) && close(uv_extent(&twisted).height(), 100.0, 1e-6));
assert!(extent(&twisted).width() > extent(&plain).width() + 10.0, "{:?} {:?}", extent(&twisted), extent(&plain));
// Without Both sides there is no back to mark.
assert!(on(Inflate::default(), behind).iter().all(|f| f.membrane != Some(PlanarFace::Back)));
}
/// A square 0.3 pt across with its corner at the lattice point `(qx, qy)` of the grid of a
/// 100 pt shape, offset 0.1 pt: it lies inside one quarter cell of that grid.
fn speck(qx: f64, qy: f64) -> BezPath {
let unit = 100.0 / 48.0 / 4.0;
square(qx * unit + 0.1, qy * unit + 0.1, 0.3)
}
/// The area of the pieces marked for graphics on `face`.
fn mapped_area(f: &[Facet], face: PlanarFace) -> f64 {
f.iter().filter(|f| f.membrane == Some(face)).map(|f| signed_area(&f.contours[0]).abs()).sum()
}
/// A hole inside one cell of the surface's grid leaves that cell's piece with a hole in it:
/// graphics still map onto the rest of the cell, front and back, and the hole stays open.
#[test]
fn inflate_maps_graphics_around_a_hole_inside_one_cell() {
let mut b = square(0.0, 0.0, 100.0);
b.extend(speck(96.0, 96.0));
let (p, r) = shape(&b);
let o = Inflate { map_surface: true, both_sides: true, ..Inflate::default() };
let f = inflate(&p, FillRule::EvenOdd, r, o, front()).unwrap();
let mapped = mapped_area(&f, PlanarFace::Front);
assert!(close(mapped, 100.0 * 100.0 - 0.3 * 0.3, 1e-3), "{mapped}");
let f = inflate(&p, FillRule::EvenOdd, r, o, View { rotation_y: 180.0, ..front() }).unwrap();
let mapped = mapped_area(&f, PlanarFace::Back);
assert!(close(mapped, 100.0 * 100.0 - 0.3 * 0.3, 1e-3), "{mapped}");
}
/// The cells graphics are mapped onto that need their holes cut out share one budget for the
/// whole surface: past it the surface is refused, however little each cell takes.
#[test]
fn inflate_cuts_holed_cells_for_graphics_within_one_budget() {
let mut b = square(0.0, 0.0, 100.0);
for i in 0..8 {
for j in 0..8 {
b.extend(speck(20.0 + 20.0 * i as f64, 20.0 + 20.0 * j as f64));
}
}
let (p, r) = shape(&b);
let o = Inflate { map_surface: true, ..Inflate::default() };
let f = inflate(&p, FillRule::EvenOdd, r, o, front()).unwrap();
assert!(close(mapped_area(&f, PlanarFace::Front), 100.0 * 100.0 - 64.0 * 0.3 * 0.3, 1e-3));
let all = FLAT_WORK.with(std::cell::Cell::get);
assert!(all > 0);
// Half the work all 64 cells took is far more than any one of them takes.
FLAT_BUDGET.with(|w| w.set(all / 2));
let half = inflate(&p, FillRule::EvenOdd, r, o, front());
FLAT_BUDGET.with(|w| w.set(MAX_FLAT_WORK));
assert_eq!(half.err().as_deref(), Some(TOO_COMPLEX_SOLID));
// The art draws without graphics as before.
assert!(inflate(&p, FillRule::EvenOdd, r, Inflate::default(), front()).is_ok());
}
/// A cell graphics are mapped onto whose pieces have more corners than one cut may take refuses
/// the surface rather than drawing that cell without its graphics.
#[test]
fn inflate_refuses_graphics_on_a_cell_with_too_many_corners() {
let mut b = square(0.0, 0.0, 100.0);
let unit = 100.0 / 48.0 / 4.0;
let c = Point::new(96.5 * unit, 96.5 * unit);
let n = MAX_FLAT_CORNERS + 10;
let mut ring = BezPath::new();
for k in 0..n {
let a = -std::f64::consts::TAU * k as f64 / n as f64;
let q = (c.x + 0.2 * a.cos(), c.y + 0.2 * a.sin());
if k == 0 { ring.move_to(q) } else { ring.line_to(q) }
}
ring.close_path();
b.extend(ring);
let (p, r) = shape(&b);
let mapped = inflate(&p, FillRule::EvenOdd, r, Inflate { map_surface: true, ..Inflate::default() }, front());
assert_eq!(mapped.err().as_deref(), Some(TOO_COMPLEX_SOLID));
assert!(inflate(&p, FillRule::EvenOdd, r, Inflate::default(), front()).is_ok());
}
#[test]
fn malformed_and_degenerate_input_is_bounded() {
let (p, b) = shape(&square(0.0, 0.0, 100.0));
@@ -483,7 +599,7 @@ fn malformed_and_degenerate_input_is_bounded() {
&p,
FillRule::EvenOdd,
b,
Inflate { depth: -5.0, volume: f64::NAN, both_sides: true, twist: f64::INFINITY, taper: f64::NAN, cap: true },
Inflate { depth: -5.0, volume: f64::NAN, both_sides: true, twist: f64::INFINITY, taper: f64::NAN, cap: true, map_surface: false },
front()
)
.is_ok()
+15 -7
View File
@@ -1,7 +1,7 @@
//! Shape Builder (Shift+M), Live Paint Bucket (K) and Live Paint Selection (Shift+L).
//! Shape Builder (Shift+M), Live Paint Bucket (K), Fill Area and Live Paint Selection (Shift+L).
//!
//! The tools only emit commands (`shapeBuilder.merge`, `livePaint.fill`, `livePaint.strokeEdge`,
//! `select.*`); the planar arrangement comes from `vectorcraft_pathops::shape_builder` (Shape
//! The tools only emit commands (`shapeBuilder.merge`, `shapeBuilder.copyRegion`, `livePaint.fill`,
//! `livePaint.strokeEdge`, `select.*`); the planar arrangement comes from `vectorcraft_pathops::shape_builder` (Shape
//! Builder) and `vectorcraft_pathops::live_paint` (Live Paint).
//!
//! **Live Paint groups** are ordinary groups (no special node kind): the group's name starts with
@@ -28,11 +28,13 @@ use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, Tool
pub use po::SHAPE_BUILDER_MAX_GAP;
mod cache;
mod fill_area;
mod live_paint;
mod lookup;
mod map;
use cache::{BACKGROUND_SEGMENTS, CacheKey, RegionCache};
pub use fill_area::{AreaFinder, EnclosedArea, FillAreaTool, every_layer, fill_area_roots};
#[cfg(test)]
use live_paint::LpHover;
pub use live_paint::{
@@ -868,11 +870,16 @@ impl Tool for ShapeBuilderTool {
/// is not true or false, a `pickColorFrom` other than `artwork` or `swatches`, a `selection` other
/// than `freeform` or `straightLine`, a `highlightColor` that is not an RGB color without an alpha
/// part and a `gapLength` that is not a finite number are errors. A finite gap length out of 0 to
/// [`SHAPE_BUILDER_MAX_GAP`] is not an error: the tool clamps it. The Live Paint tools are checked
/// by [`check_live_paint_options`]; Ok for every other tool. Saved settings go to the tools'
/// `set_option` instead, which skips a value it cannot read.
/// [`SHAPE_BUILDER_MAX_GAP`] is not an error: the tool clamps it. `fillArea` takes only
/// `gapDetection`, `gapLength` and `openFilledAsClosed`, checked the same way. The Live Paint tools
/// are checked by [`check_live_paint_options`]; Ok for every other tool. Saved settings go to the
/// tools' `set_option` instead, which skips a value it cannot read.
pub fn check_builder_options(tool: &str, values: &serde_json::Map<String, Value>) -> Result<(), String> {
if tool != "shapeBuilder" {
if tool == "fillArea" {
if let Some(key) = values.keys().find(|k| !matches!(k.as_str(), "gapDetection" | "gapLength" | "openFilledAsClosed")) {
return Err(format!("unknown Fill Area option `{key}`"));
}
} else if tool != "shapeBuilder" {
return check_live_paint_options(tool, values);
}
let one_of = |key: &str, v: &Value, names: &[&str]| {
@@ -902,6 +909,7 @@ pub fn create(id: &str) -> Option<Box<dyn Tool>> {
"shapeBuilder" => Box::new(ShapeBuilderTool::default()),
"livePaintBucket" => Box::new(LivePaintBucketTool::default()),
"livePaintSelection" => Box::new(LivePaintSelectionTool::default()),
"fillArea" => Box::new(FillAreaTool::new()),
_ => return None,
})
}
+701
View File
@@ -0,0 +1,701 @@
//! The Fill Area tool: a click inside an area that visible, unlocked paths enclose adds a new
//! closed path of that area with the current fill and stroke (`shapeBuilder.copyRegion`). The
//! paths around the area stay as they are, and nothing needs to be selected.
use vectorcraft_geom::path::segment_bounds;
use vectorcraft_geom::{ParamCurve, PathSeg};
use super::lookup::path_contains;
use super::*;
/// The area [`AreaFinder::find`] finds under a point.
#[derive(Clone, Debug, PartialEq)]
pub struct EnclosedArea {
/// The area's outline, as a Shape Builder merge of that one region makes it.
pub path: PathData,
/// The object directly in a layer that holds the front-most path along the area (its outline
/// touches the area's outline, or it covers the area), or in isolation mode the object directly
/// in the isolated object: the new path goes directly above it, so it never goes inside a group,
/// a Live Paint group, a Shaper group or a clipping group other than the isolated one.
pub above: NodeId,
}
/// How many times [`AreaFinder::find`] widens the part of the document it maps before it maps
/// every path.
const WINDOW_ROUNDS: usize = 24;
/// The side (pt) of the first window [`AreaFinder::find`] maps around a point that no path's bounds
/// hold.
const FIRST_WINDOW: f64 = 32.0;
/// How many times [`AreaFinder::find`] makes the window four times larger when the paths in it hold
/// no area under the point, before it maps every path: a 32 pt window reaches 8,192 pt.
const NEAR_ROUNDS: usize = 4;
/// Finds the area under a point among the paths of some objects, mapping only the paths near the
/// point first: an area that lies inside a window is bounded by the paths whose bounds reach the
/// window, so the paths outside it cannot change it. When the maps of [`NEAR_ROUNDS`] larger windows
/// have no area under the point, or the area does not fit after [`WINDOW_ROUNDS`] widenings, the
/// finder maps every path. When a window's paths have more segments than one Shape Builder map
/// takes, the paths with the most segments are left out until the rest fit, and an area is taken
/// only when no path left out crosses it or comes within the gap of it; a path left out that
/// covers it still counts for where the new path goes. When every path together has more segments than that,
/// an area no window finds is not found. The map of every path, once a search has needed it, is
/// kept for the next search.
pub struct AreaFinder {
/// The inputs back → front, as [`shape_builder_shapes`] gives them, with their bounds and the
/// object directly in a layer that holds each one ([`outermost`]).
inputs: Vec<(po::Shape, Rect, NodeId)>,
/// The bounds of every input.
total: Option<Rect>,
gap: f64,
/// The segments of all the inputs.
segments: usize,
/// Whether all the inputs fit the segment limit of one Shape Builder map. Past it a map keeps
/// only the filled areas and loses the lines between them, so no map of every input is made.
fits: bool,
/// The map of every input, with the index of each of its shapes in `inputs`.
full: Option<(BuilderMap, Vec<usize>)>,
}
/// Does `r` hold `p`, edges included?
fn holds(r: &Rect, p: Point) -> bool {
p.x >= r.x0 && p.x <= r.x1 && p.y >= r.y0 && p.y <= r.y1
}
/// Do `a` and `b` overlap or touch?
fn meet(a: &Rect, b: &Rect) -> bool {
a.x0 <= b.x1 && b.x0 <= a.x1 && a.y0 <= b.y1 && b.y0 <= a.y1
}
/// The area a path left out of a window's map may cut: its outline, the same as a closed path
/// (`bez`), and the box (`zone`) its outline reaches with the gap.
struct Reach<'a> {
face: &'a PathData,
bez: &'a vectorcraft_geom::kurbo::BezPath,
zone: Rect,
/// How close (pt) to the outline a path may come and still change the area: the gap and 1 pt.
reach: f64,
}
/// Does a segment of `path` (closing segments included) lie inside the area or come within its
/// reach of the area's outline? A path in the box of the area may still lie wholly outside the
/// area, in the empty corner of an L or around it, and such a path does not change it. `budget`
/// counts the work (pieces checked times the outline's segments); when it runs out, the path
/// counts as cutting the area.
fn cuts(path: &PathData, area: &Reach, budget: &mut usize) -> bool {
let bez = path.to_bezpath();
let cost = area.face.subpaths.iter().map(|sp| sp.segment_count()).sum::<usize>().max(1);
vectorcraft_geom::kurbo::segments(bez.elements().iter().copied()).any(|seg| segment_cuts(seg, area, cost, budget, 0))
}
/// How many times [`segment_cuts`] halves a segment: a piece of 1/2^24 of a segment near the area
/// counts as cutting it.
const REACH_SPLITS: u32 = 24;
/// The side (pt) below which a piece of a segment that may come within reach of the area counts as
/// cutting it.
const REACH_TOLERANCE: f64 = 0.01;
/// How much work [`cuts`] does for one area before it takes a path as cutting it: pieces checked
/// times the segments of the area's outline.
const CUT_BUDGET: usize = 1 << 24;
/// Does `seg` lie inside the area or come within its reach of the area's outline? A piece whose
/// box misses the area's zone does not; a piece whose middle is inside the area or within reach of
/// its outline does; a piece farther from the outline than its box is wide does not, since every
/// point of it is then out of reach and on the same side. The rest is halved.
fn segment_cuts(seg: PathSeg, area: &Reach, cost: usize, budget: &mut usize, depth: u32) -> bool {
let b = segment_bounds(seg);
if !meet(&b, &area.zone) {
return false;
}
let Some(left) = budget.checked_sub(cost) else { return true };
*budget = left;
let mid = seg.eval(0.5);
if area.bez.winding(mid) != 0 {
return true;
}
let Some((.., d)) = area.face.nearest(mid) else { return true };
if d <= area.reach {
return true;
}
let wide = b.width().hypot(b.height());
if d - area.reach > wide {
return false;
}
if depth >= REACH_SPLITS || wide < REACH_TOLERANCE {
return true;
}
segment_cuts(seg.subsegment(0.0..0.5), area, cost, budget, depth + 1) || segment_cuts(seg.subsegment(0.5..1.0), area, cost, budget, depth + 1)
}
/// How far (pt) an anchor of an area's outline may lie from a path's outline, with Gap Detection
/// off, and still count as on it: the least snap distance [`outline_snap`] gives, five times the
/// 0.01 pt precision the Shape Builder's map works to.
const CONTACT: f64 = 0.05;
/// Does the filled area of the closed subpaths of `s` hold `p`?
fn covers(s: &po::Shape, p: Point) -> bool {
let closed = PathData::new(s.path.subpaths.iter().filter(|sp| sp.closed).cloned().collect());
path_contains(&closed, s.rule, p)
}
/// Does `outer` hold all of `inner`?
fn within(inner: &Rect, outer: &Rect) -> bool {
inner.x0 >= outer.x0 && inner.x1 <= outer.x1 && inner.y0 >= outer.y0 && inner.y1 <= outer.y1
}
/// The object directly in `scope` (the isolated object in isolation mode), or else directly in a
/// layer (or sublayer), that holds `id`: `id` itself when `scope` or a layer holds it, or when `id`
/// is `scope`.
fn outermost(doc: &Document, id: NodeId, scope: Option<NodeId>) -> NodeId {
let Some(line) = doc.ancestry(id) else { return id };
let k = match scope {
Some(s) => line.iter().rposition(|a| *a == s),
None => line.iter().rposition(|a| doc.node(*a).is_some_and(|n| n.is_layer())),
};
k.and_then(|k| line.get(k + 1)).copied().unwrap_or(id)
}
/// Does `n` make, move or combine the art in it itself, so that a new path in it would not stay as
/// Fill Area adds it: a Live Paint group, a compound shape, a Shaper group, a graph, an Image Trace
/// result, a dimension, a flare or an Objects on Path group.
fn managed(n: &Node) -> bool {
let e = n.extras();
super::lookup::is_live_paint(n)
|| n.is_compound_shape()
|| e.shaper.is_some()
|| e.graph.is_some()
|| e.trace.is_some()
|| e.dimension.is_some()
|| e.flare.is_some()
|| e.objects_on_path.is_some()
}
/// The roots the Fill Area tool and `shapeBuilder.copyRegion` find areas among, with the isolated
/// object the new path goes into ([`AreaFinder::new`]'s `scope`), for `isolation` (the document's
/// isolated object) and `named` (the objects or layers named; None: every layer). In isolation mode
/// only the isolated layer or group's paths count: of `named`, the ones inside it, with the
/// isolated object in place of one that holds it. An isolated object that no longer exists counts
/// as no isolation. None while an object that is not a layer or a group is isolated (a compound
/// path or a single path), a layer or group with a live effect, a group that is [`managed`], a
/// clipping group or clipped layer, or one inside such an object or inside another object that is
/// not a layer or a group (an envelope): no area is found then.
pub fn fill_area_roots(doc: &Document, isolation: Option<NodeId>, named: Option<&[NodeId]>) -> Option<(Vec<NodeId>, Option<NodeId>)> {
let Some(iso) = isolation.filter(|i| doc.node(*i).is_some()) else {
return Some((named.map_or_else(|| every_layer(doc), <[NodeId]>::to_vec), None));
};
let line = doc.ancestry(iso)?;
// Every object from the layer down to the isolated one is a layer or a plain group: an
// envelope, a blend or another object that draws its contents its own way does not hold
// the new path as drawn.
// A layer or group with a live effect (a Transform effect moves what is in it) draws the new
// path elsewhere than the area.
let plain =
|a: &Node| (a.is_layer() || (matches!(a.kind, NodeKind::Group { .. }) && !managed(a))) && !a.appearance.effects.iter().any(|e| e.visible);
if !line.iter().all(|a| doc.node(*a).is_some_and(plain)) {
return None;
}
// A clipping group or clipped layer's mask clips and is not painted, and its mask hides or cuts
// a new path among the art it clips.
if line.iter().any(|a| doc.node(*a).is_some_and(Node::clips)) {
return None;
}
let Some(named) = named else { return Some((vec![iso], Some(iso))) };
let mut out = vec![];
for r in named {
if line.contains(r) {
out.push(iso);
} else if doc.ancestry(*r).is_some_and(|a| a.contains(&iso)) {
out.push(*r);
}
}
Some((out, Some(iso)))
}
impl AreaFinder {
/// The finder over the paths of `roots` (layers or objects) that the Shape Builder takes:
/// visible, unlocked paths, compound paths and Live Paint faces and edges that draw, not on a
/// locked artboard. Gaps up to `gap` close, and with `open_filled_as_closed` a filled open path
/// bounds an area as if an invisible edge closed it. With `scope` (the isolated object in
/// isolation mode), an area's new path goes directly above the object in `scope` that holds the
/// front-most path along it, so it stays inside the isolated object.
pub fn new(doc: &Document, roots: &[NodeId], scope: Option<NodeId>, gap: f64, open_filled_as_closed: bool) -> Self {
let roots = sorted_roots(doc, roots);
let (shapes, leaves) = shape_builder_shapes(doc, &roots, open_filled_as_closed);
let editable = doc.editable();
let inputs: Vec<(po::Shape, Rect, NodeId)> = shapes
.into_iter()
.zip(leaves)
.filter(|(_, l)| editable(l.id))
.filter_map(|(s, l)| {
let b = s.path.bounds()?;
Some((s, b, outermost(doc, l.id, scope)))
})
.collect();
let total = inputs.iter().map(|(_, b, _)| *b).reduce(|a, b| a.union(b));
let gap = if gap.is_finite() { gap.clamp(0.0, SHAPE_BUILDER_MAX_GAP) } else { 0.0 };
let segments: usize = inputs.iter().flat_map(|(s, ..)| &s.path.subpaths).map(|sp| sp.segment_count()).sum();
Self { inputs, total, gap, segments, fits: segments <= po::SHAPE_BUILDER_MAX_SEGMENTS, full: None }
}
/// The area under `p`: the smallest region of the map of the paths that holds `p`. None when
/// `p` is in no enclosed area.
pub fn find(&mut self, p: Point) -> Option<EnclosedArea> {
if let Some((map, picked)) = &self.full {
return self.area_in(map, picked, &[], p);
}
let total = self.total?;
// A gap bridge reaches at most `gap` past a path, so a window takes in every path within
// that of it.
let reach = self.gap + 1.0;
if !holds(&total.inflate(reach, reach), p) {
return None;
}
let mut window = self
.inputs
.iter()
.filter(|(_, b, _)| holds(&b.inflate(reach, reach), p))
.map(|(_, b, _)| *b)
.reduce(|a, b| a.union(b))
.unwrap_or_else(|| Rect::from_center_size(p, (FIRST_WINDOW, FIRST_WINDOW)));
let mut near = 0;
let mut every_path = false;
// The paths left out of the windows' maps to keep them within the segment limit, by index.
let mut left_out = vec![false; self.inputs.len()];
let mut any_left_out = false;
for round in 0..=WINDOW_ROUNDS {
let last = every_path || round == WINDOW_ROUNDS;
if last && !self.fits {
return None;
}
let zone = window.inflate(reach, reach);
let mut picked: Vec<usize> = (0..self.inputs.len())
.filter(|&i| last || (!left_out.get(i).is_some_and(|o| *o) && self.inputs.get(i).is_some_and(|(_, b, _)| meet(b, &zone))))
.collect();
// Past the segment limit a map keeps only the filled areas, so the paths with the most
// segments stay out of the window's map.
if !last {
for i in self.over_limit(&picked) {
if let Some(o) = left_out.get_mut(i) {
*o = true;
any_left_out = true;
}
}
picked.retain(|&i| !left_out.get(i).is_some_and(|o| *o));
}
let every = picked.len() == self.inputs.len();
let shapes: Vec<po::Shape> = picked.iter().filter_map(|&i| self.inputs.get(i).map(|(s, ..)| s.clone())).collect();
let map = BuilderMap::of_shapes(shapes, false, self.gap);
let face = map.region_at(p).and_then(|k| map.regions.get(k));
let bounds = face.map(|(.., rb)| *rb);
if every {
let area = self.area_in(&map, &picked, &[], p);
self.full = Some((map, picked));
return area;
}
let before = window;
match bounds {
// A path left out that crosses the area or comes within its reach could cut it, and
// only the map of every path holds both.
Some(rb) if within(&rb, &window) => {
let reached = rb.inflate(reach, reach);
let mut budget = CUT_BUDGET;
let cut = any_left_out
&& face.is_none_or(|(region, bez, _)| {
let area = Reach { face: &region.path, bez, zone: reached, reach };
self.inputs.iter().zip(&left_out).any(|((s, b, _), out)| *out && meet(b, &reached) && cuts(&s.path, &area, &mut budget))
});
if !cut {
return self.area_in(&map, &picked, &left_out, p);
}
every_path = true;
}
Some(rb) => window = window.union(rb),
// No area of the paths near the point holds it: an area that does is bounded by
// paths farther away. The window grows four times over a few rounds, and then the
// next round maps every path.
None if near < NEAR_ROUNDS => {
near += 1;
let (w, h) = (window.width().max(FIRST_WINDOW) * 4.0, window.height().max(FIRST_WINDOW) * 4.0);
window = window.union(Rect::from_center_size(window.center(), (w, h)));
}
None => window = total,
}
// A window that did not grow would give the same map again.
if window == before {
every_path = true;
}
}
None
}
/// The inputs among `picked` to leave out of a map so that the rest fit the segment limit of
/// one Shape Builder map: the ones with the most segments first. Empty when all of `picked` fit.
fn over_limit(&self, picked: &[usize]) -> Vec<usize> {
let segments = |i: usize| self.inputs.get(i).map_or(0, |(s, ..)| s.path.subpaths.iter().map(|sp| sp.segment_count()).sum::<usize>());
let mut sum: usize = picked.iter().map(|&i| segments(i)).sum();
let mut by_size: Vec<(usize, usize)> = picked.iter().map(|&i| (segments(i), i)).collect();
by_size.sort_by_key(|(n, _)| std::cmp::Reverse(*n));
let mut out = vec![];
for (n, i) in by_size {
if sum <= po::SHAPE_BUILDER_MAX_SEGMENTS {
break;
}
sum -= n;
out.push(i);
}
out
}
/// The area under `p` in `map`, made of the inputs `picked` (in its order). `left_out` marks
/// the inputs left out of the map, by index, none of which comes near the area: the front-most
/// of them that covers the area decides where the new path goes when it is in front of the
/// shape the map gives.
fn area_in(&self, map: &BuilderMap, picked: &[usize], left_out: &[bool], p: Point) -> Option<EnclosedArea> {
let (region, ..) = map.region_at(p).and_then(|k| map.regions.get(k))?;
let path = po::FaceMerger::with_gap(&map.shapes, self.gap).merge(&[region]);
if path.is_empty() {
return None;
}
let anchors: Vec<Point> = region.path.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect();
// The front-most shape that covers the area or that an anchor of its outline lies on. A
// shape within the gap of an anchor counts only when no shape is along the area itself,
// so a path near the area that bounds none of it does not decide where the new path goes.
// Without a gap, an anchor is on a shape's outline within [`CONTACT`].
let along = |gap: f64| {
map.shapes.iter().enumerate().rev().find(|(i, s)| {
let tol = if gap > 0.0 { outline_snap(&s.path) + gap } else { CONTACT };
region.sources.contains(i)
|| s.path.bounds().is_some_and(|b| {
let b = b.inflate(tol, tol);
anchors.iter().any(|q| holds(&b, *q) && s.path.nearest(*q).is_some_and(|(.., d)| d <= tol))
})
})
};
let k = along(0.0).or_else(|| along(self.gap)).map_or(map.shapes.len().checked_sub(1)?, |(i, _)| i);
let mapped = *picked.get(k)?;
// A path left out comes near no part of the area, so it covers all of it or none of it.
let covering =
left_out.iter().enumerate().rev().find(|(i, out)| **out && *i > mapped && self.inputs.get(*i).is_some_and(|(s, ..)| covers(s, p)));
let front = covering.map_or(mapped, |(i, _)| i);
let above = self.inputs.get(front).map(|(.., id)| *id)?;
Some(EnclosedArea { path, above })
}
}
/// The paths the Fill Area tool finds areas among: every layer's.
pub fn every_layer(doc: &Document) -> Vec<NodeId> {
doc.layers.iter().map(|l| l.id).collect()
}
/// Fill Area (in the Live Paint Bucket's group): a click inside an area that visible, unlocked
/// paths on any layer enclose adds a new closed path of that area with the current fill and stroke
/// (`shapeBuilder.copyRegion`), directly above the front-most object along it. The paths stay as
/// they are and nothing needs to be selected. The area under the pointer is outlined while it
/// hovers. Gap Detection and Consider Open Filled Paths as Closed are the Shape Builder's options.
#[derive(Default)]
pub struct FillAreaTool {
gap_detection: bool,
gap_length: f64,
/// Consider Open Filled Paths as Closed turned off: a filled open path cuts areas as a line
/// does.
open_filled_cuts: bool,
/// The finder for the document as it is, with the key it was made for. Away while a search
/// runs on another thread.
finder: Option<(FinderKey, AreaFinder)>,
/// The area under the pointer, with the key of the finder that found it.
hover: Option<(FinderKey, EnclosedArea)>,
/// Where the pointer last moved over the canvas.
at: Option<Point>,
/// A hover search running on another thread.
job: Option<HoverJob>,
/// The key whose search on another thread failed: hovering does not search it again.
failed: Option<FinderKey>,
/// A press added the path as a preview, which the release keeps.
pressing: bool,
}
/// The document revision, the gap, the open-filled rule and the isolated object an [`AreaFinder`]
/// was made with.
type FinderKey = ((u64, u64), f64, bool, Option<NodeId>);
/// A search for the area under `p` on another thread, which hands back the finder it took.
struct HoverJob {
key: FinderKey,
p: Point,
done: std::sync::mpsc::Receiver<(AreaFinder, Option<EnclosedArea>)>,
}
#[cfg(not(target_arch = "wasm32"))]
thread_local! {
/// The hover searches this thread has started on other threads ([`hover_searches_started`]).
static HOVER_SEARCHES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// How many hover searches this thread has started on other threads, for tests that count them.
#[cfg(all(test, not(target_arch = "wasm32")))]
pub(super) fn hover_searches_started() -> usize {
HOVER_SEARCHES.with(std::cell::Cell::get)
}
/// Runs `finder.find(p)` on another thread; gives the finder back when no thread starts.
#[cfg(not(target_arch = "wasm32"))]
fn spawn_find(finder: AreaFinder, p: Point) -> Result<std::sync::mpsc::Receiver<(AreaFinder, Option<EnclosedArea>)>, Box<AreaFinder>> {
HOVER_SEARCHES.with(|n| n.set(n.get() + 1));
let (tx, done) = std::sync::mpsc::channel();
let (back_tx, back) = std::sync::mpsc::channel();
let spawned = std::thread::Builder::new().name("vectorcraft-fill-area".into()).spawn(move || {
// The finder comes in through a channel, so a thread that does not start leaves it here.
if let Ok(mut f) = back.recv() {
let area = AreaFinder::find(&mut f, p);
// The tool may have dropped the receiver meanwhile (another tool, a new revision).
let _ = tx.send((f, area));
}
});
match spawned {
Ok(_) => match back_tx.send(finder) {
Ok(()) => Ok(done),
Err(e) => Err(Box::new(e.0)),
},
Err(_) => Err(Box::new(finder)),
}
}
/// The web build has no threads.
#[cfg(target_arch = "wasm32")]
fn spawn_find(finder: AreaFinder, _p: Point) -> Result<std::sync::mpsc::Receiver<(AreaFinder, Option<EnclosedArea>)>, Box<AreaFinder>> {
Err(Box::new(finder))
}
impl FillAreaTool {
/// A tool with the Shape Builder's default options.
pub fn new() -> Self {
Self { gap_length: GAP_LENGTHS[0], ..Self::default() }
}
fn gap(&self) -> f64 {
if self.gap_detection { self.gap_length } else { 0.0 }
}
fn open_filled_as_closed(&self) -> bool {
!self.open_filled_cuts
}
fn finder_key(&self, cx: &ToolContext) -> FinderKey {
(cx.revision, self.gap(), self.open_filled_as_closed(), cx.isolation)
}
/// The finder for the document as `cx` has it, made again when the key changed. In isolation
/// mode it takes only the isolated object's paths, as the command does.
fn take_finder(&mut self, cx: &ToolContext) -> AreaFinder {
let key = self.finder_key(cx);
match self.finder.take() {
Some((k, f)) if k == key => f,
_ => {
// An isolated object Fill Area does not work in gives a finder of no paths.
let (roots, scope) = fill_area_roots(cx.doc, key.3, None).unwrap_or_default();
AreaFinder::new(cx.doc, &roots, scope, key.1, key.2)
}
}
}
/// The hover area when it is current and holds `p`.
fn hover_holding(&self, cx: &ToolContext, p: Point) -> Option<&EnclosedArea> {
self.hover.as_ref().filter(|(k, a)| *k == self.finder_key(cx) && path_contains(&a.path, FillRule::NonZero, p)).map(|(_, a)| a)
}
/// The area under `p`, found here and now (a click). A search running on another thread is
/// waited for first, so its finder is not made again; no search starts for where the pointer
/// moved meanwhile.
fn area_at(&mut self, cx: &ToolContext, p: Point) -> Option<EnclosedArea> {
if let Some(a) = self.hover_holding(cx, p) {
return Some(a.clone());
}
self.settle(cx, true, false);
let key = self.finder_key(cx);
let mut finder = self.take_finder(cx);
let area = finder.find(p);
self.finder = Some((key, finder));
area
}
/// Looks for the area under `p` for the hover. A search of more than [`BACKGROUND_SEGMENTS`]
/// segments runs on another thread, and [`Tool::poll`] takes its result; while one runs, a new
/// position waits for it.
fn hover_at(&mut self, cx: &ToolContext, p: Point) {
self.at = Some(p);
if self.hover_holding(cx, p).is_some() {
return;
}
// The outline of an area the pointer left goes at once, while the next search runs.
self.hover = None;
if self.job.is_some() {
return;
}
let key = self.finder_key(cx);
if self.failed == Some(key) {
self.hover = None;
return;
}
let mut finder = self.take_finder(cx);
if finder.segments > BACKGROUND_SEGMENTS {
match spawn_find(finder, p) {
Ok(done) => {
self.job = Some(HoverJob { key, p, done });
return;
}
Err(f) => finder = *f,
}
}
self.hover = finder.find(p).map(|a| (key, a));
self.finder = Some((key, finder));
}
/// Takes the result of the hover search on another thread when it is done (`wait`: waits for
/// it), and with `follow` starts the search for where the pointer moved meanwhile.
fn settle(&mut self, cx: &ToolContext, wait: bool, follow: bool) {
let Some(job) = self.job.take() else { return };
let got = if wait {
job.done.recv().ok()
} else {
match job.done.try_recv() {
Ok(v) => Some(v),
Err(std::sync::mpsc::TryRecvError::Empty) => {
self.job = Some(job);
return;
}
Err(std::sync::mpsc::TryRecvError::Disconnected) => None,
}
};
let Some((finder, area)) = got else {
// The search failed (a bug in the planar map): hovering does not search it again, and
// a click searches here, which reports the failure.
self.failed = Some(job.key);
self.hover = None;
return;
};
let current = job.key == self.finder_key(cx);
if current {
self.finder = Some((job.key, finder));
}
// The area found serves wherever the pointer moved meanwhile, as long as it holds it.
let at = self.at;
self.hover = area.filter(|a| current && at.is_some_and(|p| path_contains(&a.path, FillRule::NonZero, p))).map(|a| (job.key, a));
if follow
&& let Some(p) = at
&& self.hover.is_none()
&& (p != job.p || !current)
{
self.hover_at(cx, p);
}
}
}
impl Tool for FillAreaTool {
fn id(&self) -> &'static str {
"fillArea"
}
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
match ev.kind {
PointerKind::Move => {
self.hover_at(cx, ev.pos);
vec![]
}
PointerKind::Down => {
// A click in no enclosed area does nothing.
let found = self.area_at(cx, ev.pos).is_some();
self.hover = None;
if !found {
return vec![];
}
let mut params = json!({ "point": [ev.pos.x, ev.pos.y], "gap": self.gap() });
if !self.open_filled_as_closed() {
params["openFilledAsClosed"] = json!(false);
}
// The path shows at once and is kept on the release; a press that is dropped (a
// long or canceled touch, a second finger) or Escape before the release takes it
// back.
self.pressing = true;
vec![Action::Begin("Fill Area".into()), Action::Preview("shapeBuilder.copyRegion".into(), params)]
}
PointerKind::Up if std::mem::take(&mut self.pressing) => vec![Action::Commit],
_ => vec![],
}
}
fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
if key == ToolKey::Escape && std::mem::take(&mut self.pressing) { vec![Action::Cancel] } else { vec![] }
}
fn busy(&self) -> bool {
self.pressing
}
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
self.hover
.iter()
.filter(|(k, _)| *k == self.finder_key(cx))
.map(|(_, a)| Overlay::Path { path: a.path.to_bezpath(), color: HIGHLIGHT_RED, width: 3.0, dashed: false })
.collect()
}
fn cursor(&self, cx: &ToolContext, p: Point, _m: Mods) -> Cursor {
if self.hover_holding(cx, p).is_some() { Cursor::LivePaintBucketFace } else { Cursor::LivePaintBucket }
}
fn hover_ended(&mut self, _cx: &ToolContext) {
self.hover = None;
self.at = None;
}
/// The area under a still pointer changes with the document and the view.
fn wants_rehover(&self) -> bool {
true
}
fn waiting(&self) -> bool {
self.job.is_some()
}
fn poll(&mut self, cx: &ToolContext, wait: bool) -> Vec<Action> {
self.settle(cx, wait, true);
while wait && self.job.is_some() {
self.settle(cx, true, true);
}
vec![]
}
/// The Shape Builder's Gap Detection, Gap Length and Consider Open Filled Paths as Closed,
/// which the tool shares.
fn options(&self) -> Value {
json!({
"gapDetection": self.gap_detection,
"gapLength": self.gap_length,
"openFilledAsClosed": self.open_filled_as_closed(),
})
}
fn set_option(&mut self, key: &str, v: &Value) {
match key {
"gapDetection" => self.gap_detection = v.as_bool().unwrap_or(self.gap_detection),
"gapLength" => {
if let Some(n) = v.as_f64().filter(|n| n.is_finite()) {
self.gap_length = n.clamp(0.0, SHAPE_BUILDER_MAX_GAP);
}
}
"openFilledAsClosed" => {
if let Some(b) = v.as_bool() {
self.open_filled_cuts = !b;
}
}
_ => {}
}
self.hover = None;
}
fn check_option(&self, key: &str, v: &Value) -> Result<(), String> {
check_builder_options(self.id(), &serde_json::Map::from_iter([(key.to_string(), v.clone())]))
}
}
+29
View File
@@ -3767,6 +3767,35 @@ fn live_paint_selection_options_set_the_highlight() {
assert_eq!(t.options()["width"], json!(LP_SELECT_WIDTH_RANGE.0));
}
/// A press while a Fill Area hover search runs on another thread waits for that search only: no
/// search starts for where the pointer moved meanwhile, and the press finds its own area.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn fill_area_press_does_not_search_a_hover_position_it_passed() {
let mut d = Document::new(800.0, 600.0);
let l = d.layers[0].id;
let pts: Vec<Point> = (0..200)
.map(|k| {
let a = k as f64 * std::f64::consts::TAU / 200.0;
Point::new(300.0 + 100.0 * a.cos(), 300.0 + 100.0 * a.sin())
})
.collect();
let poly = d.alloc_id();
d.insert(Some(l), 0, Node::path(poly, PathData::single(SubPath::polyline(&pts, true)), Appearance::default_art())).unwrap();
let s = Selection::default();
let p = paint();
let cx = ToolContext { revision: (1, 1), ..cx(&d, &s, &p) };
let mut t = FillAreaTool::new();
let started = super::fill_area::hover_searches_started();
t.pointer(&cx, &ev(PointerKind::Move, 500.0, 500.0));
assert!(t.waiting());
t.pointer(&cx, &ev(PointerKind::Move, 510.0, 500.0));
let acts = t.pointer(&cx, &ev(PointerKind::Down, 300.0, 300.0));
assert!(matches!(acts.as_slice(), [Action::Begin(_), Action::Preview(id, _)] if id == "shapeBuilder.copyRegion"), "{acts:?}");
assert!(!t.waiting());
assert_eq!(super::fill_area::hover_searches_started() - started, 1, "only the search that was running");
}
#[test]
fn create_builds_the_three_tools() {
for id in ["shapeBuilder", "livePaintBucket", "livePaintSelection"] {
+1
View File
@@ -103,6 +103,7 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[
&[
t("shapeBuilder", "Shape Builder Tool", Some("Shift+M"), "tool-shape-builder"),
t("livePaintBucket", "Live Paint Bucket", Some("K"), "tool-bucket"),
t("fillArea", "Fill Area Tool", None, "tool-fill-area"),
t("livePaintSelection", "Live Paint Selection Tool", Some("Shift+L"), "tool-live-select"),
],
&[
+260 -21
View File
@@ -16,8 +16,17 @@
//! circle passes through the points (two are the same, three lie on one line) or the circle would
//! reach past the canvas, the tool shows none and the release draws nothing; for three different
//! points on one line, or a circle past the canvas, the pointer shows "Circle too large".
//!
//! The tool's options (Circle Tool Options, `tool.setOption`; kept with the preferences):
//! `center`, `radii` and `diameter` show or hide the center cross, the radius lines and the
//! diameter label; `color` is the color of the cross and the lines (one of [`COLORS`]);
//! `standardAnchors` off puts the circle's anchors at the points it was drawn through instead of
//! at 0°, 90°, 180° and 270° (`anchors: "points"`); `dragThird` off places the second point with
//! a click and draws the circle through three points with a third click, and a click on the second
//! point again (as a double-click there does) draws the circle on the two points. Every option is
//! on by default, and `color` is blue.
use serde_json::{Value, json};
use serde_json::{Map, Value, json};
use vectorcraft_doc::MAX_COORD;
use vectorcraft_geom::{Point, Rect, Vec2, shapes};
@@ -35,6 +44,71 @@ const REACH_PX: f64 = 3.0;
/// The longest outline (screen points) the preview draws dashed, about 7,000 dashes.
const DASHED_PX: f64 = 50_000.0;
/// The colors the center cross and the radius lines can be drawn in, by option value. Blue is the
/// feedback color the other drawing tools use.
pub const COLORS: &[(&str, [u8; 3])] = &[
("red", [0xe5, 0x2d, 0x27]),
("blue", crate::draw2::FEEDBACK),
("magenta", [0xd6, 0x2c, 0xd6]),
("green", [0x1f, 0xb4, 0x4b]),
("black", [0x00, 0x00, 0x00]),
("gray", [0x80, 0x80, 0x80]),
];
/// The option keys that are true or false.
const SWITCHES: &[&str] = &["center", "radii", "diameter", "standardAnchors", "dragThird"];
/// The tool's options (see the module comment).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Options {
center: bool,
radii: bool,
diameter: bool,
/// An entry of [`COLORS`].
color: usize,
standard_anchors: bool,
drag_third: bool,
}
impl Default for Options {
fn default() -> Self {
Options { center: true, radii: true, diameter: true, color: 1, standard_anchors: true, drag_third: true }
}
}
impl Options {
fn switch(&mut self, key: &str) -> Option<&mut bool> {
Some(match key {
"center" => &mut self.center,
"radii" => &mut self.radii,
"diameter" => &mut self.diameter,
"standardAnchors" => &mut self.standard_anchors,
"dragThird" => &mut self.drag_third,
_ => return None,
})
}
}
/// Is every value in `values` one the tool takes? `tool.setOption` checks them all before setting
/// any; [`Tool::set_option`] skips a value it cannot read.
pub fn check_options(values: &Map<String, Value>) -> Result<(), String> {
for (key, v) in values {
if SWITCHES.contains(&key.as_str()) {
if !v.is_boolean() {
return Err(format!("`{key}` must be true or false"));
}
} else if key == "color" {
if !v.as_str().is_some_and(|s| COLORS.iter().any(|(name, _)| *name == s)) {
let names: Vec<&str> = COLORS.iter().map(|(name, _)| *name).collect();
return Err(format!("`{key}` must be one of {}", names.join(", ")));
}
} else {
return Err(format!("unknown Circle tool option `{key}`"));
}
}
Ok(())
}
/// The press in progress.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Press {
@@ -47,23 +121,36 @@ enum Press {
/// places the third point and the circle passes through `snapped`. A press within
/// [`REACH_PX`] of the first point, or one that snaps to it (`on_first`), is a press on it: let
/// go there it places nothing, and dragged out it draws the circle on the diameter it drags out.
/// With `dragThird` off, a drag moves the second point and the release places it.
Second { at: Point, snapped: Point, from: Point, on_first: bool, dragged: bool },
/// With `dragThird` off, the press after the second point was placed, at `at` (snapped). Let go
/// on the second point (`on_second`), it draws the circle on the two points; let go on the
/// first point it places nothing; otherwise it draws the circle through the three points.
Third { at: Point, from: Point, on_first: bool, on_second: bool, dragged: bool },
}
#[derive(Default)]
pub struct CircleTool {
snap: DrawSnap,
options: Options,
/// The first point, placed by a click (or by the press of a drag in progress).
first: Option<Point>,
/// With `dragThird` off, the second point, placed by a click where it is shown (snapped, with
/// Alt's rounding of the diameter when Alt was held), and where the click let go: a press near
/// either is a press on the second point, so the second click of a double-click finds it even
/// where Alt's rounding moved it away from the pointer.
second: Option<(Point, Point)>,
press: Option<Press>,
/// Where the pointer is, snapped: the point the next press or release places.
pointer: Option<Point>,
}
/// The command the tool runs for `points`.
fn command(points: &[Point]) -> (String, Value) {
/// The command the tool runs for `points`; with `standard_anchors` off, the circle's anchors are
/// at the points.
fn command(points: &[Point], standard_anchors: bool) -> (String, Value) {
let pairs: Vec<Value> = points.iter().map(|p| json!([p.x, p.y])).collect();
("shape.circleThroughPoints".into(), json!({ "points": pairs }))
let params = if standard_anchors { json!({ "points": pairs }) } else { json!({ "points": pairs, "anchors": "points" }) };
("shape.circleThroughPoints".into(), params)
}
/// The circle through two points (the ends of a diameter) or three, as `shape.circleThroughPoints`
@@ -73,6 +160,17 @@ pub fn circle_of(points: &[Point]) -> Option<(Point, f64)> {
shapes::circle_through_points(points).filter(on_canvas)
}
/// [`circle_of`], as the tool draws it: with `standard_anchors` off, also none where the path with
/// an anchor at each point ([`shapes::circle_with_anchors_at`]) reaches past the canvas, since its
/// curves can reach slightly outside the circle.
fn drawn_circle(points: &[Point], standard_anchors: bool) -> Option<(Point, f64)> {
let fits = |(c, r): &(Point, f64)| {
let b = vectorcraft_geom::Shape::bounding_box(&shapes::circle_with_anchors_at(*c, *r, points).to_bezpath());
[b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)
};
circle_of(points).filter(|c| standard_anchors || fits(c))
}
/// With Alt, `p` moved along the line from `first` so that their distance (the diameter) is on
/// the nearest ruler tick at the current zoom, in the General unit; `p` itself without Alt, and
/// when that rounding leaves no distance.
@@ -84,43 +182,65 @@ fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point
/// Are the points two or more different points through which no circle is drawn: three on one
/// line, or a circle that would reach past the canvas?
fn too_large(points: &[Point]) -> bool {
fn too_large(points: &[Point], standard_anchors: bool) -> bool {
let distinct = points.iter().enumerate().all(|(i, p)| !points.iter().take(i).any(|q| q == p));
points.len() >= 2 && distinct && circle_of(points).is_none()
points.len() >= 2 && distinct && drawn_circle(points, standard_anchors).is_none()
}
impl CircleTool {
fn clear(&mut self) {
self.first = None;
self.second = None;
self.press = None;
self.pointer = None;
self.snap.clear();
}
/// How the second point keeps to the first: Shift's 45° steps and the construction guides.
/// How the second point keeps to the first: Shift's 45° steps and the construction guides. A
/// third point keeps to neither.
fn leave(&self, cx: &ToolContext, mods: Mods) -> Option<Leave> {
self.first.map(|a| Leave::segment(cx, a, mods.shift))
self.first.filter(|_| self.second.is_none()).map(|a| Leave::segment(cx, a, mods.shift))
}
/// The points the circle passes through as the tool shows it now.
fn points(&self) -> Vec<Point> {
let mut out: Vec<Point> = self.first.into_iter().collect();
if let Some((b, _)) = self.second {
match self.press {
// Let go where it was pressed, a press on the first point draws nothing and one on
// the second point draws the circle on the two.
Some(Press::Third { on_first: true, dragged: false, .. }) => {}
Some(Press::Third { on_second: true, dragged: false, .. }) => out.push(b),
_ => {
out.push(b);
out.extend(self.pointer);
}
}
return out;
}
match self.press {
Some(Press::First { .. }) | None => out.extend(self.pointer.filter(|_| self.first.is_some())),
// A press on the first point adds no point: a drag from it drags out a diameter.
Some(Press::Second { on_first: true, dragged, .. }) => out.extend(self.pointer.filter(|_| dragged)),
Some(Press::Second { at, dragged: false, .. }) => out.push(at),
// With `dragThird` off, a drag moves the second point.
Some(Press::Second { at, .. }) if !self.options.drag_third => out.push(at),
Some(Press::Second { snapped, dragged: true, .. }) => {
out.push(snapped);
out.extend(self.pointer);
}
Some(Press::Third { .. }) => {}
}
out
}
/// The second point as the tool shows it: none for a press on the first point.
fn second(&self) -> Option<Point> {
if let Some((b, _)) = self.second {
return Some(b);
}
match self.press {
Some(Press::Second { on_first: false, at, .. }) if !self.options.drag_third => Some(at),
Some(Press::Second { on_first: false, dragged: false, at, .. }) => Some(at),
Some(Press::Second { on_first: false, dragged: true, snapped, .. }) => Some(snapped),
_ => None,
@@ -131,18 +251,34 @@ impl CircleTool {
/// (the tool showed none), it only starts afresh.
fn draw(&mut self, points: &[Point]) -> Vec<Action> {
self.clear();
if circle_of(points).is_none() {
if drawn_circle(points, self.options.standard_anchors).is_none() {
return vec![];
}
let (c, v) = command(points);
let (c, v) = command(points, self.options.standard_anchors);
vec![Action::Exec(c, v)]
}
/// With `dragThird` off, the release of a press after the second point was placed: on the
/// second point it draws the circle on the two points, on the first it places nothing, and
/// elsewhere it draws the circle through the three, or keeps the points where none passes
/// through them.
fn third_up(&mut self, at: Point, on_first: bool, on_second: bool, dragged: bool) -> Vec<Action> {
let (Some(a), Some((b, _))) = (self.first, self.second) else { return vec![] };
if on_second && !dragged {
return self.draw(&[a, b]);
}
if (on_first && !dragged) || drawn_circle(&[a, b, at], self.options.standard_anchors).is_none() {
self.snap.clear();
return vec![];
}
self.draw(&[a, b, at])
}
/// Is the press let go at `ev` a drag: is `ev` [`DRAG_PX`] or more from the press? A release
/// nearer the press is a click, also after a drag that came back to it.
fn drags(&self, cx: &ToolContext, ev: &PointerEvent) -> bool {
match self.press {
Some(Press::First { from, .. } | Press::Second { from, .. }) => ev.pos.distance(from) >= cx.tol(DRAG_PX),
Some(Press::First { from, .. } | Press::Second { from, .. } | Press::Third { from, .. }) => ev.pos.distance(from) >= cx.tol(DRAG_PX),
None => false,
}
}
@@ -173,6 +309,13 @@ impl Tool for CircleTool {
*dragged = false;
(*at, *on_first)
}
// With `dragThird` off, a click on the third point's press: the point goes back
// to where it was pressed.
Press::Third { at, from, dragged, .. } => {
*dragged = false;
*at = self.snap.press(cx, *from, &[], None);
(*at, false)
}
};
// A click on the first point places nothing: the pointer goes back to that point, so
// the tool shows no circle.
@@ -184,10 +327,27 @@ impl Tool for CircleTool {
PointerKind::Move => {
let leave = self.leave(cx, ev.mods);
let p = self.snap.hover(cx, ev.pos, &[], leave.as_ref());
self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods)));
// Alt's rounding of the diameter is for the second point only.
let rounds = self.first.filter(|_| self.second.is_none());
self.pointer = Some(rounds.map_or(p, |a| round_diameter(cx, a, p, ev.mods)));
vec![]
}
PointerKind::Down => {
if let (Some(a), Some((b, clicked))) = (self.first, self.second) {
let at = self.snap.press(cx, ev.pos, &[], None);
let reach = cx.tol(REACH_PX);
let to_second = ev.pos.distance(b).min(ev.pos.distance(clicked));
let (mut on_first, mut on_second) = (at == a || ev.pos.distance(a) <= reach, at == b || to_second <= reach);
// A press in reach of both points is on the one it snapped to, otherwise on the
// nearer one.
if on_first && on_second {
let first = if (at == a) != (at == b) { at == a } else { ev.pos.distance(a) < to_second };
(on_first, on_second) = (first, !first);
}
self.press = Some(Press::Third { at, from: ev.pos, on_first, on_second, dragged: false });
self.pointer = Some(at);
return vec![];
}
match self.first {
None => {
let at = self.snap.press(cx, ev.pos, &[], None);
@@ -207,7 +367,28 @@ impl Tool for CircleTool {
vec![]
}
PointerKind::Drag => {
let drag_third = self.options.drag_third;
let first = self.first;
match &mut self.press {
// With `dragThird` off, the second point follows the pointer as it does before
// the press.
// The point stays where it was pressed until the press is a drag.
Some(Press::Second { at, snapped, from, on_first: false, dragged }) if !drag_third => {
*dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX);
if *dragged {
let leave = first.map(|a| Leave::segment(cx, a, ev.mods.shift));
*snapped = self.snap.drag(cx, ev.pos, leave.as_ref());
*at = first.map_or(*snapped, |a| round_diameter(cx, a, *snapped, ev.mods));
self.pointer = Some(*at);
}
}
Some(Press::Third { at, from, dragged, .. }) => {
*dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX);
if *dragged {
*at = self.snap.drag(cx, ev.pos, None);
self.pointer = Some(*at);
}
}
Some(Press::First { at, from, dragged }) => {
*dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX);
let leave = Leave::segment(cx, *at, ev.mods.shift);
@@ -230,6 +411,16 @@ impl Tool for CircleTool {
vec![]
}
PointerKind::Up => match (self.press.take(), self.first, self.pointer) {
(Some(Press::Third { at, on_first, on_second, dragged, .. }), ..) => self.third_up(at, on_first, on_second, dragged),
// With `dragThird` off, the release places the second point; let go on the first
// point, as a press there is, it places nothing.
(Some(Press::Second { at, snapped, on_first: false, .. }), Some(a), _) if !self.options.drag_third => {
if !(at == a || snapped == a || ev.pos.distance(a) <= cx.tol(REACH_PX)) {
self.second = Some((at, ev.pos));
}
self.snap.clear();
vec![]
}
(Some(Press::First { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.draw(&[at, b]),
// A click places the first point; the guides of the press go.
(Some(Press::First { .. }), ..) => {
@@ -296,22 +487,33 @@ impl Tool for CircleTool {
let mut o = self.snap.guides().to_vec();
let points = self.points();
let color = crate::draw2::FEEDBACK;
if let Some((c, r)) = circle_of(&points) {
let path = shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath();
if let Some((c, r)) = drawn_circle(&points, self.options.standard_anchors) {
// The path the release draws: with `standardAnchors` off, the one with an anchor at each point.
let path = if self.options.standard_anchors {
shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath()
} else {
shapes::circle_with_anchors_at(c, r, &points).to_bezpath()
};
// The canvas draws a dashed outline dash by dash along its whole length: a circle longer
// than DASHED_PX on screen is drawn solid instead.
let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX);
o.push(Overlay::Path { path, color, width: 1.0, dashed });
for p in &points {
o.push(Overlay::Line { a: c, b: *p, color, dashed: false });
let opts = self.options;
let lines = COLORS.get(opts.color).map_or(color, |(_, rgb)| *rgb);
if opts.radii {
for p in &points {
o.push(Overlay::Line { a: c, b: *p, color: lines, dashed: false });
}
}
let arm = cx.tol(CROSS_PX);
o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color, dashed: false });
o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color, dashed: false });
if let Some(p) = self.pointer.filter(|_| cx.measurement_labels) {
if opts.center {
let arm = cx.tol(CROSS_PX);
o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color: lines, dashed: false });
o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color: lines, dashed: false });
}
if let Some(p) = self.pointer.filter(|_| cx.measurement_labels && opts.diameter) {
o.push(Overlay::Measure { p: p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("D: {}", cx.len(2.0 * r)) });
}
} else if let Some(p) = self.pointer.filter(|_| too_large(&points)) {
} else if let Some(p) = self.pointer.filter(|_| too_large(&points, self.options.standard_anchors)) {
o.push(Overlay::Label { p, text: "Circle too large".into(), color });
}
for p in self.first.into_iter().chain(self.second()) {
@@ -323,6 +525,43 @@ impl Tool for CircleTool {
fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor {
Cursor::Crosshair
}
fn options(&self) -> Value {
let o = self.options;
let color = COLORS.get(o.color).map_or("blue", |(name, _)| *name);
json!({
"center": o.center,
"radii": o.radii,
"diameter": o.diameter,
"color": color,
"standardAnchors": o.standard_anchors,
"dragThird": o.drag_third,
})
}
/// Takes the values [`check_options`] takes.
fn check_option(&self, key: &str, value: &Value) -> Result<(), String> {
check_options(&Map::from_iter([(key.to_string(), value.clone())]))
}
/// Sets one option; a value the option does not take leaves it as it was. Switching
/// `dragThird` drops the points placed so far.
fn set_option(&mut self, key: &str, value: &Value) {
if key == "color" {
if let Some(i) = value.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)) {
self.options.color = i;
}
return;
}
let Some(on) = value.as_bool() else { return };
let was = self.options.drag_third;
if let Some(switch) = self.options.switch(key) {
*switch = on;
}
if self.options.drag_third != was {
self.clear();
}
}
}
#[cfg(test)]
+298 -2
View File
@@ -94,6 +94,302 @@ fn a_click_and_a_drag_draw_the_circle_through_three_points() {
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)]));
}
/// The lines the tool shows from the center `c`: (radius lines, arms of the center cross), each
/// with its color.
fn annotations(o: &[Overlay], c: Point) -> (Vec<[u8; 3]>, Vec<[u8; 3]>) {
let (mut radii, mut cross) = (vec![], vec![]);
for o in o {
if let Overlay::Line { a, b, color, .. } = o {
if *a == c {
radii.push(*color);
} else if a.midpoint(*b).distance(c) < 1e-9 {
cross.push(*color);
}
}
}
(radii, cross)
}
/// `center`, `radii` and `diameter` show or hide the center cross, the radius lines and the
/// diameter label, each on its own, and `color` is the color of the cross and the lines; the
/// outline stays in the feedback color. Each option lasts in [`Tool::options`].
#[test]
fn the_options_show_or_hide_the_center_radii_and_diameter_in_their_color() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = CircleTool::default();
click(&mut t, &cx, (300.0, 300.0));
t.pointer(&cx, &ev(PointerKind::Move, (380.0, 360.0), Mods::default()));
let c = Point::new(340.0, 330.0);
let blue = crate::draw2::FEEDBACK;
assert_eq!(annotations(&t.overlays(&cx), c), (vec![blue; 2], vec![blue; 2]));
let diameter = |t: &CircleTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Measure { .. }));
assert!(diameter(&t));
t.set_option("center", &json!(false));
assert_eq!(annotations(&t.overlays(&cx), c), (vec![blue; 2], vec![]));
t.set_option("radii", &json!(false));
assert_eq!(annotations(&t.overlays(&cx), c), (vec![], vec![]));
assert!(diameter(&t));
t.set_option("diameter", &json!(false));
assert!(!diameter(&t));
t.set_option("center", &json!(true));
t.set_option("radii", &json!(true));
t.set_option("color", &json!("red"));
let red = [0xe5, 0x2d, 0x27];
let o = t.overlays(&cx);
assert_eq!(annotations(&o, c), (vec![red; 2], vec![red; 2]));
assert!(o.iter().any(|o| matches!(o, Overlay::Path { color, .. } if *color == blue)), "{o:?}");
assert_eq!(t.options(), json!({"center": true, "radii": true, "diameter": false, "color": "red", "standardAnchors": true, "dragThird": true}));
// A value an option does not take leaves it as it was.
for (key, value) in [("color", json!("orange")), ("center", json!("no")), ("radii", json!(0))] {
t.set_option(key, &value);
}
assert_eq!(t.options()["color"], json!("red"));
assert_eq!((&t.options()["center"], &t.options()["radii"]), (&json!(true), &json!(true)));
}
/// With `standardAnchors` off, the circle's anchors go at the points it was drawn through.
#[test]
fn anchors_at_the_points_asks_for_them() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = CircleTool::default();
t.set_option("standardAnchors", &json!(false));
let acts = drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default());
let points = json!([[300.0, 300.0], [380.0, 360.0]]);
assert_eq!(acts, vec![Action::Exec("shape.circleThroughPoints".into(), json!({"points": points, "anchors": "points"}))]);
}
/// With `standardAnchors` off, the tool shows the path with an anchor at each point, the one its
/// release draws.
#[test]
fn anchors_at_the_points_show_the_path_they_draw() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = CircleTool::default();
t.set_option("standardAnchors", &json!(false));
click(&mut t, &cx, (300.0, 300.0));
t.pointer(&cx, &ev(PointerKind::Down, (380.0, 300.0), Mods::default()));
t.pointer(&cx, &ev(PointerKind::Drag, (310.0, 340.0), Mods::default()));
let points = [Point::new(300.0, 300.0), Point::new(380.0, 300.0), Point::new(310.0, 340.0)];
let (c, r) = circle_of(&points).expect("a circle");
let want = shapes::circle_with_anchors_at(c, r, &points).to_bezpath();
let o = t.overlays(&cx);
assert!(o.iter().any(|o| matches!(o, Overlay::Path { path, .. } if *path == want)), "{o:?}");
}
/// With `standardAnchors` off, a circle within 1 pt of the canvas edge whose path with anchors at
/// the points curves past that edge is not shown and not drawn; with standard anchors it is.
#[test]
fn anchors_at_the_points_keep_the_path_on_the_canvas() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let r = MAX_COORD - 1.0;
let at = |deg: f64| (r * deg.to_radians().cos(), r * deg.to_radians().sin());
let points = [at(0.0), at(70.0), at(180.0)];
let geom: Vec<Point> = points.iter().map(|(x, y)| Point::new(*x, *y)).collect();
assert!(drawn_circle(&geom, true).is_some());
assert_eq!(drawn_circle(&geom, false), None);
let mut t = CircleTool::default();
t.set_option("standardAnchors", &json!(false));
click(&mut t, &cx, points[0]);
t.pointer(&cx, &ev(PointerKind::Down, points[1], Mods::default()));
t.pointer(&cx, &ev(PointerKind::Drag, points[2], Mods::default()));
// No outline at all: at this size the tool would draw it solid, not dashed.
let o = t.overlays(&cx);
assert!(!o.iter().any(|o| matches!(o, Overlay::Path { .. })), "{o:?}");
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, points[2], Mods::default())), vec![]);
}
/// With `dragThird` off, a click in reach of both placed points is on the nearer one: nearer the
/// first point it places nothing, nearer the second it draws the circle on the two.
#[test]
fn with_third_point_by_dragging_off_a_click_near_both_points_takes_the_nearer() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = CircleTool::default();
t.set_option("dragThird", &json!(false));
click(&mut t, &cx, (100.0, 100.0));
assert_eq!(click(&mut t, &cx, (104.0, 100.0)), vec![]);
assert_eq!(click(&mut t, &cx, (101.0, 100.0)), vec![]);
assert_eq!(click(&mut t, &cx, (103.0, 100.0)), circle(&[(100.0, 100.0), (104.0, 100.0)]));
}
/// With `dragThird` off, a press on the second point shows the circle on the two points, which its
/// release draws, and a press on the first point shows none.
#[test]
fn with_third_point_by_dragging_off_a_press_shows_the_circle_its_release_draws() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = CircleTool::default();
t.set_option("dragThird", &json!(false));
click(&mut t, &cx, (100.0, 100.0));
click(&mut t, &cx, (200.0, 100.0));
t.pointer(&cx, &ev(PointerKind::Down, (101.0, 101.0), Mods::default()));
assert_eq!(preview(&t.overlays(&cx)), None);
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (101.0, 101.0), Mods::default())), vec![]);
t.pointer(&cx, &ev(PointerKind::Down, (202.0, 101.0), Mods::default()));
let o = t.overlays(&cx);
assert!(near(preview(&o).expect("the circle is shown"), Rect::new(100.0, 50.0, 200.0, 150.0)), "{o:?}");
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (202.0, 101.0), Mods::default())), circle(&[(100.0, 100.0), (200.0, 100.0)]));
}
/// With `dragThird` off, a press that moves less than 2 screen points keeps the point where it was
/// pressed, for the second point and for the third.
#[test]
fn with_third_point_by_dragging_off_a_short_move_keeps_the_pressed_point() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let (down, drag, up) = (PointerKind::Down, PointerKind::Drag, PointerKind::Up);
let mut t = CircleTool::default();
t.set_option("dragThird", &json!(false));
click(&mut t, &cx, (100.0, 100.0));
t.pointer(&cx, &ev(down, (200.0, 100.0), Mods::default()));
t.pointer(&cx, &ev(drag, (201.0, 100.0), Mods::default()));
assert_eq!(t.pointer(&cx, &ev(up, (200.0, 100.0), Mods::default())), vec![]);
t.pointer(&cx, &ev(down, (150.0, 200.0), Mods::default()));
t.pointer(&cx, &ev(drag, (151.0, 200.0), Mods::default()));
let three = circle(&[(100.0, 100.0), (200.0, 100.0), (150.0, 200.0)]);
assert_eq!(t.pointer(&cx, &ev(up, (150.0, 200.0), Mods::default())), three);
}
/// With `dragThird` off, a second click places the second point and a third click draws the circle
/// through the three; a click on the second point again (as a double-click there does) draws the
/// circle on the two; a second point let go on the first places nothing; a drag from the first
/// point still draws the circle on its diameter.
#[test]
fn with_third_point_by_dragging_off_three_clicks_draw_the_circle() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = CircleTool::default();
t.set_option("dragThird", &json!(false));
click(&mut t, &cx, (300.0, 300.0));
assert_eq!(click(&mut t, &cx, (380.0, 300.0)), vec![]);
t.pointer(&cx, &ev(PointerKind::Move, (300.0, 360.0), Mods::default()));
let o = t.overlays(&cx);
assert!(near(preview(&o).expect("the circle through the three is shown"), Rect::new(290.0, 280.0, 390.0, 380.0)), "{o:?}");
assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Anchor { .. })).count(), 2, "{o:?}");
// A click on the first point places nothing and keeps both points.
assert_eq!(click(&mut t, &cx, (300.0, 300.0)), vec![]);
assert!(t.busy());
assert_eq!(click(&mut t, &cx, (300.0, 360.0)), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)]));
assert!(!t.busy());
// The events of a double-click on the second point: its first click places it, the second
// draws the circle on the two points, and the double-click event that follows adds nothing.
click(&mut t, &cx, (100.0, 100.0));
assert_eq!(click(&mut t, &cx, (200.0, 100.0)), vec![]);
assert_eq!(click(&mut t, &cx, (200.0, 100.0)), circle(&[(100.0, 100.0), (200.0, 100.0)]));
assert_eq!(t.pointer(&cx, &ev(PointerKind::DoubleClick, (200.0, 100.0), Mods::default())), vec![]);
assert!(!t.busy());
// A drag that moves the second point places it where it is let go.
click(&mut t, &cx, (100.0, 100.0));
assert_eq!(drag(&mut t, &cx, (150.0, 100.0), &[(180.0, 100.0), (200.0, 100.0)], Mods::default()), vec![]);
assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)]));
// Three points on one line keep the two placed: the next click elsewhere draws.
click(&mut t, &cx, (100.0, 100.0));
click(&mut t, &cx, (200.0, 100.0));
assert_eq!(click(&mut t, &cx, (300.0, 100.0)), vec![]);
assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)]));
// A second press elsewhere, dragged back and let go on the first point, places nothing: the
// next click places the second point.
click(&mut t, &cx, (100.0, 100.0));
assert_eq!(drag(&mut t, &cx, (200.0, 100.0), &[(150.0, 100.0), (100.0, 100.0)], Mods::default()), vec![]);
assert!(t.busy());
assert_eq!(click(&mut t, &cx, (200.0, 100.0)), vec![]);
assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)]));
// A drag from the first point.
assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default()), circle(&[(300.0, 300.0), (380.0, 360.0)]));
// Switching the option drops the points placed so far.
click(&mut t, &cx, (100.0, 100.0));
t.set_option("dragThird", &json!(true));
assert!(!t.busy());
}
/// With `dragThird` off, a drag of the second or third point ends where it is let go, also when the
/// release is away from the last drag.
#[test]
fn with_third_point_by_dragging_off_a_drag_ends_where_it_is_let_go() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let (down, drag, up) = (PointerKind::Down, PointerKind::Drag, PointerKind::Up);
let mut t = CircleTool::default();
t.set_option("dragThird", &json!(false));
click(&mut t, &cx, (300.0, 300.0));
t.pointer(&cx, &ev(down, (350.0, 300.0), Mods::default()));
t.pointer(&cx, &ev(drag, (380.0, 300.0), Mods::default()));
assert_eq!(t.pointer(&cx, &ev(up, (400.0, 300.0), Mods::default())), vec![]);
t.pointer(&cx, &ev(down, (350.0, 350.0), Mods::default()));
t.pointer(&cx, &ev(drag, (320.0, 380.0), Mods::default()));
assert_eq!(t.pointer(&cx, &ev(up, (300.0, 400.0), Mods::default())), circle(&[(300.0, 300.0), (400.0, 300.0), (300.0, 400.0)]));
}
/// With `dragThird` off, an Alt-click places the second point where Alt's rounding of the diameter
/// puts it (88 pt rounds to 90 pt at 100%), and the tool shows it there: the marker, the preview,
/// the circle on the two points and the circle through three all use it.
#[test]
fn an_alt_click_places_the_second_point_where_it_is_shown() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let alt = Mods { alt: true, ..Mods::default() };
let mut t = CircleTool::default();
t.set_option("dragThird", &json!(false));
click(&mut t, &cx, (300.0, 300.0));
t.pointer(&cx, &ev(PointerKind::Down, (388.0, 300.0), alt));
t.pointer(&cx, &ev(PointerKind::Up, (388.0, 300.0), alt));
t.pointer(&cx, &ev(PointerKind::Move, (300.0, 390.0), Mods::default()));
let o = t.overlays(&cx);
let second = Point::new(390.0, 300.0);
assert!(o.iter().any(|o| matches!(o, Overlay::Anchor { p, .. } if p.distance(second) < 1e-9)), "{o:?}");
// (300, 300), (390, 300) and (300, 390): center (345, 345), radius 45·√2.
let r = 45.0 * 2f64.sqrt();
assert!(near(preview(&o).unwrap(), Rect::new(345.0 - r, 345.0 - r, 345.0 + r, 345.0 + r)), "{o:?}");
assert_eq!(click(&mut t, &cx, (300.0, 390.0)), circle(&[(300.0, 300.0), (390.0, 300.0), (300.0, 390.0)]));
click(&mut t, &cx, (300.0, 300.0));
t.pointer(&cx, &ev(PointerKind::Down, (388.0, 300.0), alt));
t.pointer(&cx, &ev(PointerKind::Up, (388.0, 300.0), alt));
assert_eq!(click(&mut t, &cx, (390.0, 300.0)), circle(&[(300.0, 300.0), (390.0, 300.0)]));
// In inches the ticks are farther apart, and the rounding can move the point more than the
// 3 screen points a click reaches: the second click of a double-click, where the first let go,
// still draws the circle on the two points, at the rounded point.
let inches = ToolContext { unit: vectorcraft_doc::Unit::Inches, ..cx };
let d = 94.4;
let rounded = vectorcraft_doc::Unit::Inches.snap_to_ruler_tick(d, 1.0);
assert!((rounded - d).abs() > 3.0, "{rounded}");
click(&mut t, &inches, (300.0, 300.0));
t.pointer(&inches, &ev(PointerKind::Down, (300.0 + d, 300.0), alt));
t.pointer(&inches, &ev(PointerKind::Up, (300.0 + d, 300.0), alt));
assert_eq!(click(&mut t, &inches, (300.0 + d, 300.0)), circle(&[(300.0, 300.0), (300.0 + rounded, 300.0)]));
}
/// `tool.setOption`'s check takes the values the options take and nothing else.
#[test]
fn check_options_takes_only_the_values_the_options_take() {
let ok = json!({"center": false, "radii": true, "diameter": false, "color": "gray", "standardAnchors": false, "dragThird": false});
assert_eq!(check_options(ok.as_object().unwrap()), Ok(()));
// The tool's own check, which `tool.setOption` also runs, takes the same values.
let tool = CircleTool::default();
assert_eq!(tool.check_options(ok.as_object().unwrap()), Ok(()));
for (bad, error) in [
(json!({"center": 1}), "`center` must be true or false"),
(json!({"dragThird": null}), "`dragThird` must be true or false"),
(json!({"color": "orange"}), "`color` must be one of red, blue, magenta, green, black, gray"),
(json!({"colour": "red"}), "unknown Circle tool option `colour`"),
] {
assert_eq!(check_options(bad.as_object().unwrap()), Err(error.to_string()), "{bad}");
assert_eq!(tool.check_options(bad.as_object().unwrap()), Err(error.to_string()), "{bad}");
}
}
/// A drag ends where it is let go, also when the release is away from the last drag: from a first
/// press, from a second press, and from a press on the first point. A release within 2 screen
/// points of a second press is still a click and keeps the point of the press.
@@ -288,8 +584,8 @@ fn points_on_one_line_say_the_circle_is_too_large() {
assert_eq!(label(&t), None, "a circle is shown");
t.pointer(&cx, &ev(PointerKind::Drag, (200.0, 200.0), Mods::default()));
assert_eq!(label(&t), None, "the third point is on the second");
assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)]));
assert!(!too_large(&[Point::new(0.0, 0.0)]) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)]));
assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], true));
assert!(!too_large(&[Point::new(0.0, 0.0)], true) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)], true));
}
/// Escape drops the first point; so do a dropped press and an edit made outside the tool. A
+2
View File
@@ -524,6 +524,7 @@ id = "LivePaintBucket"
group = "Colour and gradient"
shown_when = [
"The Live Paint Bucket where a click paints nothing: away from Live Paint groups and the selected paths' regions, or over a part the Paint Fills and Paint Strokes options (and Shift) leave unpainted.",
"The Fill Area tool outside every area that visible, unlocked paths enclose, where a click adds nothing.",
"With Use Precise Cursors on, the crosshair shows instead.",
]
hotspot = "The drop the paint pours onto."
@@ -534,6 +535,7 @@ id = "LivePaintBucketFace"
group = "Colour and gradient"
shown_when = [
"The Live Paint Bucket over a face of a Live Paint group, or a region of the selected paths, that a click fills.",
"The Fill Area tool over an enclosed area, where a click adds a path of that area.",
"With Use Precise Cursors on, the crosshair shows instead.",
]
hotspot = "The drop the paint pours onto."
+3 -3
View File
@@ -1657,7 +1657,7 @@ impl DirectSelectionTool {
// The grabbed anchor snaps and the others follow it. Shift keeps the move at its
// angle, and the anchor slides along it onto what Smart Guides find there (#886).
self.guides.clear();
if segment && let Some(grid) = &self.partial_grid {
if segment && let Some(grid) = &mut self.partial_grid {
(d, self.guides) = if ev.mods.shift { grid.snap_along(cx, grab, d, false) } else { grid.snap(cx, grab, d, false) };
} else if let Some(snap) = &self.anchor_snap {
let shift = ev.mods.shift.then(|| Leave::segment(cx, grab, true));
@@ -1710,7 +1710,7 @@ impl DirectSelectionTool {
&& let Some(snap) = &self.partial_snap
{
let held = grab.unwrap_or(hold);
if let Some(grid) = &self.partial_grid {
if let Some(grid) = &mut self.partial_grid {
(d, self.guides) = if ev.mods.shift { grid.snap_along(cx, held, d, false) } else { grid.snap(cx, held, d, false) };
} else {
let shift = ev.mods.shift.then(|| Leave::segment(cx, held, true));
@@ -1730,7 +1730,7 @@ impl DirectSelectionTool {
let shift = ev.mods.shift.then(|| Leave::segment(cx, grab, true));
let (q, guides) = snap.snap_from(cx, grab + (p - start), shift.as_ref());
(d, self.guides) = (q - grab, guides);
} else if let Some(snap) = &self.move_snap {
} else if let Some(snap) = &mut self.move_snap {
(d, self.guides) = if ev.mods.shift { snap.snap_along(cx, hold, d, ev.mods.alt) } else { snap.snap(cx, hold, d, ev.mods.alt) };
}
self.snapped = snapped(d, unsnapped, ev.mods.shift, &self.guides);
+6
View File
@@ -707,6 +707,12 @@ impl Targets {
self
}
/// These targets without the ruler guides, once they stop showing during the drag they were
/// gathered for (#8363).
pub(crate) fn forget_rulers(&mut self) {
self.rulers.clear();
}
/// The ruler guides alone ([`Self::with_rulers`]): what a dragged selection's grabbed point
/// still snaps to with View → Snap to Point when Smart Guides line the selection up.
pub(crate) fn rulers(cx: &ToolContext) -> Self {
+6
View File
@@ -226,6 +226,12 @@ pub trait Tool: Send {
fn ends_on_escape(&self, _cx: &ToolContext) -> bool {
false
}
/// The point a path the tool is drawing goes on from, and the direction the path arrives there
/// in (none for a path of one point), while the tool draws one: the Quick Pen toolbar sits
/// beside it.
fn drawing_end(&self, _cx: &ToolContext) -> Option<(Point, Option<Vec2>)> {
None
}
/// Does the tool want typed text (Type tool editing)? Single-key shortcuts are suppressed.
fn wants_text(&self) -> bool {
false
+180 -57
View File
@@ -7,15 +7,17 @@
//! sharp-corner arc (it turns through the arc size, 180° by default, and meets the path before it
//! at a corner). Alt (Option) pressed and let go on its own switches to the next action. C flips
//! the last sharp-corner arc to the other side of its chord, and [ and ] make the arc size 15°
//! smaller or larger, for the last sharp-corner arc and the ones after it. A click on the first
//! smaller or larger, for the last sharp-corner arc and the ones after it; during a drag they
//! change the arc being dragged. A dragged piece ends where the press is let go. A click on the first
//! point closes the path, a click on an end of an open path goes on drawing from it, and Escape
//! or Enter ends the path. The path's points show as circles, without handles, and a preview
//! shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step.
use std::f64::consts::{FRAC_PI_2, PI};
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath, Vec2};
use crate::draw2::FEEDBACK;
@@ -39,6 +41,11 @@ const DRAG_PX: f64 = 3.0;
/// A continuous arc whose end lies within this angle (radians) of straight ahead, or of straight
/// behind, is drawn as a line: no circle runs there in the path's direction.
const STRAIGHT: f64 = 1e-6;
/// The notice the tool asks for after each of its own edits, to see the path as the document then
/// has it.
const DRAWN: &str = "drawn";
/// The notice after a press's piece is committed.
const PLACED: &str = "placed";
/// What the next click adds.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -214,21 +221,50 @@ pub fn build(base: &SubPath, pieces: &[Piece], closed: bool) -> SubPath {
sp
}
/// The path being drawn: subpath `si` of `id`, whose points were `base` before the tool drew on
/// (both none until the engine made a new path), then `pieces`. A new path starts at `start`.
#[derive(Clone, Debug, PartialEq)]
/// The path being drawn: subpath `si` of `id` (none until the engine made a new path, which starts
/// at `start`), and the `pieces` the tool added to it, each after the number of points in `kept`
/// the subpath had before it. `seen` is the path object as the document had it after the tool's
/// last edit, pixel alignment and other changes the engine makes after each edit included, and
/// `before_press` as it was when the press under way began. A piece is drawn again on the points
/// the document holds before it, so the points before it stay as they are.
#[derive(Clone, Debug, Default, PartialEq)]
struct Drawing {
id: Option<NodeId>,
si: usize,
base: Option<SubPath>,
start: Option<Point>,
pieces: Vec<Piece>,
kept: Vec<usize>,
seen: Option<Arc<Node>>,
before_press: Option<Arc<Node>>,
/// The document's revision ([`ToolContext::revision`]) after the tool's last edit.
revision: (u64, u64),
}
/// The node `id` as the document shares it, found through the document's index.
fn shared_node(doc: &Document, id: NodeId) -> Option<&Arc<Node>> {
let path = doc.index_path(id)?;
let (first, rest) = path.split_first()?;
let mut cur = doc.layers.get(*first)?;
for &i in rest {
cur = cur.children()?.get(i)?;
}
Some(cur)
}
/// Is `now` the node `then` was: the same shared node, or one equal to it?
fn same_node(now: &Node, then: &Arc<Node>) -> bool {
std::ptr::eq(now, Arc::as_ptr(then)) || *now == **then
}
impl Drawing {
/// The subpath as the tool drew it.
fn drawn(&self) -> Option<SubPath> {
Some(build(self.base.as_ref()?, &self.pieces, false))
fn push(&mut self, piece: Piece, kept: usize) {
self.pieces.push(piece);
self.kept.push(kept);
}
fn pop(&mut self) {
self.pieces.pop();
self.kept.pop();
}
}
@@ -266,30 +302,41 @@ fn point_tol(cx: &ToolContext) -> f64 {
cx.tol(5.0).max(cx.point_tol())
}
/// Asks to see the path once the actions before it are applied.
fn drawn() -> Action {
Action::Notify(DRAWN.into())
}
impl QuickPenTool {
/// The subpath being drawn, while it is selected, editable, open and still exactly what the tool
/// drew: an edit made outside the tool (a point moved, the path it went on from changed) ends
/// the drawing, so the next piece does not undo it.
/// The subpath being drawn, while it is selected, editable, open and its path still exactly as
/// the tool's last edit left it: an edit made to the path outside the tool (a point moved, its
/// look changed, the path it went on from changed), also during a press, ends the drawing, so
/// the next piece does not undo it.
fn active<'a>(&self, cx: &'a ToolContext) -> Option<(NodeId, &'a SubPath)> {
let dr = self.drawing.as_ref()?;
let id = dr.id?;
if !selected_alone(cx, id) || !cx.doc.is_editable(id) {
return None;
}
let sp = cx.doc.node(id)?.path_data()?.subpaths.get(dr.si)?;
(!sp.closed && dr.drawn()?.anchors == sp.anchors).then_some((id, sp))
let node = cx.doc.node(id)?;
if !same_node(node, dr.seen.as_ref()?) {
return None;
}
let sp = node.path_data()?.subpaths.get(dr.si)?;
(!sp.closed).then_some((id, sp))
}
/// `path.quickPen`'s params for the path being drawn, closed when `closed`.
/// `path.quickPen`'s params for the path being drawn: its last piece on the points before it,
/// closed when `closed`.
fn params(&self, closed: bool) -> Value {
let Some(dr) = &self.drawing else { return json!({}) };
let pieces: Vec<Value> = dr.pieces.iter().map(Piece::to_json).collect();
let pieces: Vec<Value> = dr.pieces.last().map(Piece::to_json).into_iter().collect();
let mut v = json!({"pieces": pieces});
match (dr.id, dr.start) {
(Some(id), _) => {
v["id"] = json!(id.0);
v["subpath"] = json!(dr.si);
v["keep"] = json!(dr.base.as_ref().map_or(1, |b| b.anchors.len().max(1)));
v["keep"] = json!(dr.kept.last().copied().unwrap_or(1).max(1));
}
(None, Some(s)) => v["start"] = json!([s.x, s.y]),
(None, None) => {}
@@ -300,15 +347,57 @@ impl QuickPenTool {
v
}
/// The last piece, while it is a sharp-corner arc and no press is under way.
/// The last piece, while it is a sharp-corner arc: the one drawn last while no press is under
/// way, or the one a press is drawing.
fn last_sharp_arc(&self, cx: &ToolContext) -> Option<Piece> {
if self.press.is_some() {
return None;
match self.press {
Some(pr) if !pr.begun => return None,
Some(_) => self.held(cx).then_some(())?,
None => self.active(cx).map(|_| ())?,
}
self.active(cx)?;
self.drawing.as_ref()?.pieces.last().copied().filter(|p| p.stroke == Stroke::SharpArc)
}
/// During a press: is the path being drawn still active, and the document as the tool's last
/// preview left it? A preview starts again from the document as the press found it, so after
/// an edit made outside the tool the press previews no more.
fn held(&self, cx: &ToolContext) -> bool {
self.active(cx).is_some() && self.drawing.as_ref().is_some_and(|dr| dr.revision == cx.revision)
}
/// Moves the end of the piece a press draws to `p` (snapped) and previews it. An edit made
/// outside the tool since the last preview ends the drawing instead: the press then commits
/// the document as it is.
fn drag_to(&mut self, cx: &ToolContext, p: Point) -> Vec<Action> {
if !self.held(cx) {
self.drawing = None;
self.snap.clear();
return vec![];
}
// The snapping leaves from the point before the piece being dragged, as the press found it.
let from = self.drawing.as_ref().and_then(|dr| {
let sp = dr.before_press.as_ref()?.path_data()?.subpaths.get(dr.si)?;
sp.anchors.get(dr.kept.last()?.checked_sub(1)?).map(|a| Leave::segment(cx, a.p, false).without_contact())
});
let q = self.snap.drag(cx, p, from.as_ref());
let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) else { return vec![] };
if last.to == q {
return vec![];
}
last.to = q;
vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()]
}
/// Draws the path again after its last piece changed: a preview while a press draws that
/// piece, else a step of its own.
fn redraw(&self) -> Vec<Action> {
if self.press.is_some_and(|pr| pr.begun) {
vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()]
} else {
vec![Action::Exec(COMMAND.into(), self.params(false)), drawn()]
}
}
fn piece_to(&self, to: Point) -> Piece {
Piece { to, stroke: self.action, turn: self.turn, flip: false }
}
@@ -332,9 +421,9 @@ impl QuickPenTool {
_ => return vec![],
};
if sp.anchors.len() >= 2 && p.distance(first) <= tol && p.distance(first) <= p.distance(last) {
let piece = self.piece_to(first);
let (piece, kept) = (self.piece_to(first), sp.anchors.len());
if let Some(dr) = self.drawing.as_mut() {
dr.pieces.push(piece);
dr.push(piece, kept);
}
let out = vec![Action::Exec(COMMAND.into(), self.params(true))];
self.drawing = None;
@@ -345,27 +434,25 @@ impl QuickPenTool {
}
let from = self.leave(cx).map(|l| l.1);
let q = self.snap.press(cx, p, &[id], from.as_ref());
let piece = self.piece_to(q);
let (piece, kept) = (self.piece_to(q), sp.anchors.len());
if let Some(dr) = self.drawing.as_mut() {
dr.pieces.push(piece);
dr.push(piece, kept);
dr.before_press = shared_node(cx.doc, id).cloned();
}
self.press = Some(Press { at: p, dragged: false, begun: true });
return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false))];
return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false)), drawn()];
}
if let Some((id, si, at_first)) = open_end_at(cx, p, tol, None)
&& cx.doc.is_editable(id)
&& let Some(sp) = cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si))
{
// From its start, `continue_from` reverses the path first.
let mut base = sp.clone();
if at_first {
base.reverse();
}
self.drawing = Some(Drawing { id: Some(id), si, base: Some(base), start: None, pieces: vec![] });
return continue_from(cx, id, si, at_first);
// From its start, `continue_from` reverses the path first; the tool then sees it.
self.drawing = Some(Drawing { id: Some(id), si, ..Drawing::default() });
let mut out = continue_from(cx, id, si, at_first);
out.push(drawn());
return out;
}
let q = self.snap.press(cx, p, &[], None);
self.drawing = Some(Drawing { id: None, si: 0, base: None, start: Some(q), pieces: vec![] });
self.drawing = Some(Drawing { start: Some(q), ..Drawing::default() });
vec![Action::Exec(COMMAND.into(), self.params(false)), Action::Notify("created".into())]
}
@@ -427,36 +514,61 @@ impl Tool for QuickPenTool {
}
pr.dragged = true;
self.press = Some(pr);
// The snapping leaves from the point before the piece being dragged.
let from = self.drawing.as_ref().and_then(|dr| {
let sp = build(dr.base.as_ref()?, dr.pieces.split_last().map_or(&[][..], |(_, rest)| rest), false);
sp.anchors.last().map(|a| Leave::segment(cx, a.p, false).without_contact())
});
let q = self.snap.drag(cx, p, from.as_ref());
if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) {
last.to = q;
if !pr.begun {
return vec![];
}
vec![Action::Preview(COMMAND.into(), self.params(false))]
self.drag_to(cx, p)
}
PointerKind::Up => {
self.snap.clear();
match self.press.take() {
Some(pr) if pr.begun => vec![Action::Commit],
let out = match self.press {
// The piece ends where the press is let go, also past the last drag.
Some(pr) if pr.begun => {
let mut out = vec![];
if pr.dragged || p.distance(pr.at) >= cx.tol(DRAG_PX) {
out = self.drag_to(cx, p);
} else if self.active(cx).is_none() {
// An edit made outside the tool during the press ends the path.
self.drawing = None;
}
// With Real-time Drawing off, the commit applies the piece.
out.extend([Action::Commit, Action::Notify(PLACED.into())]);
out
}
_ => vec![],
};
if let Some(dr) = self.drawing.as_mut() {
dr.before_press = None;
}
self.press = None;
self.snap.clear();
out
}
PointerKind::DoubleClick | PointerKind::TripleClick => vec![],
}
}
fn notify(&mut self, cx: &ToolContext, what: &str) {
let Some(dr) = self.drawing.as_mut() else { return };
if what == "created"
&& let [id] = cx.selection.objects.as_slice()
&& let Some(base) = cx.doc.node(*id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.first())
&& let Some(dr) = self.drawing.as_mut()
&& let Some(node) = shared_node(cx.doc, *id).filter(|n| n.path_data().is_some_and(|pd| !pd.subpaths.is_empty()))
&& dr.id.is_none()
{
(dr.id, dr.si, dr.base, dr.start) = (Some(*id), 0, Some(base.clone()), None);
(dr.id, dr.si, dr.start, dr.seen) = (Some(*id), 0, None, Some(node.clone()));
} else if (what == DRAWN || what == PLACED)
&& let Some(id) = dr.id
{
dr.seen = shared_node(cx.doc, id).cloned();
dr.revision = cx.revision;
// Once committed, a piece that added no point to the path (the command refused it) is
// not kept for C and [ ] to change.
let points = dr.seen.as_ref().and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(dr.si)).map(|sp| sp.anchors.len());
if what == PLACED
&& let (Some(points), Some(&kept)) = (points, dr.kept.last())
&& points <= kept
{
dr.pop();
}
}
}
@@ -465,6 +577,11 @@ impl Tool for QuickPenTool {
self.active(cx).is_some()
}
fn drawing_end(&self, cx: &ToolContext) -> Option<(Point, Option<Vec2>)> {
let (_, sp) = self.active(cx)?;
Some((sp.anchors.last()?.p, arrival(sp)))
}
fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool {
match key {
ToolKey::Letter('c') => self.last_sharp_arc(cx).is_some(),
@@ -475,13 +592,19 @@ impl Tool for QuickPenTool {
}
/// A dropped press does not end the path being drawn: the piece it added goes.
fn drop_press(&mut self, _cx: &ToolContext) -> Vec<Action> {
/// The drawing goes on only when the path is back as it was before the press.
fn drop_press(&mut self, cx: &ToolContext) -> Vec<Action> {
self.snap.clear();
if self.press.take().is_some_and(|pr| pr.begun)
&& let Some(dr) = self.drawing.as_mut()
{
dr.pieces.pop();
dr.pop();
let now = dr.id.and_then(|id| cx.doc.node(id));
match (now, dr.before_press.take()) {
(Some(now), Some(before)) if same_node(now, &before) => dr.seen = Some(before),
_ => self.drawing = None,
}
}
self.snap.clear();
vec![]
}
@@ -495,7 +618,7 @@ impl Tool for QuickPenTool {
if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) {
last.flip = !last.flip;
}
vec![Action::Exec(COMMAND.into(), self.params(false))]
self.redraw()
}
ToolKey::BracketLeft | ToolKey::BracketRight => {
let by = if key == ToolKey::BracketLeft { -TURN_STEP } else { TURN_STEP };
@@ -511,17 +634,17 @@ impl Tool for QuickPenTool {
if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) {
last.turn = turn;
}
vec![Action::Exec(COMMAND.into(), self.params(false))]
self.redraw()
}
ToolKey::AltTap => {
self.action = self.action.next();
// A drag under way draws its piece with the new action.
if self.press.is_some_and(|pr| pr.begun) {
if self.press.is_some_and(|pr| pr.begun) && self.held(cx) {
let (action, turn) = (self.action, self.turn);
if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) {
(last.stroke, last.turn, last.flip) = (action, turn, false);
}
return vec![Action::Preview(COMMAND.into(), self.params(false))];
return vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()];
}
vec![]
}
+18 -3
View File
@@ -309,10 +309,24 @@ impl MoveSnap {
Self { bounds, targets: None, points: None, copy_targets: None, copy_points: None, rulers: None, by_edge: false }
}
/// The ruler guides stopped showing since the move began (View › Hide Guides, or Trim View,
/// #8363): the move no longer snaps to them, for the rest of it, while its other targets stay.
/// They were gathered when it began, and nothing pulls toward a guide the canvas does not draw.
fn forget_hidden_rulers(&mut self, cx: &ToolContext) {
if cx.guides {
return;
}
self.rulers = None;
for t in [&mut self.points, &mut self.copy_points].into_iter().flatten() {
t.forget_rulers();
}
}
/// The move (`copy`: the copy) by `d` of the selection grabbed at `start`, snapped, and its
/// guides. With Smart Guides › Snap to Last Location, a move within Snapping Tolerance of where
/// it began goes back there before anything else snaps ([`Targets::snap_back`]).
pub(crate) fn snap(&self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec<Overlay>) {
pub(crate) fn snap(&mut self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec<Overlay>) {
self.forget_hidden_rulers(cx);
let (targets, points) = if copy { (&self.copy_targets, &self.copy_points) } else { (&self.targets, &self.points) };
if let Some(ov) = targets.as_ref().and_then(|t| t.snap_back(self.bounds, d, cx.snap_tol())) {
return (Vec2::ZERO, ov);
@@ -391,7 +405,8 @@ impl MoveSnap {
/// passes an anchor or crosses a ruler guide ([`Targets::snap_point_along`]). A move of zero
/// length does not snap, and Snap to Last Location goes back to where the move began first, as
/// in [`Self::snap`].
pub(crate) fn snap_along(&self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec<Overlay>) {
pub(crate) fn snap_along(&mut self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec<Overlay>) {
self.forget_hidden_rulers(cx);
let len = d.hypot();
if !len.is_finite() || len <= 1e-9 {
return (d, vec![]);
@@ -1957,7 +1972,7 @@ impl SelectionTool {
}
let mut d = move_delta(start, p, m.shift, cx.constrain_angle);
let unsnapped = d;
if let Some(snap) = &self.moving {
if let Some(snap) = &mut self.moving {
(d, self.guides) = if m.shift { snap.snap_along(cx, hold, d, m.alt) } else { snap.snap(cx, hold, d, m.alt) };
}
// Shift has already constrained `d`: any change is a snap.
+1 -1
View File
@@ -2198,7 +2198,7 @@ fn move_follows_the_while_moving_option() {
let p = paint();
let pixel_snap = PixelSnap { moving: false, ..PixelSnap::default() };
let c = ToolContext { snap_to_pixel: true, pixel_snap, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) };
let snap = MoveSnap::new(&c);
let mut snap = MoveSnap::new(&c);
let (dv, _) = snap.snap(&c, Point::new(150.0, 150.0), Vec2::new(3.3, 4.6), false);
assert!((dv - Vec2::new(3.3, 4.6)).hypot() < 1e-9, "{dv:?}");
let on = ToolContext { pixel_snap: PixelSnap::default(), ..c };
+4
View File
@@ -78,6 +78,8 @@ const ROWS: &[Row] = &[
(&["star"], None, &["points"]),
// The Ellipse dialog's Anchors.
(&["ellipse"], None, &["anchors"]),
// Circle Tool Options (`circle::CircleTool`).
(&[crate::circle::ID], None, &["center", "radii", "diameter", "color", "standardAnchors", "dragThird"]),
(&["freeTransform"], None, &["constrain"]),
// Shape Builder Tool Options (`builder::ShapeBuilderOptions`).
(
@@ -96,6 +98,8 @@ const ROWS: &[Row] = &[
"highlightColor",
],
),
// Fill Area uses the Shape Builder's Gap Detection and open-filled-path options.
(&["fillArea"], Some("shapeBuilder"), &["openFilledAsClosed", "gapDetection", "gapLength"]),
// Objects on Path Tool Options: the Pivot and Rotate of the objects attached next.
(&["objectsOnPath"], None, &["pivot", "rotate"]),
(&["artboard"], None, &["moveArt", "scaleArt"]),
+4
View File
@@ -479,6 +479,10 @@ impl VectorcraftApp {
if crate::touch::is_drawing_tool(now) {
self.ui.touch_drawing_tool = Some(now.to_string());
}
// Selecting the Quick Pen tool shows its toolbar, even after Hide Toolbar.
if now == vectorcraft_tools::quickpen::ID {
self.ui.quick_pen_bar = true;
}
Ok(())
}
+1 -1
View File
@@ -122,7 +122,7 @@ impl VectorcraftApp {
zoom: self.view().map_or(1.0, |v| v.screen_zoom(self.canvas_ui_zoom)),
outline: self.outline_view(),
smart_guides: self.ui.view.smart_guides,
guides: self.ui.view.guides,
guides: self.ui.view.guides_shown(),
snap_to_grid: self.ui.view.snap_to_grid,
pixel_preview: self.ui.view.pixel_preview,
snap_to_pixel: self.ui.view.snap_to_pixel,
+8 -4
View File
@@ -28,6 +28,7 @@ mod input;
mod outline;
mod overlays;
mod panes;
mod quick_pen_bar;
mod raster;
mod selection_marks;
mod task_bar;
@@ -68,6 +69,7 @@ use overlays::{
};
pub use panes::{Layout as TileLayout, Panes};
pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_noted, tile, tiled_area};
pub(crate) use quick_pen_bar::quick_pen_bar_rect;
pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job};
use raster::{changed_pixels, frame_ppp, pixel_region, upload};
pub use selection_marks::SelectionMarks;
@@ -326,7 +328,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
paint_paper(app, st, ui, &painter, &xf, rect, (&t, app.outline_view()));
// The grid behind the art (Guides & Grid › Grids In Back), else over it below.
let grid_look = (app.ui.view.grid && !presenting).then(|| LineLook::grid(&app.session.prefs));
let grid_look = (app.ui.view.grid_shown() && !presenting).then(|| LineLook::grid(&app.session.prefs));
let grids_in_back = app.session.prefs.grids_in_back;
if let Some(look) = grid_look.filter(|_| grids_in_back) {
grid(&painter, &xf, doc.grid.spacing, doc.grid.subdivisions, look);
@@ -416,7 +418,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
grid(&painter, &xf, 1.0, 1, LineLook { color: PIXEL_GRID, dots: false });
}
artboard_outlines(app, ui, &painter, &xf, &t);
if app.ui.view.guides {
if app.ui.view.guides_shown() {
guide_lines(app, &painter, &xf, rect, &t);
}
nine_slice_overlay(app, &painter, &xf);
@@ -463,6 +465,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
task_bar(app, ui, &xf);
}
if app.ui.screen_mode < 3 {
// The Quick Pen toolbar gives way to a drag as the task bar does.
quick_pen_bar::quick_pen_bar(app, ui, &xf);
contour_bar::contour_bar(app, ui, &xf);
// After the task bar, which the row of character alternates keeps clear of.
alternates_bar::alternates_bar(app, ui, &xf);
@@ -899,7 +903,7 @@ fn cache_key(
outline: app.outline_view(),
trim: app.ui.view.trim_view,
templates: app.ui.view.templates,
guides: app.ui.view.guides,
guides: app.ui.view.guides_shown(),
ppp,
hidden: vec![],
rot: v.rotation,
@@ -1098,7 +1102,7 @@ fn frame_options(
overprint_preview: vectorcraft_render::proof::overprint_preview_on(),
trim: app.ui.view.trim_view,
hide_templates: !app.ui.view.templates,
hide_guides: !app.ui.view.guides,
hide_guides: !app.ui.view.guides_shown(),
tile_edge: vectorcraft_color::Color::from_hex(&app.session.prefs.pattern_tile_edge_color).map_or(opts.tile_edge, |c| {
let [r, g, b, _] = c.to_rgba8(1.0);
[r, g, b]
+58 -12
View File
@@ -222,7 +222,14 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c
if resp.clicked_by(egui::PointerButton::Primary) {
ui.data_mut(|d| d.insert_temp(last_click, now));
}
if resp.double_clicked_by(egui::PointerButton::Primary)
// Trim View hides the guides (#8363): a guide made now could not be seen, so none is.
let trim_view = app.ui.view.trim_view;
let refuse = |app: &mut VectorcraftApp| app.status(crate::menus::TRIM_VIEW_HIDES.to_string());
if trim_view && first_here && resp.double_clicked_by(egui::PointerButton::Primary) {
refuse(app);
}
if !trim_view
&& resp.double_clicked_by(egui::PointerButton::Primary)
&& first_here
&& let Some(p) = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos()))
{
@@ -253,12 +260,22 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c
} else {
continue;
};
let p = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos()));
let on_canvas = p.is_some_and(|p| canvas.contains(p));
if on_canvas {
// The new guide shows even if guides were hidden.
app.ui.view.guides = true;
// A drag Trim View is on for at any point makes no guide, so none previews, even when
// Trim View is turned off again before the release: the whole gesture is cancelled and
// stays so until the button is released.
let cancel = egui::Id::unique(if vertical { "ruler-left-trim-cancel" } else { "ruler-top-trim-cancel" });
if resp.drag_started() {
ui.data_mut(|d| d.remove::<bool>(cancel));
}
if trim_view && ui.data(|d| d.get_temp::<bool>(cancel).is_none()) {
refuse(app);
ui.data_mut(|d| d.insert_temp(cancel, true));
}
let cancelled = ui.data(|d| d.get_temp::<bool>(cancel).is_some());
if cancelled && kind == PointerKind::Up {
ui.data_mut(|d| d.remove::<bool>(cancel));
}
let p = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos()));
let ev = PointerEvent {
kind,
pos: p.map_or(Point::ZERO, |p| xf.to_doc(p)),
@@ -267,6 +284,21 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c
pressure: 1.0,
pen: None,
};
if cancelled {
// A guide already dragged when Trim View turned on ends as a release off the canvas
// does: no guide, no undo step.
if app.session.ruler_guide_dragging()
&& let Err(e) = app.session.ruler_guide(vertical, &PointerEvent { kind: PointerKind::Up, ..ev }, false, app.view_info())
{
app.status(e.to_string());
}
continue;
}
let on_canvas = p.is_some_and(|p| canvas.contains(p));
if on_canvas {
// The new guide shows even if guides were hidden.
app.ui.view.guides = true;
}
if let Err(e) = app.session.ruler_guide(vertical, &ev, on_canvas, app.view_info()) {
app.status(e.to_string());
}
@@ -288,11 +320,14 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c
let drag_id = ruler_origin_drag_id();
let uid = app.session.active().map(|d| d.uid);
if corner.drag_started_by(egui::PointerButton::Primary) {
ui.data_mut(|d| d.insert_temp(drag_id, (uid, false)));
ui.data_mut(|d| d.insert_temp(drag_id, OriginDrag { doc: uid, cancelled: false, trim_view: app.ui.view.trim_view }));
}
let mut preview = None;
if let Some((started_in, mut cancelled)) = ui.data(|d| d.get_temp::<(Option<u64>, bool)>(drag_id)) {
cancelled |= started_in != uid || ui.input(|i| !i.focused || i.key_pressed(egui::Key::Escape));
if let Some(OriginDrag { doc: started_in, mut cancelled, trim_view }) = ui.data(|d| d.get_temp::<OriginDrag>(drag_id)) {
// Trim View turned on or off during the drag: the snap targets gathered at its start
// hold the ruler guides, or leave them out, as they no longer show (#8363), so the origin
// could snap to a guide nobody sees. The drag is cancelled as for hidden rulers.
cancelled |= started_in != uid || trim_view != app.ui.view.trim_view || ui.input(|i| !i.focused || i.key_pressed(egui::Key::Escape));
let pointer =
corner.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())).filter(|p| canvas.contains(*p)).map(|p| xf.to_doc(p));
// The origin snaps as a drawn point does (Smart Guides, Snap to Point, pixels, the grid).
@@ -313,7 +348,7 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c
} else if !ui.input(|i| i.pointer.primary_down()) {
end_ruler_origin_drag(app, ui);
} else {
ui.data_mut(|d| d.insert_temp(drag_id, (started_in, cancelled)));
ui.data_mut(|d| d.insert_temp(drag_id, OriginDrag { doc: started_in, cancelled, trim_view }));
if !cancelled {
preview = at;
}
@@ -333,10 +368,21 @@ pub(super) fn rulers_hidden(app: &mut VectorcraftApp, ui: &Ui) -> Option<Point>
/// Ends a drag from the rulers' corner, released or cancelled: its state and its snapping guides go.
fn end_ruler_origin_drag(app: &mut VectorcraftApp, ui: &Ui) {
ui.data_mut(|d| d.remove::<(Option<u64>, bool)>(ruler_origin_drag_id()));
ui.data_mut(|d| d.remove::<OriginDrag>(ruler_origin_drag_id()));
app.session.end_ruler_origin_drag();
}
/// A drag of the rulers' origin out of their corner, kept between frames.
#[derive(Clone, Copy)]
struct OriginDrag {
/// The document it started in (`Document::uid`): another one active cancels it.
doc: Option<u64>,
/// Cancelled (Escape, focus lost, another document, Trim View toggled): it sets nothing.
cancelled: bool,
/// View › Trim View was on when it started.
trim_view: bool,
}
/// The key of the ruler origin drag's state in egui's temporary data.
fn ruler_origin_drag_id() -> egui::Id {
egui::Id::unique("ruler-origin-drag")
@@ -345,7 +391,7 @@ fn ruler_origin_drag_id() -> egui::Id {
/// Is a drag from the rulers' corner in progress? It stays true after Escape cancels the move, until
/// the button is released.
pub(crate) fn ruler_origin_dragging(ctx: &egui::Context) -> bool {
ctx.data(|d| d.get_temp::<(Option<u64>, bool)>(ruler_origin_drag_id()).is_some())
ctx.data(|d| d.get_temp::<OriginDrag>(ruler_origin_drag_id()).is_some())
}
/// What the rulers count, and from where: `unit`, from `origin` (document points), with each
+1 -1
View File
@@ -188,7 +188,7 @@ pub(super) fn hit_with<T>(
path_only: prefs.object_selection_by_path_only,
type_path_only: prefs.type_selection_by_path_only,
scope: app.session.active().and_then(|st| st.isolation),
skip_guides: !app.ui.view.guides,
skip_guides: !app.ui.view.guides_shown(),
..Default::default()
};
test(&app.session.active()?.doc, p, opt)
+2 -2
View File
@@ -554,7 +554,7 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo
let xf = Xf::at(rect, &v, ui_zoom);
let painter = ui.painter_at(rect);
paint_paper(app, st, ui, &painter, &xf, rect, (&t, v.outline));
let grid_look = app.ui.view.grid.then(|| LineLook::grid(&app.session.prefs));
let grid_look = app.ui.view.grid_shown().then(|| LineLook::grid(&app.session.prefs));
let grids_in_back = app.session.prefs.grids_in_back;
if let Some(look) = grid_look.filter(|_| grids_in_back) {
grid(&painter, &xf, st.doc.grid.spacing, st.doc.grid.subdivisions, look);
@@ -587,7 +587,7 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo
if shows_artboards(app) {
artboard_edges(app, &st.doc, (&painter, &xf, &t), (v.artboard, dim_on_canvas(&t, v.outline)), |_| false);
}
if app.ui.view.guides {
if app.ui.view.guides_shown() {
guides_of(app, st, (&painter, &xf, &t), rect);
}
if app.ui.view.edges {
+278
View File
@@ -0,0 +1,278 @@
//! The Quick Pen toolbar: a floating bar on the canvas while the Quick Pen tool is active. It holds
//! the tool's actions (Straight Line, Continuous Arc, Sharp Corner Arc), Flip Arc for the last
//! sharp-corner arc, and a More Options menu with Hide Toolbar, Pin Toolbar Position and Reset
//! Toolbar Position. Its handle, at its left end, drags it.
//!
//! Public behavior: selecting the tool shows the toolbar, its actions decide what a click or drag
//! draws, Flip Arc flips the sharp-corner arc just drawn, the More menu hides the toolbar and resets
//! its position, and the toolbar moves by dragging its left side
//! ([Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html)).
//! The toolbar follows the drawing, beside the point the path goes on from and away from what was
//! drawn ([Behind the design: the Quick Pen tool](https://adobe.design/ideas/behind-the-design-adobe-illustrator-s-quick-pen-tool)).
//! VectorCraft's own rules: the exact place beside the point, moving to the drawn side where the
//! other side runs off the canvas, the place with no path being drawn, how a drag's offset is kept,
//! Pin Toolbar Position (which holds the toolbar at its place in the canvas window, not on the
//! artboard), and Window › Quick Pen Toolbar to show it again.
use vectorcraft_tools::quickpen::{self, Stroke as Action};
use super::{Color32, CornerRadius, Pos2, Sense, Stroke, Tokens, Ui, Vec2, VectorcraftApp, Xf, json, pos2, vec2, widgets};
/// The space between the point the path goes on from and the toolbar's nearest corner.
const GAP: f32 = 24.0;
/// The width of the toolbar's handle.
const HANDLE: f32 = 4.0;
/// The side of the toolbar's buttons.
const BUTTON: f32 = 28.0;
/// The space between the toolbar's controls.
const SPACING: f32 = 4.0;
fn bar_id() -> egui::Id {
egui::Id::unique("quick-pen-bar")
}
/// Where the Quick Pen toolbar was last drawn (none while it isn't shown).
pub(crate) fn quick_pen_bar_rect(ctx: &egui::Context) -> Option<egui::Rect> {
let id = bar_id();
ctx.memory(|m| m.areas().is_visible(&egui::LayerId::new(egui::Order::Middle, id)).then(|| m.area_rect(id)).flatten())
}
/// The toolbar's top-left corner, of `size`, beside `end` (the point the path goes on from, on
/// screen), on the side the path arrives there from `dir` (on screen): to its right and below it
/// for a path drawn to the right and down, so the toolbar stays off what was drawn. A path of one
/// point puts it to the right and below. Where that side runs out of `room` (the canvas) and the
/// other side fits, it goes on the other side; where neither fits, on the side with more room.
/// Kept in `room` ([`keep_in`]), it covers `end` only when neither side fits across or down.
fn beside(end: Pos2, dir: Option<Vec2>, size: Vec2, room: egui::Rect) -> Pos2 {
// `first` unless it runs out of room and `other` fits or runs out by less.
let pick = |first: f32, other: f32, lo: f32, hi: f32, len: f32| {
let over = |p: f32| (lo - p).max(0.0) + (p + len - hi).max(0.0);
if over(other) < over(first) { other } else { first }
};
let (right, left) = (end.x + GAP, end.x - GAP - size.x);
let (below, above) = (end.y + GAP, end.y - GAP - size.y);
let x = if dir.is_none_or(|d| d.x >= 0.0) { (right, left) } else { (left, right) };
let y = if dir.is_none_or(|d| d.y >= 0.0) { (below, above) } else { (above, below) };
pos2(pick(x.0, x.1, room.left(), room.right(), size.x), pick(y.0, y.1, room.top(), room.bottom(), size.y))
}
/// The toolbar's place with no path being drawn: centered at the bottom of the canvas area `room`.
fn resting(room: egui::Rect, size: Vec2) -> Pos2 {
pos2(room.center().x - size.x / 2.0, room.bottom() - size.y)
}
/// `p` moved, as little as it takes, for a toolbar of `size` to lie inside `room`.
fn keep_in(p: Pos2, size: Vec2, room: egui::Rect) -> Pos2 {
p.clamp(room.min, (room.max - size).max(room.min))
}
/// Where an unpinned toolbar of `size` sits: `home` moved by the drag `offset`, kept in `room`,
/// unless that would cover `end` (the point the path goes on from, on screen), where it sits at
/// `home` as if never dragged.
fn unpinned(home: Pos2, offset: Vec2, end: Option<Pos2>, size: Vec2, room: egui::Rect) -> Pos2 {
let moved = keep_in(home + offset, size, room);
if end.is_some_and(|e| egui::Rect::from_min_size(moved, size).contains(e)) { keep_in(home, size, room) } else { moved }
}
/// What a click on the toolbar does.
enum Click {
Action(Action),
Run(&'static str, serde_json::Value),
}
/// Is a drag under way (past the drag threshold) that began on the canvas `canvas` outside the
/// toolbar's last place `bar`? A stroke, a Space or middle-button pan and a drag from a path's first
/// point all are; a drag of the toolbar's handle is not.
fn canvas_drag(dragging: bool, press: Option<Pos2>, canvas: egui::Rect, bar: Option<egui::Rect>) -> bool {
dragging && press.is_some_and(|p| canvas.contains(p) && !bar.is_some_and(|b| b.contains(p)))
}
/// The Quick Pen toolbar, while the Quick Pen tool is active, Window › Quick Pen Toolbar is on and
/// no press is dragging on the canvas. Selecting the tool turns Window › Quick Pen Toolbar on
/// ([`VectorcraftApp::try_select_tool`]).
pub(super) fn quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) {
if !app.ui.quick_pen_bar || app.session.tool_id() != quickpen::ID {
return;
}
let (dragging, press, down) = ui.input(|i| (i.pointer.is_decidedly_dragging(), i.pointer.press_origin(), i.pointer.any_down()));
// The handle's drag moves the toolbar away from where the press began.
let handle_id = bar_id().with("handle");
if !down {
ui.ctx().data_mut(|d| d.insert_temp(handle_id, false));
}
let on_handle = ui.ctx().data(|d| d.get_temp::<bool>(handle_id)).unwrap_or(false);
let shown = app.ui.quick_pen_bar_place.shown_at.zip(egui::AreaState::load(ui.ctx(), bar_id()).and_then(|s| s.size));
if canvas_drag(dragging && !on_handle, press, xf.rect, shown.map(|(at, size)| egui::Rect::from_min_size(xf.rect.min + at, size))) {
return;
}
let Some(doc) = app.session.active().map(|st| st.uid) else { return };
let view = app.view_info();
let end = app.session.tool_drawing_end(view);
let flip = app.session.tool_claims_key(vectorcraft_tools::ToolKey::Letter('c'), view);
let current = app.session.tool_options().get("action").and_then(serde_json::Value::as_str).and_then(Action::parse).unwrap_or_default();
let t = Tokens::get(ui.ctx());
let id = bar_id();
let bounds = xf.rect.shrink(8.0);
let est = vec2(HANDLE + 5.0 * BUTTON + 6.0 * SPACING + 16.0, BUTTON + 12.0);
let size = egui::AreaState::load(ui.ctx(), id).and_then(|s| s.size).unwrap_or(est);
let end = end.map(|(p, dir)| {
let at = xf.to_screen(p);
(at, dir.map(|d| xf.to_screen(p + d) - at))
});
let drawing = end.is_some();
let home = match end {
Some((at, dir)) => beside(at, dir, size, bounds),
None => resting(bounds, size),
};
let place = &mut app.ui.quick_pen_bar_place;
// Just unpinned: follow the drawing from the pinned spot.
if !place.pinned
&& let Some(at) = place.pin_at.take()
{
place.offset = Some((doc, drawing, xf.rect.min + at - home));
}
// A drag's offset holds in the document and the kind of place (beside the drawing, or resting)
// it was made in.
let offset = place.offset.filter(|(d, beside, _)| *d == doc && *beside == drawing).map_or(Vec2::ZERO, |(_, _, o)| o);
let pos = match place.pin_at {
Some(at) => keep_in(xf.rect.min + at, size, bounds),
None => unpinned(home, offset, end.map(|(at, _)| at), size, bounds),
};
place.shown_at = Some(pos - xf.rect.min);
// Pinned before it ever showed: hold it here.
if place.pinned && place.pin_at.is_none() {
place.pin_at = place.shown_at;
}
let pinned = place.pinned;
let mut moved = Vec2::ZERO;
let mut click: Option<Click> = None;
egui::Area::new(id).order(egui::Order::Middle).fixed_pos(pos).show(ui.ctx(), |ui| {
egui::Frame::NONE
.fill(t.panel)
.stroke(Stroke::new(1.0, t.tool_active))
.corner_radius(CornerRadius::same(5))
.inner_margin(egui::Margin::symmetric(8, 6))
.shadow(egui::epaint::Shadow { offset: [0, 3], blur: 10, spread: 0, color: Color32::from_black_alpha(70) })
.show(ui, |ui| {
// In a canvas pane narrower than the toolbar, its controls wrap onto more rows.
ui.set_max_width((bounds.width() - 18.0).max(HANDLE + SPACING + BUTTON));
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(SPACING, SPACING);
let (g, grip) = ui.allocate_exact_size(vec2(HANDLE, BUTTON), Sense::drag());
let active = grip.hovered() || grip.dragged();
ui.painter().rect_filled(g.shrink2(vec2(0.5, 4.0)), CornerRadius::same(2), if active { t.text_dim } else { t.button_border });
if grip.dragged() {
ui.ctx().data_mut(|d| d.insert_temp(handle_id, true));
ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
moved = grip.drag_delta();
} else if grip.hovered() {
ui.ctx().set_cursor_icon(egui::CursorIcon::Grab);
}
let actions = [
(Action::Line, "dc-line", tl!("Straight Line")),
(Action::ContinuousArc, "spline", tl!("Continuous Arc")),
(Action::SharpArc, "dc-arc", tl!("Sharp Corner Arc")),
];
for (action, icon, tip) in actions {
if widgets::icon_button(ui, icon, tip, current == action, BUTTON).clicked() {
click = Some(Click::Action(action));
}
}
if widgets::icon_button_enabled(ui, "flip-horizontal-2", tl!("Flip Arc"), false, flip, BUTTON).clicked() {
click = Some(Click::Run("tool.quickPen.flipArc", json!({})));
}
let more = widgets::icon_button(ui, "ellipsis", tl!("More Options"), false, BUTTON);
egui::Popup::menu(&more).show(|ui| {
ui.set_min_width(170.0);
let items = [
(tl!("Hide Toolbar"), "window.quickPenToolbar", false),
(tl!("Pin Toolbar Position"), "window.quickPenToolbar.pin", pinned),
(tl!("Reset Toolbar Position"), "window.quickPenToolbar.reset", false),
];
for (label, cmd, checked) in items {
if widgets::menu_item(ui, label, true, checked) {
click = Some(Click::Run(cmd, json!({})));
}
}
});
});
});
});
if moved != Vec2::ZERO {
let to = keep_in(pos + moved, size, bounds);
let place = &mut app.ui.quick_pen_bar_place;
if place.pinned {
place.pin_at = Some(to - xf.rect.min);
} else {
place.offset = Some((doc, drawing, to - home));
}
ui.ctx().request_repaint();
}
let r = match click {
Some(Click::Action(a)) => app.run("tool.setOption", json!({"key": "action", "value": a.name()})).map(|_| ()),
Some(Click::Run(cmd, p)) => app.run(cmd, p).map(|_| ()),
None => Ok(()),
};
if let Err(e) = r {
app.ui.status = e;
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The toolbar sits off what was drawn: ahead of a path drawn right and down, behind-left and
/// above for one drawn left and up, and to the right and below a single point.
#[test]
fn the_toolbar_sits_beside_the_end_away_from_the_drawing() {
let (end, size) = (pos2(500.0, 300.0), vec2(180.0, 40.0));
let room = egui::Rect::from_min_max(pos2(8.0, 8.0), pos2(808.0, 608.0));
assert_eq!(beside(end, Some(vec2(1.0, 0.0)), size, room), pos2(524.0, 324.0));
assert_eq!(beside(end, Some(vec2(-1.0, -1.0)), size, room), pos2(500.0 - 24.0 - 180.0, 300.0 - 24.0 - 40.0));
assert_eq!(beside(end, Some(vec2(0.0, 1.0)), size, room), pos2(524.0, 324.0));
assert_eq!(beside(end, Some(vec2(-1.0, 0.5)), size, room), pos2(296.0, 324.0));
assert_eq!(beside(end, None, size, room), pos2(524.0, 324.0));
assert_eq!(resting(room, size), pos2(318.0, 568.0));
// Near the canvas's bottom right corner, the side that runs off it gives way to the other.
let corner = pos2(700.0, 580.0);
assert_eq!(beside(corner, Some(vec2(1.0, 1.0)), size, room), pos2(700.0 - 24.0 - 180.0, 580.0 - 24.0 - 40.0));
// Near the top left corner, a path heading up and left still gets a toolbar off its end.
let corner = pos2(30.0, 30.0);
assert_eq!(beside(corner, Some(vec2(-1.0, -1.0)), size, room), pos2(54.0, 54.0));
// On a canvas too narrow for either side across, the toolbar goes on the side with more
// room and stays off the end by going below it.
let narrow = egui::Rect::from_min_max(pos2(8.0, 8.0), pos2(208.0, 608.0));
let end = pos2(60.0, 300.0);
let at = keep_in(beside(end, Some(vec2(-1.0, 1.0)), size, narrow), size, narrow);
assert_eq!(at, pos2(28.0, 324.0));
assert!(!egui::Rect::from_min_size(at, size).contains(end));
}
/// Any drag that began on the canvas hides the toolbar, whether or not the tool has a press
/// (a pan does not); a drag that began on the toolbar, and no drag, do not.
#[test]
fn a_drag_that_began_on_the_canvas_hides_the_toolbar() {
let canvas = egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(800.0, 600.0));
let bar = Some(egui::Rect::from_min_size(pos2(300.0, 500.0), vec2(180.0, 40.0)));
assert!(canvas_drag(true, Some(pos2(100.0, 100.0)), canvas, bar), "a pan or stroke on the canvas");
assert!(canvas_drag(true, Some(pos2(100.0, 100.0)), canvas, None), "no toolbar shown yet");
assert!(!canvas_drag(false, Some(pos2(100.0, 100.0)), canvas, bar), "a click, not a drag");
assert!(!canvas_drag(true, Some(pos2(310.0, 510.0)), canvas, bar), "the toolbar's own drag");
assert!(!canvas_drag(true, Some(pos2(900.0, 100.0)), canvas, bar), "a drag in another panel");
assert!(!canvas_drag(true, None, canvas, bar));
}
/// A drag's offset moves the toolbar from its place, unless that would put it over the point
/// the path goes on from.
#[test]
fn a_dragged_toolbar_never_covers_the_end() {
let size = vec2(180.0, 40.0);
let room = egui::Rect::from_min_max(pos2(8.0, 8.0), pos2(808.0, 608.0));
let (end, home) = (pos2(500.0, 300.0), pos2(524.0, 324.0));
assert_eq!(unpinned(home, vec2(30.0, 40.0), Some(end), size, room), pos2(554.0, 364.0));
assert_eq!(unpinned(home, vec2(-60.0, -40.0), Some(end), size, room), home, "over the end");
assert_eq!(unpinned(home, vec2(-60.0, -40.0), None, size, room), pos2(464.0, 284.0));
assert_eq!(unpinned(home, vec2(900.0, 0.0), Some(end), size, room), pos2(628.0, 324.0), "kept on the canvas");
}
}
+247
View File
@@ -15357,3 +15357,250 @@ fn auto_spell_check_is_a_toggle_of_the_canvas_lines() {
assert_eq!(count(&mut app), 0, "off");
assert!(app.canvas.spelling.lines.is_empty(), "no node is kept");
}
/// #8363: Trim View hides the ruler guides, the guide paths and the grid while it is on, and they
/// are neither snapped to nor picked, as hidden guides are; turned off, they come back as they
/// were. The rulers stay.
#[test]
fn trim_view_hides_the_guides_and_the_grid() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.canvas.worker_started = true; // render on this thread
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.session.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap();
app.run("shape.rectangle", json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap();
app.run("view.guides.make", json!({})).unwrap();
app.run("select.none", json!({})).unwrap();
(app.ui.view.grid, app.ui.view.guides, app.ui.view.rulers) = (true, true, true);
let (red, green) = (Color32::from_rgb(255, 0, 0), Color32::from_rgb(0, 255, 0));
app.session.execute("prefs.set", &json!({"values": {"gridColor": "#ff0000", "guideColor": "#00ff00"}})).unwrap();
let ctx = egui::Context::default();
// → (a gridline, a ruler guide, guide paths in the art, guides snapped to and picked).
let drawn = |app: &mut VectorcraftApp| {
let s = shapes(app, &ctx);
let line = |c: Color32| s.iter().any(|s| matches!(s, Shape::LineSegment { stroke, .. } if stroke.color == c));
let guide_paths = !app.canvas.shown.as_ref().unwrap().1.hide_guides;
(line(red), line(green), guide_paths, app.view_info().guides)
};
assert_eq!(drawn(&mut app), (true, true, true, true), "Trim View off: all of them");
app.run("view.trimView", json!({})).unwrap();
assert_eq!(drawn(&mut app), (false, false, false, false), "Trim View on: none of them");
assert!(app.ui.view.grid && app.ui.view.guides && app.ui.view.rulers, "the choices stay, and so do the rulers");
app.run("view.trimView", json!({})).unwrap();
assert_eq!(drawn(&mut app), (true, true, true, true), "Trim View off: back as they were");
// Hidden before, they stay hidden after.
app.run("view.guides", json!({})).unwrap();
app.run("view.trimView", json!({})).unwrap();
app.run("view.trimView", json!({})).unwrap();
assert_eq!(drawn(&mut app), (true, false, false, false), "guides hidden before Trim View stay hidden");
}
/// #8363: a selected guide path is deselected when Trim View hides it, as Hide Guides does (#3219).
#[test]
fn trim_view_deselects_selected_guide_paths() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap();
app.run("view.guides.make", json!({})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(id)]);
app.run("view.trimView", json!({})).unwrap();
assert!(app.session.active().unwrap().selection.objects.is_empty());
}
/// #8363: Trim View hides the guides, so a guide dragged or double-clicked out of a ruler while it
/// is on would be made but never seen. None is: no preview line, no guide, no undo step, the
/// stored Show/Hide Guides choice is left alone, and the status line says why. A drag already
/// going when Trim View turns on ends as a release off the canvas does.
#[test]
fn trim_view_makes_no_guide_from_the_rulers() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.ui.view.rulers = true;
app.ui.view.guides = false;
app.ui.view.smart_guides = false;
app.ui.view.snap_to_point = false;
app.ui.view.trim_view = true;
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let rect = app.canvas_rect.unwrap();
let from = pos2(rect.center().x, rect.top() - RULER / 2.0);
let at = pos2(rect.center().x, rect.top() + 120.0);
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
let across = |s: &Shape| {
matches!(s, Shape::LineSegment { points, .. }
if (points[0].y - at.y).abs() <= 2.0 && points[0].y == points[1].y && (points[1].x - points[0].x).abs() >= rect.width() - 0.5)
};
let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().len();
let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
let before = steps(&app);
// A drag: nothing previews and nothing is made.
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
frame(&mut app, &ctx, vec![button(from, true)]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
assert!(!shapes(&mut app, &ctx).iter().any(across), "no guide previews");
assert!(!app.session.ruler_guide_dragging());
frame(&mut app, &ctx, vec![button(at, false)]);
assert_eq!(count(&app), 0, "no guide from a drag");
assert!(!app.ui.view.guides, "the stored choice is left alone");
assert_eq!(app.ui.status, crate::menus::TRIM_VIEW_HIDES);
// A double-click: nothing either.
app.ui.status.clear();
let click = |app: &mut VectorcraftApp| {
frame(app, &ctx, vec![egui::Event::PointerMoved(from)]);
frame(app, &ctx, vec![button(from, true)]);
frame(app, &ctx, vec![button(from, false)]);
};
click(&mut app);
click(&mut app);
assert_eq!(count(&app), 0, "no guide from a double-click");
assert!(!app.ui.view.guides);
assert_eq!(app.ui.status, crate::menus::TRIM_VIEW_HIDES);
assert_eq!(steps(&app), before, "no undo step");
// Trim View turned on during a drag: the drag ends without a guide.
app.ui.view.trim_view = false;
let from2 = pos2(rect.center().x + 30.0, rect.top() - RULER / 2.0);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from2)]);
frame(&mut app, &ctx, vec![button(from2, true)]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
assert!(app.session.ruler_guide_dragging(), "the drag started with Trim View off");
app.ui.view.trim_view = true;
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos2(at.x + 5.0, at.y))]);
assert!(!app.session.ruler_guide_dragging(), "ended");
assert!(!shapes(&mut app, &ctx).iter().any(across), "no guide previews");
frame(&mut app, &ctx, vec![button(at, false)]);
assert_eq!(count(&app), 0, "no guide from the drag Trim View interrupted");
assert_eq!(steps(&app), before, "no undo step");
// With Trim View off again, a drag makes a guide as before.
app.ui.view.trim_view = false;
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
frame(&mut app, &ctx, vec![button(from, true)]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
frame(&mut app, &ctx, vec![button(at, false)]);
assert_eq!(count(&app), 1);
assert!(app.ui.view.guides, "the new guide shows");
}
/// #8363: a guide drag Trim View cancelled stays cancelled until the button is released. Trim
/// View turned off again before the release does not start a new guide: the release makes none
/// and adds no undo step. The next drag works as before.
#[test]
fn a_ruler_drag_trim_view_cancelled_stays_cancelled_until_released() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.ui.view.rulers = true;
app.ui.view.smart_guides = false;
app.ui.view.snap_to_point = false;
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let rect = app.canvas_rect.unwrap();
let from = pos2(rect.center().x, rect.top() - RULER / 2.0);
let at = pos2(rect.center().x, rect.top() + 120.0);
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().len();
let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
let before = steps(&app);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
frame(&mut app, &ctx, vec![button(from, true)]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
assert!(app.session.ruler_guide_dragging());
app.ui.view.trim_view = true;
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos2(at.x, at.y + 5.0))]);
assert!(!app.session.ruler_guide_dragging(), "Trim View ends the drag");
app.ui.view.trim_view = false;
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos2(at.x, at.y + 10.0))]);
assert!(!app.session.ruler_guide_dragging(), "turned off again, no new guide starts");
frame(&mut app, &ctx, vec![button(pos2(at.x, at.y + 10.0), false)]);
assert_eq!(count(&app), 0, "the release makes no guide");
assert_eq!(steps(&app), before, "no undo step");
// The next drag makes a guide.
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
frame(&mut app, &ctx, vec![button(from, true)]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
frame(&mut app, &ctx, vec![button(at, false)]);
assert_eq!(count(&app), 1);
}
/// #8363: Trim View turned on or off during a drag of the rulers' origin out of their corner
/// cancels it, as hiding the rulers does: the snap targets gathered at its start would hold
/// guides Trim View hides. The origin is left where it was. A drag wholly with Trim View on, or
/// wholly off, sets it.
#[test]
fn trim_view_toggled_during_a_ruler_origin_drag_cancels_it() {
for (start, end, sets) in [(false, true, false), (true, false, false), (true, true, true), (false, false, true)] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.session.execute("guide.add", &json!({"vertical": true, "pos": 150})).unwrap();
app.ui.view.rulers = true;
app.ui.view.trim_view = start;
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let rect = app.canvas_rect.unwrap();
let xf = Xf::new(rect, app.view().unwrap());
let origin = |app: &VectorcraftApp| {
let d = &app.session.active().unwrap().doc;
format!("{:?} {:?}", d.ruler_origin, d.artboard_ruler_origins)
};
let was = origin(&app);
let from = pos2(rect.left() - RULER / 2.0, rect.top() - RULER / 2.0);
let at = xf.to_screen(Point::new(151.0, 100.0));
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
frame(&mut app, &ctx, vec![button(from, true)]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
assert!(crate::canvas::ruler_origin_dragging(&ctx), "{start} {end}: dragging");
app.ui.view.trim_view = end;
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + vec2(1.0, 0.0))]);
frame(&mut app, &ctx, vec![button(at + vec2(1.0, 0.0), false)]);
assert_eq!(origin(&app) != was, sets, "Trim View {start} then {end}: origin set {sets}");
}
}
/// #8363: a Selection move begun with the guides shown gathers the ruler guides to snap to. When
/// they stop showing during the move (Trim View or Hide Guides turned on), it no longer snaps to
/// them; with them shown throughout, it does.
#[test]
fn a_move_stops_snapping_to_guides_hidden_during_it() {
// What hides the guides mid-move (none: they stay shown), and whether the move then snaps.
for (hide, snaps) in [(None, true), (Some("trim"), false), (Some("guides"), false)] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 50, "height": 50})).unwrap();
app.session.execute("guide.add", &json!({"vertical": true, "pos": 200})).unwrap();
app.select_tool("selection");
app.ui.view.smart_guides = false;
app.ui.view.snap_to_point = true;
app.ui.view.guides = true;
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let rect = app.canvas_rect.unwrap();
let xf = Xf::new(rect, app.view().unwrap());
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
// Grabbed at its centre, moved first well away from the guide, then 1.5 px short of it.
let grab = xf.to_screen(Point::new(75.0, 75.0));
let away = xf.to_screen(Point::new(120.0, 75.0));
let near = xf.to_screen(Point::new(200.0, 75.0)) - vec2(1.5, 0.0);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab)]);
frame(&mut app, &ctx, vec![button(grab, true)]);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(away)]);
match hide {
Some("trim") => app.ui.view.trim_view = true,
Some(_) => app.ui.view.guides = false,
None => {}
}
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(near)]);
frame(&mut app, &ctx, vec![button(near, false)]);
let b = app.session.active().unwrap().doc.art_bounds().unwrap();
let centre = (b.x0 + b.x1) / 2.0;
assert_eq!((centre - 200.0).abs() < 1e-6, snaps, "{hide:?}: the grabbed centre at {centre}");
assert!((centre - xf.to_doc(near).x).abs() < 1e-6 || snaps, "{hide:?}: unsnapped, it follows the pointer: {centre}");
}
}
+2 -1
View File
@@ -209,7 +209,8 @@ pub(super) fn info_text(app: &VectorcraftApp) -> (String, Option<u64>) {
(text, Some(next))
}
StatusBarShow::Undos => {
let text = st.map(|d| format!("{}: {} {}: {}", tl!("Undos"), d.history.undo.len(), tl!("Redos"), d.history.redo.len()));
let (undos, redos) = (crate::i18n::colon(tl!("Undos")), crate::i18n::colon(tl!("Redos")));
let text = st.map(|d| format!("{undos} {} {redos} {}", d.history.undo.len(), d.history.redo.len()));
(text.unwrap_or_default(), None)
}
StatusBarShow::ColorProfile => (st.map(|d| color_profile_name(&d.doc)).unwrap_or_default(), None),
Loaded 100 of 193 files, more files were not shown because too many files have changed in this diff. Show more