Merge main into feat/link-info-show-in-folder

This commit is contained in:
dotCooCoo committed 2026-11-24 22:33:55 -08:00
commit 6bb47e42bd
283 files changed
+13085 -1491

No files matched your search

+27
View File
@@ -154,6 +154,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | |
| `assets/icons/dc-corner-tool.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-crystallize.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-cube.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-curvature-circle.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (an arch with the circle that touches it at its top, and that circle's center) | MIT OR Apache-2.0 | |
@@ -194,6 +195,15 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-grad-stroke-along.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-grad-stroke-within.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-gradient.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-graph-area.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-graph-bar.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-graph-column.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-graph-line.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-graph-pie.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-graph-radar.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-graph-scatter.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-graph-stacked-bar.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-graph-stacked-column.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-graphic-styles.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-grid-view.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-group-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
@@ -203,6 +213,9 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-join-round.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-join.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-knife.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-lasso-enclosing.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-lasso-polygonal.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-lasso.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-line-cut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-line.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-list-view.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
@@ -230,6 +243,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-para-rtl.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-path-eraser.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-pathfinder.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-perspective-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-perspective.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-pf-crop.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-pf-divide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
@@ -248,6 +262,8 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-puppet.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-quick-pen.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a line and a half circle with a dot at each point) | MIT OR Apache-2.0 | |
| `assets/icons/dc-rearrange.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-recolor-arrow.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a right arrow, a Recolor Artwork row that is recolored) | MIT OR Apache-2.0 | |
| `assets/icons/dc-recolor-arrow-off.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a dashed line without a head, a Recolor Artwork row that is excluded) | MIT OR Apache-2.0 | |
| `assets/icons/dc-rect-cut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-rect-grid.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-reference-point.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
@@ -262,7 +278,11 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-screen-mode.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-selection.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-shape-builder.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-shared-edge.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-shear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-slice-select.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-slice.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-slide-anchor.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-smooth.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-stroke-center.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-stroke-inside.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
@@ -273,7 +293,14 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-swatch-kinds.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-swatch-process.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a square, a process color) | MIT OR Apache-2.0 | |
| `assets/icons/dc-swatch-spot.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a dot in a ring, a spot color) | MIT OR Apache-2.0 | |
| `assets/icons/dc-symbol-screener.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-symbol-scruncher.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-symbol-shifter.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-symbol-sizer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-symbol-spinner.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-symbol-sprayer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-symbol-stainer.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-symbol-styler.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-touch-type.svg` | VectorCraft contributors (designed by ham9zah) | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-transform-panel.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-transparency.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
Generated
+110 -99
View File
@@ -1134,7 +1134,7 @@ dependencies = [
[[package]]
name = "craft"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-automation",
"craft-behavior",
@@ -1175,7 +1175,7 @@ dependencies = [
[[package]]
name = "craft-affinity"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"crc32fast",
"flate2",
@@ -1186,7 +1186,7 @@ dependencies = [
[[package]]
name = "craft-appkit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"block2 0.6.2",
"objc2-app-kit 0.3.2",
@@ -1196,7 +1196,7 @@ dependencies = [
[[package]]
name = "craft-atomic"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"rustix 1.1.6",
]
@@ -1204,7 +1204,7 @@ dependencies = [
[[package]]
name = "craft-automation"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"base64 0.23.1",
"craft-behavior",
@@ -1229,7 +1229,7 @@ dependencies = [
[[package]]
name = "craft-behavior"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"accesskit",
"bitflags 2.13.2",
@@ -1247,7 +1247,7 @@ dependencies = [
[[package]]
name = "craft-browse"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-docpath",
@@ -1265,7 +1265,7 @@ dependencies = [
[[package]]
name = "craft-cdr"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"crc32fast",
"flate2",
@@ -1274,7 +1274,7 @@ dependencies = [
[[package]]
name = "craft-cloud-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"egui",
]
@@ -1282,7 +1282,7 @@ dependencies = [
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"md-5",
"rayon",
@@ -1291,12 +1291,12 @@ dependencies = [
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
[[package]]
name = "craft-color-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-cms",
@@ -1316,7 +1316,7 @@ dependencies = [
[[package]]
name = "craft-control"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"getrandom 0.3.4",
"serde",
@@ -1326,7 +1326,7 @@ dependencies = [
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"rayon",
]
@@ -1334,7 +1334,7 @@ dependencies = [
[[package]]
name = "craft-dialogs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"block2 0.6.2",
"craft-atomic",
@@ -1359,7 +1359,7 @@ dependencies = [
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"serde",
]
@@ -1367,7 +1367,7 @@ dependencies = [
[[package]]
name = "craft-draw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1386,7 +1386,7 @@ dependencies = [
[[package]]
name = "craft-dxf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-codepage",
"encoding_rs",
@@ -1398,12 +1398,12 @@ dependencies = [
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"fontique",
"harfrust 0.13.3",
@@ -1418,7 +1418,7 @@ dependencies = [
[[package]]
name = "craft-font-manager"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-font-catalog",
@@ -1431,13 +1431,13 @@ dependencies = [
"egui",
"log",
"serde",
"skrifa 0.44.0",
"skrifa 0.47.0",
]
[[package]]
name = "craft-font-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"cap-primitives",
"craft-atomic",
@@ -1453,17 +1453,18 @@ dependencies = [
"thiserror 2.0.21",
"toml",
"ureq",
"wuff",
]
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
[[package]]
name = "craft-gif"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"gif",
]
@@ -1471,7 +1472,7 @@ dependencies = [
[[package]]
name = "craft-gzip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"flate2",
]
@@ -1479,7 +1480,7 @@ dependencies = [
[[package]]
name = "craft-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"bitflags 2.13.2",
"craft-i18n",
@@ -1492,7 +1493,7 @@ dependencies = [
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"chrono",
"fixed_decimal",
@@ -1520,7 +1521,7 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-dds",
"craft-jpeg",
@@ -1547,7 +1548,7 @@ dependencies = [
[[package]]
name = "craft-imaging"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1565,7 +1566,7 @@ dependencies = [
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"thiserror 2.0.21",
]
@@ -1573,7 +1574,7 @@ dependencies = [
[[package]]
name = "craft-jxl"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"brotli-decompressor 5.0.3",
"jixel",
@@ -1584,7 +1585,7 @@ dependencies = [
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-host",
"craft-i18n",
@@ -1599,7 +1600,7 @@ dependencies = [
[[package]]
name = "craft-layers"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-i18n",
@@ -1613,7 +1614,7 @@ dependencies = [
[[package]]
name = "craft-menu"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-host",
@@ -1631,7 +1632,7 @@ dependencies = [
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"brotli-decompressor 6.3.2",
"chrono",
@@ -1643,7 +1644,7 @@ dependencies = [
[[package]]
name = "craft-metafile"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"encoding_rs",
"image",
@@ -1654,7 +1655,7 @@ dependencies = [
[[package]]
name = "craft-mime"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"chrono",
"craft-codepage",
@@ -1664,7 +1665,7 @@ dependencies = [
[[package]]
name = "craft-pages"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -1680,7 +1681,7 @@ dependencies = [
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"hayro-interpret",
"hayro-syntax",
@@ -1692,7 +1693,7 @@ dependencies = [
[[package]]
name = "craft-platform"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"async-channel",
"async-io",
@@ -1723,7 +1724,7 @@ dependencies = [
[[package]]
name = "craft-plotter"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"kurbo 0.13.1",
"thiserror 2.0.21",
@@ -1732,7 +1733,7 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-host",
@@ -1756,7 +1757,7 @@ dependencies = [
[[package]]
name = "craft-proof"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"log",
"miniz_oxide 0.9.1",
@@ -1767,7 +1768,7 @@ dependencies = [
[[package]]
name = "craft-ps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-eps",
"flate2",
@@ -1781,7 +1782,7 @@ dependencies = [
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"encoding_rs",
"flate2",
@@ -1792,7 +1793,7 @@ dependencies = [
[[package]]
name = "craft-quit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"dispatch2",
"egui",
@@ -1805,7 +1806,7 @@ dependencies = [
[[package]]
name = "craft-review"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"base64 0.23.1",
"craft-behavior",
@@ -1824,7 +1825,7 @@ dependencies = [
[[package]]
name = "craft-settings"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-atomic",
"craft-host",
@@ -1841,7 +1842,7 @@ dependencies = [
[[package]]
name = "craft-stream-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"fax",
"hayro-ccitt",
@@ -1852,7 +1853,7 @@ dependencies = [
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-image-codecs",
"craft-xml",
@@ -1873,7 +1874,7 @@ dependencies = [
[[package]]
name = "craft-table"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -1885,7 +1886,7 @@ dependencies = [
[[package]]
name = "craft-text"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-font-manager",
@@ -1910,7 +1911,7 @@ dependencies = [
[[package]]
name = "craft-theme"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"bitflags 2.13.2",
"craft-tracked",
@@ -1925,7 +1926,7 @@ dependencies = [
[[package]]
name = "craft-theme-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-atomic",
"craft-behavior",
@@ -1940,7 +1941,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1950,7 +1951,7 @@ dependencies = [
[[package]]
name = "craft-time"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1959,7 +1960,7 @@ dependencies = [
[[package]]
name = "craft-timeline"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -1974,12 +1975,12 @@ dependencies = [
[[package]]
name = "craft-tracked"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-cloud-ui",
"craft-ui-canvas",
@@ -1993,7 +1994,7 @@ dependencies = [
[[package]]
name = "craft-ui-canvas"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-i18n",
@@ -2009,7 +2010,7 @@ dependencies = [
[[package]]
name = "craft-ui-contract"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"accesskit",
"craft-behavior",
@@ -2047,7 +2048,7 @@ dependencies = [
[[package]]
name = "craft-ui-macros"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -2058,7 +2059,7 @@ dependencies = [
[[package]]
name = "craft-ui-panels"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2076,7 +2077,7 @@ dependencies = [
[[package]]
name = "craft-ui-patterns"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2097,7 +2098,7 @@ dependencies = [
[[package]]
name = "craft-ui-shell"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2118,7 +2119,7 @@ dependencies = [
[[package]]
name = "craft-ui-widgets"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2137,7 +2138,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"chrono",
"craft-host",
@@ -2166,7 +2167,7 @@ dependencies = [
[[package]]
name = "craft-vectorcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"flate2",
"serde",
@@ -2177,7 +2178,7 @@ dependencies = [
[[package]]
name = "craft-wayland"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"raw-window-handle",
"wayland-backend",
@@ -2187,7 +2188,7 @@ dependencies = [
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"js-sys",
"serde_json",
@@ -2198,7 +2199,7 @@ dependencies = [
[[package]]
name = "craft-win32"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"winsafe",
]
@@ -2206,7 +2207,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-appkit",
"craft-atomic",
@@ -2238,7 +2239,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -2400,7 +2401,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -2526,7 +2527,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
[[package]]
name = "ecolor"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
dependencies = [
"bytemuck",
"emath",
@@ -2535,7 +2536,7 @@ dependencies = [
[[package]]
name = "eframe"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
dependencies = [
"ahash",
"bytemuck",
@@ -2570,7 +2571,7 @@ dependencies = [
[[package]]
name = "egui"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
dependencies = [
"accesskit",
"ahash",
@@ -2589,7 +2590,7 @@ dependencies = [
[[package]]
name = "egui-wgpu"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
dependencies = [
"ahash",
"bytemuck",
@@ -2608,7 +2609,7 @@ dependencies = [
[[package]]
name = "egui-winit"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
dependencies = [
"accesskit_winit",
"arboard",
@@ -2633,7 +2634,7 @@ dependencies = [
[[package]]
name = "egui_extras"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
dependencies = [
"ahash",
"egui",
@@ -2647,7 +2648,7 @@ dependencies = [
[[package]]
name = "egui_glow"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
dependencies = [
"bytemuck",
"egui",
@@ -2660,7 +2661,7 @@ dependencies = [
[[package]]
name = "egui_kittest"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
dependencies = [
"dify",
"eframe",
@@ -2686,7 +2687,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
[[package]]
name = "emath"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
dependencies = [
"bytemuck",
]
@@ -2767,7 +2768,7 @@ dependencies = [
[[package]]
name = "epaint"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
dependencies = [
"ahash",
"bytemuck",
@@ -2793,7 +2794,7 @@ dependencies = [
[[package]]
name = "epaint_default_fonts"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
[[package]]
name = "equivalent"
@@ -3083,7 +3084,7 @@ checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"
dependencies = [
"io-lifetimes 2.0.4",
"rustix 1.1.6",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -3506,7 +3507,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"brotli",
"hayro-postscript",
@@ -3515,7 +3516,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -3533,7 +3534,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -3551,12 +3552,12 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
[[package]]
name = "hayro-syntax"
version = "0.7.2"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -4116,7 +4117,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
dependencies = [
"io-lifetimes 3.0.1",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -4487,7 +4488,7 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"base64 0.22.1",
"bumpalo",
@@ -4644,7 +4645,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=a4b6d3b6ca04a65d5972339b808d1049a14c7167#a4b6d3b6ca04a65d5972339b808d1049a14c7167"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"arrayvec",
"kurbo 0.13.1",
@@ -9717,7 +9718,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"
dependencies = [
"bitflags 2.13.2",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -9772,6 +9773,16 @@ dependencies = [
"either",
]
[[package]]
name = "wuff"
version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6a992b57b3d1ee972b2e3fd9225e44793104d49818836dd812d5459187712dd"
dependencies = [
"brotli-decompressor 6.3.2",
"bytes",
]
[[package]]
name = "x11-dl"
version = "2.21.0"
@@ -10280,14 +10291,14 @@ dependencies = [
[[patch.unused]]
name = "egui_demo_lib"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
[[patch.unused]]
name = "egui_inspection"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
[[patch.unused]]
name = "egui_system_font_provider"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560"
source = "git+https://github.com/storytold/egui.git?rev=b15ffe9bfc2c8e6748533b32b708e10abaf2afec#b15ffe9bfc2c8e6748533b32b708e10abaf2afec"
+48 -48
View File
@@ -11,44 +11,44 @@ rust-version = "1.95"
repository = "https://github.com/storytold/vectorcraft"
[workspace.dependencies]
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
# 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 = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-vectorcraft-format = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
# Native Affinity documents (craft-libs#914).
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-affinity = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
# Bounded CDR (v1-v27) and CMX (32-bit) reader (craft-libs#778).
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-cdr = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
# SVG parsing, limits, SVGZ and writer (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
# EPS container, previews, ASCII85 and DSC comments (craft-libs#778).
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
# DXF tags, reader and writer (craft-libs#778, #926, #927).
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
# WMF, EMF and EMF+ reader (craft-libs#778).
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
# The framework facade (`craft::ui`, `craft::settings`, `craft::platform`, ...). No default features: each crate names
# the members it imports.
craft = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
# Below the egui layer, so not through the facade: the colour harmony rules and their settings (craft-color-ui
# without its `ui` feature), the colour type they work in, and the craft-fonts tables the text crate's build writes.
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
craft-color-ui = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
# internal
vectorcraft-geom = { path = "crates/geom" }
vectorcraft-color = { path = "crates/color" }
@@ -191,25 +191,25 @@ lto = "thin"
codegen-units = 1
[patch.crates-io]
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "b15ffe9bfc2c8e6748533b32b708e10abaf2afec" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+2
View File
@@ -148,6 +148,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 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 length handles: a handle beyond the start and the end of the path being drawn, or of the selected path, makes the line or arc there longer or shorter when dragged; a line keeps its direction and an arc its circle (`path.quickPenLength`, 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.
@@ -158,6 +159,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-01: Sort Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects are sorted by width, height, area, position, opacity or stacking order (small to large, large to small or at random) and take another of those in that order, trading their values or stepping them evenly, as one undo step (`addon.arrange.sort`, #4917).
- 2026-11-15: Tangent Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the circles that touch two selected paths or compound paths at a set radius, or three of them (up to eight for three circles), touching each outline without crossing it; circles, rotated ellipses and other paths alike. A dialog that previews every circle or one picked by number, the current paint, one undo step (`addon.pathtools.tangentCircle`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-17: Add Bounding Rectangle and Add Bounding Circle join the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): a live rectangle on the selection's geometric bounding box, or the smallest live circle that holds its outlines, around the whole selection or around each object, with the current paint and one undo step; the menu items open a dialog with Offset, One per Object and Preview (`addon.pathtools.boundingRectangle`, `addon.pathtools.boundingCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
- 2026-11-22: Add Inscribed Circle joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the largest live circle inside each selected closed path or compound path, in the area it fills under its fill rule, with the current paint and one undo step (`addon.pathtools.inscribedCircle`, #6966). A VectorCraft addition: headline numbers unchanged.
- 2026-11-01: New Symbols from Layers joins the Document Tools add-on (Object › Plug-ins › Document Tools): one symbol of each top-level layer's art (the layers highlighted in the Layers panel when two or more are, else every layer), named after the layer, made as New Symbol makes one; Convert Layers to Symbols also puts an instance of each in place of its layer's art. Empty layers are skipped and reported; one undo step. A VectorCraft addition: headline numbers unchanged.
- 2026-11-01: Document Tools, a built-in add-on (Object › Plug-ins › Document Tools), starts with Save a Timestamped Copy: a copy of the document named `<name>_YYYY-MM-DD_HH-MM` (UTC; `-2`, `-3`… when that name is taken) goes next to it, or into a folder picked for a document never saved, written as File › Save a Copy writes it, so the document keeps its path, title and modified state. Off on the web, which has no clock. A VectorCraft addition: headline numbers unchanged.
- 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged.
+1 -1
View File
@@ -27,7 +27,7 @@ log = { workspace = true }
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
# The page command API (storytold/craft-libs#413): the request plumbing behind window.vectorcraft.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "a4b6d3b6ca04a65d5972339b808d1049a14c7167", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "4bed21baaa41d2b47bef90879c04df521f6f6043", version = "0.1.0" }
wasm-bindgen = "0.2"
serde_json = { workspace = true }
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20v-8a8 8 0 0 1 8-8h8"/><path d="M12 12L6.34 6.34" stroke-dasharray="1.5 2"/><circle cx="12" cy="12" r="1.5" fill="currentColor"/></svg>

After

Width:  |  Height:  |  Size: 332 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 15l4-4 4 3 4-6 4 3v9H4Z" fill="currentColor" fill-opacity="0.4"/><path d="M4 4v16h16"/></svg>

After

Width:  |  Height:  |  Size: 289 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4v16h16"/><rect x="4" y="5" width="9" height="3"/><rect x="4" y="9.5" width="15" height="3"/><rect x="4" y="14" width="6" height="3"/></svg>

After

Width:  |  Height:  |  Size: 336 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4v16h16"/><rect x="7" y="11" width="3" height="9"/><rect x="11.5" y="6" width="3" height="14"/><rect x="16" y="9" width="3" height="11"/></svg>

After

Width:  |  Height:  |  Size: 339 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4v16h16"/><path d="M7 15l4-5 3 3 6-7"/></svg>

After

Width:  |  Height:  |  Size: 241 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="8"/><path d="M12 12V4a8 8 0 0 1 6.93 12Z" fill="currentColor" fill-opacity="0.4"/></svg>

After

Width:  |  Height:  |  Size: 299 B

+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="M12 4.5l7.61 5.53-2.91 8.94H7.3l-2.91-8.94Z"/><path d="M12 12.5V4.5M12 12.5l7.61-2.47M12 12.5l4.7 6.47M12 12.5l-4.7 6.47M12 12.5l-7.61-2.47" stroke-width="0.75"/><path d="M12 7.5l5.23 3.3-2.58 5.34-5.59.41-1.34-5.44Z" fill="currentColor" fill-opacity="0.4"/></svg>

After

Width:  |  Height:  |  Size: 457 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4v16h16"/><circle cx="8" cy="15" r="1.3" fill="currentColor"/><circle cx="10.5" cy="10" r="1.3" fill="currentColor"/><circle cx="13.5" cy="13.5" r="1.3" fill="currentColor"/><circle cx="16" cy="7.5" r="1.3" fill="currentColor"/><circle cx="18" cy="11.5" r="1.3" fill="currentColor"/></svg>

After

Width:  |  Height:  |  Size: 485 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4v16h16"/><rect x="4" y="5" width="9" height="3"/><rect x="4" y="9.5" width="15" height="3"/><rect x="4" y="14" width="6" height="3"/><rect x="4" y="5" width="5" height="3" fill="currentColor"/><rect x="4" y="9.5" width="8" height="3" fill="currentColor"/><rect x="4" y="14" width="3" height="3" fill="currentColor"/></svg>

After

Width:  |  Height:  |  Size: 519 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4v16h16"/><rect x="7" y="11" width="3" height="9"/><rect x="11.5" y="6" width="3" height="14"/><rect x="16" y="9" width="3" height="11"/><rect x="7" y="16" width="3" height="4" fill="currentColor"/><rect x="11.5" y="13" width="3" height="7" fill="currentColor"/><rect x="16" y="15" width="3" height="5" fill="currentColor"/></svg>

After

Width:  |  Height:  |  Size: 526 B

+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="M8 15.7A8.5 6.5 0 1 1 11 16.4"/><circle cx="7" cy="17.6" r="1.5"/><path d="M6.2 19c-.4 1-1 1.8-1.9 2.4"/><rect x="10" y="8" width="4" height="4" fill="currentColor"/></svg>

After

Width:  |  Height:  |  Size: 365 B

+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="M8 15.7L3.5 9 9 3.5l9 1 3 6.5-6 5.4h-4"/><circle cx="7" cy="17.6" r="1.5"/><path d="M6.2 19c-.4 1-1 1.8-1.9 2.4"/></svg>

After

Width:  |  Height:  |  Size: 313 B

+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="M8 15.7A8.5 6.5 0 1 1 11 16.4"/><circle cx="7" cy="17.6" r="1.5"/><path d="M6.2 19c-.4 1-1 1.8-1.9 2.4"/></svg>

After

Width:  |  Height:  |  Size: 304 B

+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="M2 21l4.5-9h7l4.5 9Z"/><path d="M10 12v9M4.25 16.5h11.5"/><path d="M15 2v9.5l2.4-2.3 1.7 3.6 1.5-.7-1.7-3.5h3.3Z" fill="currentColor"/></svg>

After

Width:  |  Height:  |  Size: 334 B

+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="butt" stroke-linejoin="miter"><path d="M3 12H21" stroke-dasharray="3 3"/></svg>

After

Width:  |  Height:  |  Size: 232 B

+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="butt" stroke-linejoin="miter"><path d="M3 12H20.5"/><path d="M15 6.5L20.5 12L15 17.5"/></svg>

After

Width:  |  Height:  |  Size: 246 B

+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="M3 7h9v2h9v9H3Z"/><path d="M12 9v9" stroke-dasharray="2 2"/></svg>

After

Width:  |  Height:  |  Size: 259 B

+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"><rect x="3" y="3" width="10" height="10" stroke-dasharray="2 2.5"/><rect x="3" y="3" width="4" height="3.5" fill="currentColor"/><path d="M14.5 12.5v9l2.3-2.2 1.6 3.4 1.4-.7-1.6-3.3h3.1Z" fill="currentColor"/></svg>

After

Width:  |  Height:  |  Size: 399 B

+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"><rect x="3" y="3" width="10" height="10" stroke-dasharray="2 2.5"/><rect x="3" y="3" width="4" height="3.5" fill="currentColor"/><path d="M11.5 21.5l2.5-6 3.5 3.5Z" fill="currentColor"/><path d="M15.75 17.25l4.5-4.5a1.6 1.6 0 0 1 2.25 2.25l-4.5 4.5Z"/></svg>

After

Width:  |  Height:  |  Size: 442 B

+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="M3 18C7 8 17 8 21 18"/><rect x="10.5" y="9" width="3" height="3" fill="currentColor"/><path d="M8 5H3.5M5.5 3L3.5 5l2 2M16 5h4.5M18.5 3l2 2-2 2"/></svg>

After

Width:  |  Height:  |  Size: 345 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="5.5" cy="12" r="3" fill="currentColor"/><circle cx="12" cy="12" r="3" fill="currentColor" fill-opacity="0.4"/><circle cx="18.5" cy="12" r="3"/></svg>

After

Width:  |  Height:  |  Size: 345 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="10.5" r="2"/><circle cx="14" cy="10.5" r="2"/><circle cx="12" cy="14" r="2"/><path d="M2 12h4M4.5 10.5L6 12l-1.5 1.5M22 12h-4M19.5 10.5L18 12l1.5 1.5"/></svg>

After

Width:  |  Height:  |  Size: 362 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6.5" r="2"/><circle cx="5" cy="12" r="2"/><circle cx="7" cy="17.5" r="2"/><path d="M11 12h10M18 9l3 3-3 3"/></svg>

After

Width:  |  Height:  |  Size: 317 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="18" r="2"/><circle cx="15.5" cy="8.5" r="5.5"/><path d="M8 16l3-3M8.5 13H11v2.5"/></svg>

After

Width:  |  Height:  |  Size: 291 B

+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="M12 9l3 3-3 3-3-3Z"/><path d="M19.5 12a7.5 7.5 0 1 1-2.2-5.3"/><path d="M17.3 3.2v3.5h-3.5"/></svg>

After

Width:  |  Height:  |  Size: 292 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="6.5" cy="7" r="2.5"/><circle cx="6.5" cy="16.5" r="2.5" fill="currentColor"/><path d="M16 5c2.6 3.5 4 5.6 4 7.6a4 4 0 0 1-8 0c0-2 1.4-4.1 4-7.6Z" fill="currentColor"/></svg>

After

Width:  |  Height:  |  Size: 369 B

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="15" r="3.5"/><circle cx="15.5" cy="11" r="4.5" fill="currentColor" fill-opacity="0.4"/><circle cx="15.5" cy="11" r="2"/><path d="M19.5 2.5v3M18 4h3"/></svg>

After

Width:  |  Height:  |  Size: 359 B

+1 -1
View File
@@ -219,7 +219,7 @@ pub fn set_live_art(f: LiveArt, inputs: LiveInputs) {
}
/// The registered [`LiveInputs`] now, 0 while nothing is registered.
fn live_inputs() -> u64 {
pub fn live_inputs() -> u64 {
LIVE_ART.get().map_or(0, |(_, inputs)| inputs())
}
+83 -20
View File
@@ -293,8 +293,15 @@ pub fn is_white(p: &Paint) -> bool {
}
}
/// Whether `p` is paper white: white ([`is_white`]) and not a tint above 0% of one of the spot
/// inks `spots` ([`Document::spot_ink_names`]). The white of a spot swatch (an opaque white ink,
/// for example) is an ink of its own; a 0% tint puts no ink down.
pub fn is_paper_white(p: &Paint, spots: &BTreeSet<String>) -> bool {
is_white(p) && !matches!(p, Paint::Solid { swatch: Some(name), tint, .. } if *tint > 0.0 && spots.contains(name))
}
/// Discard White Overprint (Document Setup) as output applies it: whether it is on, and the spot
/// inks a white tint of which still overprints ([`Document::spot_ink`]).
/// inks a white tint of which still overprints ([`Document::spot_ink_names`]).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct DiscardWhite {
on: bool,
@@ -304,8 +311,13 @@ pub struct DiscardWhite {
impl DiscardWhite {
/// The document's setting and spot inks.
pub fn of(doc: &Document) -> Self {
let spot_inks = doc.swatches_iter().map(|s| &s.name).filter(|n| doc.swatch(n).is_some_and(|s| s.spot && s.paint.color().is_some()));
Self { on: doc.setup.discard_white_overprint, spot_inks: spot_inks.cloned().collect() }
Self::printing(doc, |_| true)
}
/// The document's setting when only the spot inks for which `spot` is true print as spot
/// inks: a white of another one (converted to process inks) is paper white.
pub fn printing(doc: &Document, spot: impl Fn(&str) -> bool) -> Self {
Self { on: doc.setup.discard_white_overprint, spot_inks: doc.spot_ink_names().into_iter().filter(|n| spot(n)).collect() }
}
/// The setting `on`, with no spot inks.
@@ -314,32 +326,31 @@ impl DiscardWhite {
}
/// Whether `p` loses its overprint: the setting is on and `p` is paper white
/// ([`is_white`]), not a tint above 0% of a spot ink, which prints as that ink.
/// ([`Self::paper_white`]), not a tint above 0% of a spot ink, which prints as that ink.
pub fn discards(&self, p: &Paint) -> bool {
let spot = matches!(p, Paint::Solid { swatch: Some(name), tint, .. } if *tint > 0.0 && self.spot_inks.contains(name));
self.on && is_white(p) && !spot
self.on && self.paper_white(p)
}
/// Whether `p` is paper white with these spot inks ([`is_paper_white`]), whether the setting
/// is on or off: an overprinting paper white puts no ink down.
pub fn paper_white(&self, p: &Paint) -> bool {
is_paper_white(p, &self.spot_inks)
}
}
impl Document {
/// The names of the spot swatches that a color linked by name prints as: a name whose first
/// swatch ([`Document::swatch`]) is not a solid spot color is left out.
pub fn spot_ink_names(&self) -> BTreeSet<String> {
let mut seen = BTreeSet::new();
self.swatches_iter().filter(|s| seen.insert(s.name.as_str()) && s.spot && s.paint.color().is_some()).map(|s| s.name.clone()).collect()
}
/// The names of the spot swatches.
pub fn spot_names(&self) -> Vec<String> {
self.swatches_iter().filter(|s| s.spot).map(|s| s.name.clone()).collect()
}
/// Whether `p` is a tint above 0% of a spot swatch with a solid color, which prints as an ink
/// of its own even when its color is white ([`is_white`]); a link is judged by the first
/// swatch of its name.
pub fn spot_ink(&self, p: &Paint) -> bool {
matches!(p, Paint::Solid { swatch: Some(name), tint, .. } if *tint > 0.0 && self.swatch(name).is_some_and(|s| s.spot && s.paint.color().is_some()))
}
/// Whether Discard White Overprint (Document Setup) takes the overprint off `p`
/// ([`DiscardWhite::discards`]).
pub fn discards_white_overprint(&self, p: &Paint) -> bool {
self.setup.discard_white_overprint && is_white(p) && !self.spot_ink(p)
}
/// Files from before per-fill/stroke overprint listed the objects marked Overprint Black
/// under [`LEGACY_OVERPRINT_KEY`]: their 100% black fills and strokes overprint now.
pub fn migrate_overprint_black(&mut self) {
@@ -488,6 +499,58 @@ mod tests {
assert!(OverprintBlack { spot: true, ..Default::default() }.apply(&mut n, &spots), "Include Spot Blacks takes it");
}
#[test]
fn a_white_spot_ink_overprints_under_discard_white() {
let mut d = Document::new(100.0, 100.0);
let white = Color::cmyk(0.0, 0.0, 0.0, 0.0);
d.swatches.push(vectorcraft_color::Swatch { name: "Opaque White".into(), paint: Paint::solid(white), global: true, spot: true });
d.swatches.push(vectorcraft_color::Swatch { name: "Process White".into(), paint: Paint::solid(white), global: true, spot: false });
let spot = Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 1.0 };
let process = Paint::Solid { color: white, swatch: Some("Process White".into()), tint: 1.0 };
let paper = Paint::solid(white);
assert!(d.setup.discard_white_overprint, "on by default");
d.swatches.push(vectorcraft_color::Swatch {
name: "Red Ink".into(),
paint: Paint::solid(Color::cmyk(0.0, 1.0, 1.0, 0.0)),
global: true,
spot: true,
});
// A 0% tint of a spot ink resolves to white and puts no ink down.
let no_red = Paint::Solid { color: white, swatch: Some("Red Ink".into()), tint: 0.0 };
let no_white = Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 0.0 };
let half_white = Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 0.5 };
let discard = DiscardWhite::of(&d);
assert!(discard.discards(&paper), "paper white knocks out");
assert!(discard.discards(&process), "so does a global process white");
assert!(!discard.discards(&spot) && !discard.discards(&half_white), "a white spot ink is an ink");
assert!(discard.discards(&no_red) && discard.discards(&no_white), "a 0% tint of a spot ink is paper white");
assert!(!is_paper_white(&spot, &d.spot_ink_names()) && is_paper_white(&paper, &d.spot_ink_names()));
let converted = DiscardWhite::printing(&d, |n| n != "Opaque White");
assert!(converted.discards(&spot), "a white spot ink printed as process inks is paper white");
// A spot swatch after a process one of the same name: a link finds the process one.
d.swatches.push(vectorcraft_color::Swatch { name: "Process White".into(), paint: Paint::solid(white), global: true, spot: true });
assert!(DiscardWhite::of(&d).discards(&process), "the first swatch of the name decides");
// A spot swatch without a solid color prints a linked solid as its own process color.
d.swatches.push(vectorcraft_color::Swatch { name: "Empty".into(), paint: Paint::None, global: true, spot: true });
let empty = Paint::Solid { color: white, swatch: Some("Empty".into()), tint: 1.0 };
assert!(DiscardWhite::of(&d).discards(&empty), "so it is paper white");
d.setup.discard_white_overprint = false;
assert!(!DiscardWhite::of(&d).discards(&paper), "off: white overprints too");
// The previews and plates darken the spot ink and leave paper white knocking out.
let blend = |fill: Paint| {
let mut n = Node::path(NodeId(1), Default::default(), Appearance::basic(fill, Paint::None, 0.0));
if let Some(f) = n.appearance.fill_mut() {
f.overprint = true;
}
let mut a = Arc::new(n);
darken_overprints(&mut a, &discard, &BTreeMap::new());
a.appearance.fill().map(|f| f.blend)
};
assert_eq!(blend(spot), Some(BlendMode::Darken));
assert_eq!(blend(paper), Some(BlendMode::Normal));
}
#[test]
fn apply_deep_copies_only_the_nodes_that_change() {
let k = cmyk(0.0, 0.0, 0.0, 1.0);
@@ -560,7 +623,7 @@ mod tests {
};
let spot = linked("White Ink", 0.5);
assert_eq!(blend(spot.clone(), spot.clone()), (BlendMode::Darken, Some(BlendMode::Darken)));
assert!(doc.spot_ink(&spot) && !discard.discards(&spot));
assert!(!discard.paper_white(&spot) && !discard.discards(&spot));
for knocks_out in [linked("White Ink", 0.0), linked("Paper", 1.0), Paint::solid(white)] {
assert!(discard.discards(&knocks_out), "{knocks_out:?}");
assert_eq!(blend(knocks_out.clone(), knocks_out.clone()).0, BlendMode::Normal, "{knocks_out:?}");
+3 -2
View File
@@ -846,8 +846,9 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
pub use addons::{fold_source, print_hidden};
/// Document Info's category titles and the Objects category's count labels.
pub use docinfo::{CATEGORIES, OBJECT_LABELS};
/// Document Info's category titles, the Objects category's count labels, and how its image rows
/// write a resolution and a number of bytes.
pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number};
pub use docmenu::guide_indexes;
pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress};
pub(crate) use object::bounds_rewrite;
+1 -1
View File
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Ink Fixes",
["Object", "Plug-ins", "Color Effects"],
None,
"{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes, and colorized images with a white color, stop overprinting), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}",
"{scope?: \"selection\" (the selection, or `ids`; by default, the document while nothing is selected) | \"document\" (every layer), inkLimit?: total ink % 1..400 (0 or left out: off), excludePureBlack?: true (black-only and grey colours keep their ink), removeWhiteOverprint?: false (white fills and strokes, and colorized images with a white color, stop overprinting; a white linked to a spot swatch at a tint above 0% is an ink and keeps it), overprintBlack?: black % 1..100 (black-only and grey fills and strokes this dark or darker overprint, as edit.colors.overprintBlack; 0 or left out: off), textOnly?: false (Overprint Black on type only), fill?: true, stroke?: true, ids?: [id…]} prepare a CMYK document's inks for print as one undo step: CMYK colours (solid, gradient stops, gradient meshes) with more total ink than inkLimit are scaled down to it (colours of spot swatches and Registration stay), white overprint is removed and black overprint set. Refused in RGB documents (File › Document Color Mode › CMYK Color first). On a path directly in a graph series, the graph also stores a paint the ink limit changes on the topmost visible fill or stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, inkLimited: paints and meshes scaled, whiteOverprintRemoved: objects, blackOverprinted: objects}",
has_doc,
print_fixes::run
),
@@ -1,14 +1,15 @@
//! Print Ink Fixes (`addon.color.printFixes`, Object › Plug-ins › Color Effects › Print Ink
//! Fixes…): a CMYK document's inks made ready for print in one undo step. Colours with more total
//! ink than the limit are scaled down to it, white fills and strokes stop overprinting, and black
//! ink than the limit are scaled down to it, paper white fills and strokes stop overprinting, and black
//! ones start to, as Edit › Edit Colors › Overprint Black sets it.
use std::collections::BTreeSet;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_doc::overprint::{OverprintBlack, is_white};
use vectorcraft_doc::overprint::{OverprintBlack, is_paper_white};
use vectorcraft_doc::{ColorMode, Node, NodeKind};
use super::super::super::colorcmds::{Recolor, Scope, keeping_series_paint};
@@ -78,8 +79,9 @@ impl Fixes {
}
/// Remove white overprint from `n`'s own fills and strokes and its characters': true when
/// that changed anything.
fn unset_white(&self, n: &mut Node) -> bool {
/// that changed anything. A white linked to one of the spot inks `inks` is an ink and keeps
/// overprinting ([`is_paper_white`]).
fn unset_white(&self, n: &mut Node, inks: &BTreeSet<String>) -> bool {
let mut changed = false;
let mut off = |aimed: bool, white: bool, flag: &mut bool| {
if aimed && white && *flag {
@@ -89,31 +91,32 @@ impl Fixes {
};
for it in &mut n.appearance.items {
let aimed = if it.is_fill() { self.fill } else { self.stroke };
let white = is_white(it.paint());
let white = is_paper_white(it.paint(), inks);
off(aimed, white, it.overprint_mut());
}
if let NodeKind::Text(t) = &mut n.kind {
for r in &mut t.runs {
off(self.fill, is_white(&r.style.fill), &mut r.style.overprint_fill);
off(self.stroke, is_white(&r.style.stroke), &mut r.style.overprint_stroke);
off(self.fill, is_paper_white(&r.style.fill, inks), &mut r.style.overprint_fill);
off(self.stroke, is_paper_white(&r.style.stroke, inks), &mut r.style.overprint_stroke);
}
}
// A colorized image's color is its fill.
if n.colorize_overprints() {
let white = n.extras().colorize.as_deref().is_some_and(is_white);
let white = n.extras().colorize.as_deref().is_some_and(|p| is_paper_white(p, inks));
off(self.fill, white, &mut n.extras_mut().colorize_overprint);
}
changed
}
/// The overprint fixes on `n` and everything inside it: (objects whose white overprint was
/// removed, objects set to overprint black).
fn overprint(&self, n: &mut Node, black: &OverprintBlack, spots: &[String]) -> (usize, usize) {
let white = usize::from(self.remove_white_overprint && self.unset_white(n));
/// removed, objects set to overprint black). `spots`: the document's spot swatch names; `inks`:
/// those that linked colors print as ([`vectorcraft_doc::Document::spot_ink_names`]).
fn overprint(&self, n: &mut Node, black: &OverprintBlack, spots: &[String], inks: &BTreeSet<String>) -> (usize, usize) {
let white = usize::from(self.remove_white_overprint && self.unset_white(n, inks));
let blacks = self.overprint_black > 0.0 && (!self.text_only || matches!(n.kind, NodeKind::Text(_)));
let mut counts = (white, usize::from(blacks && black.apply(n, spots)));
for c in n.children_mut().into_iter().flatten().filter(|c| !c.is_ruler_guide()) {
let (w, b) = self.overprint(Arc::make_mut(c), black, spots);
let (w, b) = self.overprint(Arc::make_mut(c), black, spots, inks);
counts = (counts.0 + w, counts.1 + b);
}
counts
@@ -159,10 +162,10 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
if !fixes.remove_white_overprint && fixes.overprint_black <= 0.0 {
return Ok(ink);
}
let spots = d.spot_names();
let (spots, inks) = (d.spot_names(), d.spot_ink_names());
for id in &ids {
if let Some(n) = d.node_mut(*id) {
let (w, b) = fixes.overprint(n, &black, &spots);
let (w, b) = fixes.overprint(n, &black, &spots, &inks);
(white, blacks) = (white + w, blacks + b);
}
}
@@ -101,6 +101,20 @@ fn white_overprint_goes_and_black_overprint_comes_at_the_threshold() {
assert_eq!(s.execute(C, &json!({"overprintBlack": 90, "fill": false})).unwrap()["changed"], 0);
}
#[test]
fn a_white_spot_ink_keeps_its_overprint() {
let white = cmyk(0.0, 0.0, 0.0, 0.0);
let (mut s, ids) = doc(&[(white.clone(), true), (white.clone(), true)]);
s.execute("swatch.new", &json!({"name": "Opaque White", "color": white, "spot": true})).unwrap();
s.execute("select.set", &json!({"ids": [ids[1].0]})).unwrap();
s.execute("paint.setFill", &json!({"swatch": "Opaque White"})).unwrap();
s.execute("select.none", &json!({})).unwrap();
assert!(fill(&s, ids[1]).1, "the swatch keeps the overprint");
let v = s.execute(C, &json!({"removeWhiteOverprint": true})).unwrap();
assert_eq!(v["whiteOverprintRemoved"], 1, "{v}");
assert_eq!([fill(&s, ids[0]).1, fill(&s, ids[1]).1], [false, true], "paper white stops; the spot white is an ink");
}
#[test]
fn bad_requests_and_rgb_documents_are_refused() {
let (mut s, ids) = doc(&[(cmyk(100.0, 100.0, 100.0, 100.0), true)]);
+4 -2
View File
@@ -4,8 +4,8 @@
//! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's
//! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes
//! into Paths, Trim at Crossings ([`trim`]), Smooth Bridge ([`bridge`]), Common Tangents
//! ([`tangents`]), Tangent Circle ([`tangent_circle`]) and Add Bounding Rectangle and Add
//! Bounding Circle ([`bounding`]).
//! ([`tangents`]), Tangent Circle ([`tangent_circle`]), Add Bounding Rectangle and Add
//! Bounding Circle ([`bounding`]) and Add Inscribed Circle ([`inscribed`]).
//! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's
//! and the UI's.
@@ -14,6 +14,7 @@ mod bridge;
mod corners;
#[cfg(test)]
mod effect_tests;
mod inscribed;
mod shape;
mod shared_edge;
mod tangent_circle;
@@ -190,6 +191,7 @@ pub fn specs() -> Vec<CommandSpec> {
v.extend(tangent_circle::specs());
v.extend(tangents::specs());
v.extend(bounding::specs());
v.extend(inscribed::specs());
v
}
@@ -49,7 +49,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
/// Enabled with a selection that is not an object of a symbol instance's art, which
/// [`selected_roots_to_transform`] refuses.
fn whole_objects(s: &Session) -> std::result::Result<(), String> {
pub(super) fn whole_objects(s: &Session) -> std::result::Result<(), String> {
has_selection(s)?;
no_symbol_part(s)
}
@@ -0,0 +1,97 @@
//! Add Inscribed Circle: the largest live circle inside each selected closed path or compound
//! path. The circle is the pathops crate's
//! ([`inscribed_circle`](vectorcraft_pathops::addons::pathtools::inscribed_circle)).
use serde_json::{Value, json};
use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind};
use vectorcraft_geom::{Affine, FillRule, PathData};
use vectorcraft_pathops::addons::pathtools::{self as pt, InscribedError};
use super::super::super::edit::selected_roots_to_transform;
use super::super::super::{CommandSpec, bad, cmd};
use super::bounding::whole_objects;
use crate::{Result, Session};
#[cfg(test)]
mod tests;
/// The command.
pub(crate) const COMMAND: &str = "addon.pathtools.inscribedCircle";
/// The undo step's name.
const LABEL: &str = "Add Inscribed Circle";
/// How far a live circle's four curves reach past a true circle, as a share of its radius: at
/// most 0.0273%, about 20° from each axis.
const CIRCLE_BULGE: f64 = 3e-4;
pub(super) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.pathtools.inscribedCircle",
"Add Inscribed Circle",
["Object", "Plug-ins", "Path Precision Tools"],
None,
"{} draw the largest live circle inside each selected closed path or compound path (a path of a compound path selected on its own counts as a path): the circle lies in the area the path fills under its fill rule, so holes and the overlaps of crossing subpaths count as the fill shows them, and before it is drawn its radius is within 0.02 pt of the largest (when the filled area's box is at least 10 pt across on its narrower side; for a smaller one, within a five-hundredth of that side; a curve whose control polygon is longer than 4096² times the flattening tolerance, half the search's precision (83,886 pt at 0.005 pt), is flattened more coarsely, and the circle can be smaller by as much; a curved hole narrower than the flattening tolerance can also make it smaller; a shape that flattening would close up or move off its curves is flattened finer, down to 1/65,536 of the tolerance). The drawn circle's four curves reach up to 0.03% of its radius past a true circle, so it is drawn 0.03% smaller and stays inside where it touches. Holes and gaps narrower than 1e-6 pt close up, and edges can move by as much, as in the other path operations. Strokes and effects are left out. The circles get the current paint and go on top of the current layer or of the isolated group, as other new art; inside an isolated compound path they join it and take its appearance; they are selected; one undo step. It is an error, with the document unchanged, when a selected object is not a closed path or compound path (\"object N is not a closed path or compound path\"; an open path has no inside), when it fills no area (\"object N fills no area\"), and when its outline has more than 262,144 anchors (in subpaths of two or more) or more than 262,144 straight pieces once flattened, or the searches of the selected objects together measure more than 134,217,728 distances from a point to an edge, or one search keeps more than 1,048,576 cells waiting, or the shape is so thin for its length that it flattens to no area even at the finest tolerance (\"object N is too complex to measure\") → {id: the first circle, ids}",
whole_objects,
inscribed_circle
)]
}
/// The outline of path or compound path `id` and its fill rule; `None` for anything else, an open
/// path, or a compound path with an open member.
fn outline(d: &Document, id: NodeId) -> Option<(PathData, FillRule)> {
let n = d.node(id)?;
let (paths, rule): (Vec<&PathData>, FillRule) = match &n.kind {
NodeKind::Path { path, rule, .. } => (vec![path], *rule),
NodeKind::Compound { children, rule } => (children.iter().filter_map(|c| c.path_data()).collect(), *rule),
_ => return None,
};
let subpaths: Vec<_> = paths.iter().flat_map(|p| p.subpaths.iter()).filter(|sp| !sp.anchors.is_empty()).collect();
if subpaths.is_empty() || subpaths.iter().any(|sp| !sp.closed) {
return None;
}
Some((PathData::new(subpaths.into_iter().cloned().collect()), rule))
}
fn inscribed_circle(s: &mut Session, _p: &Value) -> Result<Value> {
// The roots leave out selected layers, which are not paths either.
let st = s.doc()?;
if let Some(layer) = st.selection.objects.iter().find(|id| st.doc.node(**id).is_some_and(Node::is_layer)) {
return Err(bad(COMMAND, format!("object {} is not a closed path or compound path", layer.0)));
}
let roots = selected_roots_to_transform(s)?;
let d = &s.doc()?.doc;
let mut circles = vec![];
// The searches share one work limit, so the command stays bounded however many objects are
// selected.
let mut work = pt::MAX_INSCRIBED_WORK;
for id in roots {
let value = id.0;
let Some((path, rule)) = outline(d, id) else {
return Err(bad(COMMAND, format!("object {value} is not a closed path or compound path")));
};
let c = pt::inscribed_circle_within(&path, rule, &mut work).map_err(|e| match e {
InscribedError::NoArea => bad(COMMAND, format!("object {value} fills no area")),
InscribedError::TooComplex => bad(COMMAND, format!("object {value} is too complex to measure")),
})?;
circles.push(c);
}
// Path art: inside an isolated compound path, the circles join it, as Tangent Circle's do.
let parent = s.doc()?.target_parent_for_path()?;
let look = s.new_art_look(s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width);
let ids = s.edit(LABEL, |d, sel| {
let mut ids = vec![];
for c in &circles {
// Smaller by the curves' bulge, so the drawn circle stays inside where it touches.
let (r, at) = (c.radius / (1.0 + CIRCLE_BULGE), c.center);
let live = LiveShape::Ellipse { w: 2.0 * r, h: 2.0 * r, pie: (0.0, 360.0), xf: Affine::translate((at.x - r, at.y - r)) };
let kind = NodeKind::Path { path: live.to_path(), rule: FillRule::NonZero, live: Some(Box::new(live)), clipping: false, guide: false };
let mut n = Node::new(d.alloc_id(), kind);
look.apply(d, &mut n);
ids.push(n.id);
d.insert(parent, usize::MAX, n)?;
}
sel.set(ids.iter().copied());
Ok(ids)
})?;
let first = ids.first().map_or(0, |id| id.0);
Ok(json!({ "id": first, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
}
@@ -0,0 +1,221 @@
//! Add Inscribed Circle: the largest circle in a square, a concave shape and a ring compound path
//! under its fill rule, one circle per object as one undo step, the drawn circle inside where its
//! curves bulge, and the errors that leave the document as it was.
use serde_json::{Value, json};
use vectorcraft_doc::{LiveShape, NodeId, NodeKind};
use vectorcraft_geom::Point;
use super::COMMAND;
use crate::Session;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s
}
fn id_of(v: &Value) -> NodeId {
NodeId(v["id"].as_u64().unwrap())
}
fn ids_of(v: &Value) -> Vec<NodeId> {
v["ids"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect()
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
fn undo_len(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn object_count(s: &Session) -> usize {
let mut n = 0;
s.doc().unwrap().doc.walk(|_| n += 1);
n
}
/// The center and radius of the live circle `id`.
fn circle(s: &Session, id: NodeId) -> (Point, f64) {
match &s.doc().unwrap().doc.node(id).unwrap().kind {
NodeKind::Path { live: Some(live), .. } => match live.as_ref() {
LiveShape::Ellipse { w, h, xf, .. } => {
assert!((w - h).abs() < 1e-9, "a circle, not an ellipse");
(*xf * Point::new(w / 2.0, h / 2.0), w / 2.0)
}
other => panic!("not a live ellipse: {other:?}"),
},
other => panic!("not a live shape: {other:?}"),
}
}
/// The smallest drawn radius for a largest circle of radius `largest`: smaller by the curves'
/// bulge, and by the search's 0.02 pt.
fn least(largest: f64) -> f64 {
largest / (1.0 + super::CIRCLE_BULGE) - 0.02
}
/// The command on the selection fails with a message holding `want`, and the document is as it was.
fn refused(s: &mut Session, want: &str) {
let (undo, objects) = (undo_len(s), object_count(s));
let e = s.execute(COMMAND, &json!({})).unwrap_err().to_string();
assert!(e.contains(want), "{e}");
assert_eq!((undo_len(s), object_count(s)), (undo, objects));
}
/// The circle in a square sits at its center and touches its sides, gets the current paint, goes
/// on top of the layer and is selected; one undo removes it.
#[test]
fn a_square_gets_the_circle_that_touches_its_sides() {
let mut s = session();
let sq = id_of(&s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap());
let (undo, objects) = (undo_len(&s), object_count(&s));
let out = s.execute(COMMAND, &json!({})).unwrap();
let id = id_of(&out);
let (center, r) = circle(&s, id);
assert!((center - Point::new(150.0, 150.0)).hypot() < 0.02 && r <= 50.0 + 1e-6 && r > least(50.0), "{center:?} {r}");
assert_eq!(s.doc().unwrap().selection.objects, vec![id]);
let d = &s.doc().unwrap().doc;
let parent = d.parent_of(sq).unwrap();
assert_eq!(d.parent_of(id), Some(parent));
assert_eq!(d.node(parent).unwrap().children().unwrap().last().map(|n| n.id), Some(id), "on top of the layer");
// The current paint, as the rectangle drawn before got it.
let (n, r) = (d.node(id).unwrap(), d.node(sq).unwrap());
assert_eq!((n.appearance.fill_paint(), n.appearance.stroke_paint()), (r.appearance.fill_paint(), r.appearance.stroke_paint()));
assert_eq!(undo_len(&s), undo + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(object_count(&s), objects);
}
/// The circle in an L sits in its corner, inside the shape, where the box's center is outside.
#[test]
fn a_concave_shape_gets_the_circle_in_its_corner() {
let mut s = session();
let anchors = [(0, 0), (100, 0), (100, 30), (30, 30), (30, 100), (0, 100)].map(|(x, y)| json!({"x": x, "y": y}));
s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap();
let id = id_of(&s.execute(COMMAND, &json!({})).unwrap());
let (center, r) = circle(&s, id);
let largest = 30.0 * std::f64::consts::SQRT_2 / (1.0 + std::f64::consts::SQRT_2);
assert!(r <= largest + 1e-6 && r > least(largest), "{r}");
assert!(center.x < 30.0 && center.y < 30.0, "{center:?}");
}
/// A compound path of two concentric circles: under even-odd the inner one is a hole, and the
/// circle lies in the ring beside it. Under nonzero it is a hole while the two circles turn
/// opposite ways, and with both turning the same way the circle fills the outer one.
#[test]
fn a_ring_compound_path_gets_a_circle_by_its_fill_rule() {
let mut s = session();
let outer = id_of(&s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 200})).unwrap());
let inner = id_of(&s.execute("shape.ellipse", &json!({"x": 160, "y": 160, "width": 80, "height": 80})).unwrap());
select(&mut s, &[outer, inner]);
let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
let ring = Point::new(200.0, 200.0);
let cases = [("evenOdd", false, 70.0, 30.0), ("nonZero", false, 70.0, 30.0), ("nonZero", true, 0.0, 100.0), ("evenOdd", true, 70.0, 30.0)];
for (rule, same_way, around, largest) in cases {
select(&mut s, &[compound]);
let both = s.doc().unwrap().doc.node(compound).unwrap().children().unwrap().iter().map(|n| n.id.0).collect::<Vec<_>>();
s.execute("path.reverse", &json!({"ids": both, "reversed": true})).unwrap();
if !same_way {
s.execute("path.reverse", &json!({"ids": [both[1]], "reversed": false})).unwrap();
}
s.execute("path.setFillRule", &json!({"rule": rule, "ids": [compound.0]})).unwrap();
select(&mut s, &[compound]);
let id = id_of(&s.execute(COMMAND, &json!({})).unwrap());
let (center, r) = circle(&s, id);
assert!(r > least(largest) && r < largest + 0.0003 * 140.0, "{rule} {same_way}: {r}");
assert!(((center - ring).hypot() - around).abs() < 0.1, "{rule} {same_way}: {center:?}");
}
}
/// Each selected path gets its own circle, all as one undo step; a path of a compound path
/// selected on its own gets a circle of its own outline.
#[test]
fn each_selected_path_gets_a_circle_in_one_step() {
let mut s = session();
let a = id_of(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap());
let b = id_of(&s.execute("shape.rectangle", &json!({"x": 100, "y": 0, "width": 40, "height": 80})).unwrap());
select(&mut s, &[a, b]);
let undo = undo_len(&s);
let ids = ids_of(&s.execute(COMMAND, &json!({})).unwrap());
assert_eq!(ids.len(), 2);
assert_eq!(undo_len(&s), undo + 1);
let centers: Vec<Point> = ids.iter().map(|id| circle(&s, *id).0).collect();
assert!(centers.iter().any(|c| c.x < 40.0) && centers.iter().any(|c| c.x > 100.0), "{centers:?}");
s.execute("edit.undo", &json!({})).unwrap();
select(&mut s, &[a, b]);
let compound = id_of(&s.execute("object.compoundPath.make", &json!({})).unwrap());
let member = s.doc().unwrap().doc.node(compound).unwrap().children().unwrap()[0].id;
select(&mut s, &[member]);
let id = id_of(&s.execute(COMMAND, &json!({})).unwrap());
let r = circle(&s, id).1;
assert!(r <= 20.0 + 1e-6 && r > least(20.0), "the member's own square: {r}");
// Inside the isolated compound path, the circle joins it.
s.execute("object.isolate", &json!({"id": compound.0})).unwrap();
select(&mut s, &[member]);
let id = id_of(&s.execute(COMMAND, &json!({})).unwrap());
assert_eq!(s.doc().unwrap().doc.parent_of(id), Some(compound));
}
/// The drawn circle stays inside a large square turned so that it touches the square's sides
/// where its curves bulge most past a true circle, about 20° from each axis.
#[test]
fn the_drawn_circle_stays_inside_where_its_curves_bulge() {
let mut s = session();
let (center, half) = (Point::new(1200.0, 1200.0), 1000.0);
for degrees in [15.0_f64, 19.4, 25.0] {
let (sin, cos) = degrees.to_radians().sin_cos();
let corner = |u: f64, v: f64| json!({"x": center.x + u * cos - v * sin, "y": center.y + u * sin + v * cos});
let anchors = [(-half, -half), (half, -half), (half, half), (-half, half)].map(|(u, v)| corner(u, v));
s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap();
let id = id_of(&s.execute(COMMAND, &json!({})).unwrap());
let NodeKind::Path { path, .. } = &s.doc().unwrap().doc.node(id).unwrap().kind else {
panic!("not a path");
};
for seg in path.to_bezpath().segments() {
for i in 0..=200 {
let p = vectorcraft_geom::ParamCurve::eval(&seg, f64::from(i) / 200.0) - center;
let (u, v) = (p.x * cos + p.y * sin, -p.x * sin + p.y * cos);
assert!(u.abs().max(v.abs()) <= half, "{degrees}°: ({u}, {v}) is outside the square");
}
}
}
}
/// An open path, an object that is not a path or compound path, a path that fills no area and an
/// empty selection are errors, and nothing is drawn.
#[test]
fn open_paths_other_objects_and_no_selection_are_refused() {
let mut s = session();
assert!(s.execute(COMMAND, &json!({})).is_err(), "nothing selected");
let open = id_of(&s.execute("path.create", &json!({"anchors": [{"x": 0, "y": 0}, {"x": 80, "y": 0}, {"x": 0, "y": 60}]})).unwrap());
select(&mut s, &[open]);
refused(&mut s, "is not a closed path or compound path");
let sq = id_of(&s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 50, "height": 50})).unwrap());
select(&mut s, &[sq]);
let group = id_of(&s.execute("object.group", &json!({})).unwrap());
select(&mut s, &[group]);
refused(&mut s, "is not a closed path or compound path");
// One refused object leaves the other selected objects without a circle too.
select(&mut s, &[group, open]);
refused(&mut s, "is not a closed path or compound path");
let flat = [(0, 300), (100, 300), (50, 300)].map(|(x, y)| json!({"x": x, "y": y}));
let flat = id_of(&s.execute("path.create", &json!({"anchors": flat, "closed": true})).unwrap());
select(&mut s, &[flat]);
refused(&mut s, "fills no area");
// A selected layer is refused too, alone or with a path.
let mut layer = None;
s.doc().unwrap().doc.walk(|n| {
if n.is_layer() {
layer.get_or_insert(n.id);
}
});
let layer = layer.unwrap();
let path = id_of(&s.execute("shape.rectangle", &json!({"x": 200, "y": 100, "width": 50, "height": 50})).unwrap());
for ids in [vec![layer], vec![layer, path]] {
select(&mut s, &ids);
refused(&mut s, "is not a closed path or compound path");
}
}
+18
View File
@@ -1198,6 +1198,24 @@ pub(crate) fn capture_series_paint_writes(
super::graph::capture_series_top_paints(d, &rows)
}
/// Store on the graph the opacity and blend mode of each row an edit wrote (`written`: an object with the index of the
/// row) on the series marks among them, when that row is the topmost visible one of its kind, also when the mark
/// already showed that opacity: it replaces the opacity another mark of the series left on the graph. When the edit
/// reaches several marks of one series, the frontmost one sets what the graph stores. Returns whether the stored
/// opacity or blend mode changed.
pub(crate) fn capture_series_opacity_writes(d: &mut vectorcraft_doc::Document, written: &[(NodeId, usize)]) -> bool {
let ids: Vec<NodeId> = written.iter().map(|(id, _)| *id).collect();
// A later mark's capture replaces an earlier one's: take them in paint order.
let rows: Vec<(NodeId, bool)> = series_children_in_paint_order(d, &ids)
.into_iter()
.flat_map(|id| {
let shown = written.iter().filter(move |(w, _)| *w == id).filter_map(|(_, at)| Some((id, top_row_kind(&d.node(id)?.appearance, *at)?)));
shown.collect::<Vec<_>>()
})
.collect();
super::graph::capture_series_opacity(d, &rows)
}
/// The kind of the row at `at` (fill `true`, stroke `false`) when it is the topmost visible row of that kind in `ap`.
fn top_row_kind(ap: &Appearance, at: usize) -> Option<bool> {
let fill = ap.items.get(at)?.is_fill();
+112 -17
View File
@@ -14,13 +14,14 @@
//! the document's Spot Colors option says. Pasting back into the document the objects came from
//! uses its resources as they are now.
use std::cell::OnceCell;
use std::cell::{Cell, OnceCell};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_brush::Brush;
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_doc::pattern::pattern_paint;
use vectorcraft_doc::text::{KINSOKU_NAME_MAX, KINSOKU_SETS_MAX};
use vectorcraft_doc::{
Appearance, AppearanceItem, Document, Effect, GraphDesign, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol,
@@ -610,6 +611,9 @@ pub(crate) enum SwatchChoice {
pub(crate) struct SwatchChoices {
all: SwatchChoice,
by_name: BTreeMap<String, SwatchChoice>,
/// Names a swatch or pattern that comes in under a numbered name skips, each with the swatch
/// it is reserved for, which still comes in under it when the document does not use it.
reserved: Arc<BTreeMap<String, Swatch>>,
}
impl SwatchChoices {
@@ -621,16 +625,22 @@ impl SwatchChoices {
};
match p.get("swatchConflict") {
None | Some(Value::Null) => Ok(Self::default()),
Some(Value::Object(m)) => {
Ok(Self { all: SwatchChoice::Merge, by_name: m.iter().map(|(k, v)| Ok((k.clone(), one(v)?))).collect::<Result<_>>()? })
}
Some(v) => Ok(Self { all: one(v)?, by_name: BTreeMap::new() }),
Some(Value::Object(m)) => Ok(Self {
all: SwatchChoice::Merge,
by_name: m.iter().map(|(k, v)| Ok((k.clone(), one(v)?))).collect::<Result<_>>()?,
reserved: Arc::default(),
}),
Some(v) => Ok(Self { all: one(v)?, ..Self::default() }),
}
}
/// Add for every conflict: each pasted swatch whose name the document gives another color
/// comes in renamed.
pub(crate) fn add_all() -> Self {
Self { all: SwatchChoice::Add, by_name: BTreeMap::new() }
Self { all: SwatchChoice::Add, ..Self::default() }
}
/// These choices, with numbered names skipping the names of `names` ([`SwatchChoices::reserved`]).
pub(crate) fn reserving(self, names: &Arc<BTreeMap<String, Swatch>>) -> Self {
Self { reserved: Arc::clone(names), ..self }
}
fn of(&self, name: &str) -> SwatchChoice {
self.by_name.get(name).copied().unwrap_or(self.all)
@@ -1154,6 +1164,9 @@ pub(crate) struct Imported {
pub added_designs: BTreeSet<String>,
/// The global and spot colors that took the document's color (merged).
merged_swatches: BTreeSet<String>,
/// Whether a name [`SwatchChoices::reserving`] reserves changed the name a swatch or pattern
/// came in under.
pub reserved_named: bool,
}
impl Imported {
@@ -1425,9 +1438,39 @@ impl Clipboard {
let bare = |p: &PatternDef| PatternDef { name: String::new(), art: vec![], ..p.clone() };
let same = |n: &str| !fresh && d.pattern(n).is_some_and(|x| bare(x) == bare(def) && same_art(&out.relink, &x.art, &def.art));
let p = existing(&def.name, d.patterns.iter().map(|p| p.name.as_str()), same_doc, same).unwrap_or_else(|| {
// Its swatch comes along under the same name.
let name = unique_name(&def.name, |n| d.pattern(n).is_some() || d.swatch_name_taken(n));
// Its swatch comes along under the same name, which skips the reserved swatch
// names too, except its own name when that is reserved for a swatch of it.
let skipped = Cell::new(false);
let ours = |w: &Swatch| matches!(&w.paint, Paint::Pattern { pattern, .. } if *pattern == def.name);
let name = unique_name(&def.name, |n| {
let used = d.pattern(n).is_some() || d.swatch_name_taken(n);
let held = !used && choices.reserved.get(n).is_some_and(|w| n != def.name || !ours(w));
skipped.set(skipped.get() || held);
used || held
});
out.reserved_named |= skipped.get();
add_pattern(d, PatternDef { name: name.clone(), ..def.clone() });
// The name is left to a swatch it is reserved for that places the pattern
// otherwise; the swatch the pattern comes with gets another.
let placed = choices.reserved.get(&name).is_some_and(|w| ours(w) && w.paint != pattern_paint(&def.name));
if placed && d.swatches.last().is_some_and(|w| w.name == name) {
let other = unique_name(&name, |n| n == name || d.swatch_name_taken(n) || choices.reserved.contains_key(n));
if let Some(w) = d.swatches.last_mut() {
w.name = other;
}
}
// A pattern that comes in under another name than the one reserved for its
// swatch, because a pattern has that name, keeps that name for its swatch
// when no swatch or color group uses it.
let own = name != def.name
&& !d.swatch_name_taken(&def.name)
&& choices.reserved.get(&def.name).is_some_and(|w| w.paint == pattern_paint(&def.name));
if own && d.swatches.last().is_some_and(|w| w.name == name) {
if let Some(w) = d.swatches.last_mut() {
w.name = def.name.clone();
}
out.reserved_named = true;
}
Placed::added(&def.name, name)
});
added_patterns.extend(p.new_name(&def.name));
@@ -1660,7 +1703,9 @@ impl Clipboard {
out.merged_swatches.insert(w.name.clone());
Placed::Existing
} else {
add_swatch(d, w, same_doc)
let (p, reserved_named) = add_swatch(d, w, w, same_doc, &choices.reserved, &out.relink);
out.reserved_named |= reserved_named;
p
};
out.placed(Res::Swatch, &w.name, &p);
}
@@ -1675,7 +1720,8 @@ impl Clipboard {
for def in self.swatches.iter().filter(|w| !is_base(w) && used.carries(w)) {
let mut w = def.clone();
out.relink.paint(&mut w.paint);
let p = add_swatch(d, &w, same_doc);
let (p, reserved_named) = add_swatch(d, &w, def, same_doc, &choices.reserved, &out.relink);
out.reserved_named |= reserved_named;
out.placed(Res::Swatch, &def.name, &p);
}
}
@@ -1877,13 +1923,62 @@ pub(crate) fn import_graph_designs(src: &Document, d: &mut Document, names: &[St
clip.import_used(d, &used, &SwatchChoices::default(), false)
}
/// Whether `name` ends in a space and a number, as a numbered copy's name ("Ink 2") does.
pub(crate) fn numbered_name(name: &str) -> bool {
name.rsplit_once(' ').is_some_and(|(_, k)| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit()))
}
/// 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 {
/// share one namespace) → where it went, and whether `reserved` changed its name. `source` is the
/// pasted swatch `w` stands for, before its links were relinked. A numbered name skips the names
/// in `reserved`. A numbered name in `reserved` ("Ink 2") that `d` does not use is kept for the
/// swatch it is reserved for: that swatch comes in under it, not as a numbered copy of it that `d`
/// has, and another swatch of that name gets a number. A numbered copy in `d` whose name is
/// reserved for another swatch, and that is that swatch with its links as `relink` gives them, is
/// left to it, whether or not the import brings that swatch.
fn add_swatch(d: &mut Document, w: &Swatch, source: &Swatch, same_doc: bool, reserved: &BTreeMap<String, Swatch>, relink: &Relink) -> (Placed, bool) {
let same = |n: &str| d.swatch(n).is_some_and(|t| *t == Swatch { name: n.to_string(), ..w.clone() });
existing(&w.name, d.swatches_iter().map(|t| t.name.as_str()), same_doc, same).unwrap_or_else(|| {
let name = d.free_swatch_name(&w.name);
d.swatches.push(Swatch { name: name.clone(), ..w.clone() });
Placed::added(&w.name, name)
})
let kept = (!same_doc && numbered_name(&w.name) && !d.swatch_name_taken(&w.name)).then(|| reserved.get(&w.name)).flatten();
let (owns, held) = (kept.is_some_and(|o| o == source), kept.is_some_and(|o| o != source));
let is_owner = |t: &Swatch, o: &Swatch| {
let mut o = o.clone();
relink.paint(&mut o.paint);
*t == o
};
let theirs =
|n: &str| n != w.name && copy_of(&w.name, n) && reserved.get(n).is_some_and(|o| o != source && d.swatch(n).is_some_and(|t| is_owner(t, o)));
let names = || d.swatches_iter().map(|t| t.name.as_str());
let excluded = Cell::new(false);
let found = existing(
&w.name,
names().filter(|n| {
let t = theirs(n);
excluded.set(excluded.get() || t);
!t
}),
same_doc,
same,
);
let reused = |p: &Option<Placed>| match p {
Some(Placed::Reused(n)) => Some(n.clone()),
_ => None,
};
let passed_over = excluded.get() && reused(&found) != reused(&existing(&w.name, names(), same_doc, same));
let over_copy = match found {
Some(p) if !owns => return (p, passed_over),
found => found.is_some(),
};
let mut skipped = held;
let name = if d.swatch_name_taken(&w.name) || held {
let mut free = |n: &String| {
let taken = d.swatch_name_taken(n);
skipped |= !taken && reserved.contains_key(n);
!taken && !reserved.contains_key(n)
};
(2..).map(|i| format!("{} {i}", w.name)).find(&mut free).unwrap_or_else(|| d.free_swatch_name(&w.name))
} else {
w.name.clone()
};
d.swatches.push(Swatch { name: name.clone(), ..w.clone() });
(Placed::added(&w.name, name), over_copy || skipped || passed_over)
}
+273 -17
View File
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Info",
["Window", "Document Info"],
None,
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file, format, effectivePpi, memoryBytes, storedBytes}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one; format: a linked image's file format by its extension, else the format of the pixels the document holds, null when unknown; effectivePpi: [x, y] pixels per inch at the size it is placed at, a distorted image measured at its middle, null when it has no area; memoryBytes: for an embedded image width × height × 4, the bytes of the 8-bit RGBA pixels it is drawn from, else null; storedBytes: for an embedded image the bytes of the encoded image the document holds, else null; a Linked Images row gives the format, the size, the resolution and the file (`PNG; 1200 × 800 px; 150 ppi — /art/photo.png`), an Embedded Images row the format, the size and the memory (`PNG; 1200 × 800 px; estimated memory 3.7 MiB`)), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freef Line truncated
has_doc,
info
),
@@ -183,8 +183,126 @@ fn count_fonts(fonts: &mut BTreeMap<super::fonts::UsedFont, usize>, t: &vectorcr
}
}
/// An image object as Document Info lists it: (name, width, height, linked file).
type ImageRow = (String, u32, u32, Option<String>);
/// An image object as Linked Images or Embedded Images lists it.
struct ImageRow {
name: String,
width: u32,
height: u32,
/// What a linked image's row names: its file's path, or the file's name alone when the request
/// may not read it. `None` for an embedded image.
file: Option<String>,
/// The image's format ([`image_format`]); `None` when it is not known.
format: Option<&'static str>,
/// The pixels per inch across and down at the size the image is placed at; `None` when its
/// transform flattens it.
ppi: Option<[f64; 2]>,
/// For an embedded image, the bytes its pixels take when drawn (8-bit RGBA: width × height × 4).
memory: Option<u64>,
/// For an embedded image, the bytes of the encoded image the document holds.
stored: Option<u64>,
}
impl ImageRow {
/// Image object `n` (image `im`) of `d`, `file` the row value of its link.
fn of(d: &Document, n: &Node, im: &vectorcraft_doc::ImageObject, file: Option<String>) -> Self {
let name = im.link.as_ref().map_or_else(|| n.display_name(), |l| l.name().to_string());
// A distorted image is measured at its middle, as `image.info` measures it.
let xf = vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf);
let ppi = super::place::effective_ppi(xf);
// An image with no pixels across or down has no area, and so does one whose transform lays
// both pixel axes on one line. The determinant is compared with the product of the two
// axes' lengths, at any scale.
let [xx, xy, yx, yy, ..] = xf.as_coeffs();
let has_area = im.width > 0 && im.height > 0 && xf.determinant().abs() > 1e-9 * xx.hypot(xy) * yx.hypot(yy);
let embedded = im.link.is_none();
let memory = || u64::from(im.width).checked_mul(u64::from(im.height))?.checked_mul(4);
Self {
name,
width: im.width,
height: im.height,
file,
format: image_format(d, im),
ppi: (has_area && ppi.iter().all(|v| *v > 0.0 && v.is_finite())).then_some(ppi),
memory: if embedded { memory() } else { None },
stored: if embedded { d.images.get(&im.key).map(|b| b.bytes.len() as u64) } else { None },
}
}
/// The row's value: the format, the size in pixels, and for a linked image its resolution and
/// file, for an embedded one the memory its pixels take.
fn value(&self) -> String {
let format = self.format.unwrap_or("Unknown format");
let size = format!("{} × {} px", self.width, self.height);
match &self.file {
Some(file) => {
let ppi = match self.ppi {
Some([x, y]) if ppi_number(x) == ppi_number(y) => format!("{} ppi", ppi_number(x)),
Some([x, y]) => format!("{} × {} ppi", ppi_number(x), ppi_number(y)),
None => "resolution unavailable".into(),
};
format!("{format}; {size}; {ppi} — {file}")
}
None => {
let memory = self.memory.map_or_else(|| "memory unavailable".to_string(), |b| format!("estimated memory {}", byte_size(b)));
format!("{format}; {size}; {memory}")
}
}
}
/// The row's `imageObjects` entry.
fn entry(&self) -> Value {
json!({
"name": self.name,
"width": self.width,
"height": self.height,
"linked": self.file.is_some(),
"file": self.file,
"format": self.format,
"effectivePpi": self.ppi,
"memoryBytes": self.memory,
"storedBytes": self.stored,
})
}
}
/// The format of image `im` of `d`, as the Links panel names it: for a linked image its file's, by
/// its extension (DCS for a separated one), else the type of the pixels the document holds for it;
/// `None` when neither names a known format.
fn image_format(d: &Document, im: &vectorcraft_doc::ImageObject) -> Option<&'static str> {
use super::fileio;
if im.link.is_some() && d.images.get(&im.key).is_some_and(vectorcraft_doc::ImageBlob::is_separated) {
return Some("DCS");
}
im.link
.as_ref()
.and_then(|l| fileio::format_for_name(l.name()).or_else(|| fileio::readable_format_for_name(l.name())))
.or_else(|| d.images.get(&im.key).and_then(|b| fileio::FORMATS.iter().find(|f| f.raster && f.mime == b.mime)))
.map(|f| f.label)
}
/// A resolution as Document Info shows it: rounded to a tenth (below 1, to a hundredth), without a
/// trailing `.0`.
pub fn ppi_number(ppi: f64) -> String {
let k = if ppi.abs() < 1.0 { 100.0 } else { 10.0 };
format!("{}", (ppi * k).round() / k)
}
/// A number of bytes as Document Info shows it: in B below 1 KiB, else in KiB, MiB or GiB rounded
/// to a tenth.
pub fn byte_size(bytes: u64) -> String {
const UNITS: [&str; 3] = ["KiB", "MiB", "GiB"];
if bytes < 1024 {
return format!("{bytes} B");
}
let mut v = bytes as f64 / 1024.0;
let mut unit = 0;
// 1023.96 KiB is shown as 1 MiB rather than as 1024 KiB.
while v >= 1023.95 && unit + 1 < UNITS.len() {
v /= 1024.0;
unit += 1;
}
format!("{} {}", (v * 10.0).round() / 10.0, UNITS[unit])
}
/// A Repeat object as Document Info lists it: its `repeatObjects` entry, and its row, which gives
/// its name and then its kind with the number of instances it draws (for a grid, its rows and
@@ -337,11 +455,9 @@ fn sections(
"symbols" => names("symbols"),
"fonts" => fonts.to_vec(),
"fontDetails" => font_details.to_vec(),
"linkedImages" => {
images.iter().filter_map(|(name, w, h, link)| Some((name.clone(), format!("{w} × {h} px — {}", link.as_ref()?)))).collect()
}
"linkedImages" => images.iter().filter(|i| i.file.is_some()).map(|i| (i.name.clone(), i.value())).collect(),
"repeats" => repeats.to_vec(),
_ => images.iter().filter(|i| i.3.is_none()).map(|(name, w, h, _)| (name.clone(), format!("{w} × {h} px"))).collect(),
_ => images.iter().filter(|i| i.file.is_none()).map(|i| (i.name.clone(), i.value())).collect(),
};
Section { id, title, rows }
})
@@ -753,8 +869,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
im.key.clone(),
json!({ "width": im.width, "height": im.height, "linked": im.link.is_some(), "link": link.and_then(|(l, ok)| ok.then_some(&l.path)) }),
);
let name = im.link.as_ref().map_or_else(|| n.display_name(), |l| l.name().to_string());
image_rows.push((name, im.width, im.height, link.map(|(l, ok)| if ok { l.path.clone() } else { l.name().to_string() })));
let file = link.map(|(l, ok)| if ok { l.path.clone() } else { l.name().to_string() });
image_rows.push(ImageRow::of(d, n, im, file));
Some("images")
}
NodeKind::SymbolInstance { symbol, .. } => {
@@ -835,13 +951,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
let font_names: Vec<String> = fonts.keys().map(super::fonts::font_label).collect();
let (font_uses, font_use_rows): (Vec<Value>, Vec<(String, String)>) = fonts.iter().map(|(f, n)| font_use(f, *n)).unzip();
let (font_entries, font_rows): (Vec<Value>, Vec<(String, String)>) = fonts.keys().map(font_detail).unzip();
// The image objects in walk order, as Linked Images and Embedded Images list them: `file` is a
// linked image's row value (its path, or its file name alone when the request may not read it),
// and null for an embedded one.
let image_objects: Vec<Value> = image_rows
.iter()
.map(|(name, w, h, file)| json!({ "name": name, "width": w, "height": h, "linked": file.is_some(), "file": file }))
.collect();
// The image objects in walk order, as Linked Images and Embedded Images list them.
let image_objects: Vec<Value> = image_rows.iter().map(ImageRow::entry).collect();
// Each brush the art uses with its type, found by name in the Brushes panel as the renderer finds it (the first of two
// brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type. A row names the type
// as the New Brush dialog does (`Art Brush`), and the panel translates these values when it shows them.
@@ -2246,11 +2357,156 @@ mod tests {
assert_eq!(objects.len(), 2, "{objects:?}");
for (o, r) in objects.iter().zip(&embedded) {
assert_eq!((o["linked"].clone(), o["file"].clone(), o["name"].clone()), (json!(false), Value::Null, r[0].clone()), "{o}");
assert_eq!(r[1], format!("{} × {} px", o["width"], o["height"]));
let memory = byte_size(o["memoryBytes"].as_u64().unwrap());
assert_eq!(r[1], format!("{}; {} × {} px; estimated memory {memory}", o["format"].as_str().unwrap(), o["width"], o["height"]));
}
assert!(section("linkedImages").is_empty());
}
/// An image object to place: (key, MIME type, linked path, width, height, transform).
type Placed<'a> = (&'a str, &'a str, Option<&'a str>, u32, u32, Affine);
/// Image objects `images` placed in a new document, with a blob of `100 + n` bytes of type
/// `mime` for each new key; their ids in order.
fn images_in(s: &mut Session, images: &[Placed]) -> Vec<NodeId> {
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.edit("Place", |d, _| {
let mut ids = vec![];
for (n, (key, mime, link, width, height, xf)) in images.iter().enumerate() {
if !d.images.contains_key(*key) {
d.images.insert((*key).into(), vectorcraft_doc::ImageBlob::new(*mime, vec![0; 100 + n]));
}
let id = d.alloc_id();
let im = vectorcraft_doc::ImageObject {
key: (*key).into(),
width: *width,
height: *height,
xf: *xf,
link: link.map(vectorcraft_doc::LinkInfo::new),
placement: Default::default(),
pixels: None,
};
d.insert(d.default_layer(), usize::MAX, Node::new(id, NodeKind::Image(Box::new(im))))?;
ids.push(id);
}
Ok(ids)
})
.unwrap()
}
/// Linked Images gives each linked image's format, size in pixels, resolution at the size it is
/// placed at and file, and Embedded Images each embedded image's format, size and the memory
/// its pixels take; `imageObjects` gives the same facts with the bytes the document holds for an
/// embedded image, the text report writes the same rows, and Selection Only lists the selected
/// images alone.
#[test]
fn image_rows_give_format_resolution_and_memory() {
let mut s = Session::new();
let half = Affine::scale(0.5);
let ids = images_in(
&mut s,
&[
("a", "image/png", None, 1200, 800, half),
("b", "image/jpeg", None, 10, 10, half),
("c", "image/x-unheard-of", None, 3, 2, half),
("a", "image/png", Some("/art/photo.png"), 1200, 800, Affine::scale(0.48)),
("a", "image/png", Some("/art/photo.png"), 1200, 800, Affine::scale(0.24)),
("a", "image/png", Some("/art/wide.png"), 1200, 800, Affine::scale_non_uniform(0.5, 1.0)),
("a", "image/png", Some("/art/scan.tif"), 1200, 800, half),
("a", "image/png", Some("/art/flat.png"), 1200, 800, Affine::scale_non_uniform(0.5, 0.0)),
// Both pixel axes on one line: neither has length 0, but the image has no area.
("a", "image/png", Some("/art/line.png"), 1200, 800, Affine::new([0.5, 0.5, 1.0, 1.0, 0.0, 0.0])),
("c", "image/x-unheard-of", Some("/art/odd.qqq"), 3, 2, half),
],
);
let i = s.execute("document.info", &json!({})).unwrap();
let rows = |i: &Value, id: &str| -> Vec<(String, String)> {
let section = i["sections"].as_array().unwrap().iter().find(|s| s["id"] == id).unwrap().clone();
section["rows"].as_array().unwrap().iter().map(|r| (r[0].as_str().unwrap().into(), r[1].as_str().unwrap().into())).collect()
};
let embedded = rows(&i, "embeddedImages");
let values: Vec<&str> = embedded.iter().map(|(_, v)| v.as_str()).collect();
assert_eq!(
values,
[
"PNG; 1200 × 800 px; estimated memory 3.7 MiB",
"JPEG; 10 × 10 px; estimated memory 400 B",
"Unknown format; 3 × 2 px; estimated memory 24 B"
]
);
let linked = rows(&i, "linkedImages");
assert_eq!(
linked,
[
("photo.png", "PNG; 1200 × 800 px; 150 ppi — /art/photo.png"),
("photo.png", "PNG; 1200 × 800 px; 300 ppi — /art/photo.png"),
("wide.png", "PNG; 1200 × 800 px; 144 × 72 ppi — /art/wide.png"),
("scan.tif", "TIFF; 1200 × 800 px; 144 ppi — /art/scan.tif"),
("flat.png", "PNG; 1200 × 800 px; resolution unavailable — /art/flat.png"),
("line.png", "PNG; 1200 × 800 px; resolution unavailable — /art/line.png"),
("odd.qqq", "Unknown format; 3 × 2 px; 144 ppi — /art/odd.qqq"),
]
.map(|(a, b)| (a.to_string(), b.to_string()))
);
let objects = i["imageObjects"].as_array().unwrap();
assert_eq!(objects.len(), 10);
assert_eq!(
(objects[0]["format"].clone(), objects[0]["effectivePpi"].clone(), objects[0]["memoryBytes"].clone(), objects[0]["storedBytes"].clone()),
(json!("PNG"), json!([144.0, 144.0]), json!(1200 * 800 * 4), json!(100))
);
assert_eq!((objects[1]["format"].clone(), objects[1]["storedBytes"].clone()), (json!("JPEG"), json!(101)));
assert_eq!(objects[2]["format"], Value::Null);
// A linked image gives no memory and no stored bytes: the document holds only its preview.
assert_eq!((objects[3]["memoryBytes"].clone(), objects[3]["storedBytes"].clone()), (Value::Null, Value::Null));
let ppi = |o: &Value| -> Vec<f64> { o["effectivePpi"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect() };
assert!(ppi(&objects[3]).iter().all(|v| (v - 150.0).abs() < 1e-9), "{}", objects[3]);
assert_eq!(ppi(&objects[5]), [144.0, 72.0]);
assert_eq!((objects[7]["effectivePpi"].clone(), objects[8]["effectivePpi"].clone()), (Value::Null, Value::Null));
let text = s.execute("document.info", &json!({"format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
assert!(text.contains("\nphoto.png: PNG; 1200 × 800 px; 150 ppi — /art/photo.png\n"), "{text}");
assert!(text.contains(": JPEG; 10 × 10 px; estimated memory 400 B\n"), "{text}");
// Selection Only lists the selected images alone, with the same rows.
s.execute("select.set", &json!({"ids": [ids[1].0, ids[5].0]})).unwrap();
let selected = s.execute("document.info", &json!({"selectionOnly": true})).unwrap();
assert_eq!(rows(&selected, "embeddedImages").iter().map(|(_, v)| v.as_str()).collect::<Vec<_>>(), [values[1]]);
assert_eq!(rows(&selected, "linkedImages"), [linked[2].clone()]);
}
/// An image placed at a very small size still has an area, so its row gives a resolution.
#[test]
fn a_tiny_placement_still_gives_a_resolution() {
let mut s = Session::new();
images_in(&mut s, &[("a", "image/png", Some("/art/huge.png"), 100_000, 100_000, Affine::scale(1e-7))]);
let i = s.execute("document.info", &json!({})).unwrap();
let ppi = i["imageObjects"][0]["effectivePpi"].as_array().map(|v| v.iter().map(|v| v.as_f64().unwrap_or(0.0)).collect::<Vec<_>>());
let ppi = ppi.unwrap_or_default();
assert!(ppi.len() == 2 && ppi.iter().all(|v| (v / 7.2e8 - 1.0).abs() < 1e-9), "{}", i["imageObjects"][0]);
}
/// An image with no pixels across or down has no area, so its row gives no resolution whatever
/// its transform.
#[test]
fn a_zero_pixel_image_has_no_resolution() {
let mut s = Session::new();
let half = Affine::scale(0.5);
images_in(&mut s, &[("a", "image/png", Some("/art/none.png"), 0, 800, half), ("a", "image/png", Some("/art/flat.png"), 1200, 0, half)]);
let i = s.execute("document.info", &json!({})).unwrap();
let objects = i["imageObjects"].as_array().cloned().unwrap_or_default();
assert_eq!(objects.iter().map(|o| o["effectivePpi"].clone()).collect::<Vec<_>>(), [Value::Null, Value::Null], "{objects:?}");
let text = s.execute("document.info", &json!({"format": "text"})).unwrap()["text"].as_str().unwrap_or_default().to_string();
assert!(text.contains("none.png: PNG; 0 × 800 px; resolution unavailable — /art/none.png\n"), "{text}");
assert!(text.contains("flat.png: PNG; 1200 × 0 px; resolution unavailable — /art/flat.png\n"), "{text}");
}
/// A number of bytes reads in B below 1 KiB, else in KiB, MiB or GiB to a tenth, and a
/// resolution to a tenth without a trailing `.0`.
#[test]
fn byte_sizes_and_resolutions_read_to_a_tenth() {
let shown = [0, 1023, 1024, 1536, 1024 * 1024 - 1, 3_840_000, 5 << 30, u64::MAX].map(byte_size);
assert_eq!(shown, ["0 B", "1023 B", "1 KiB", "1.5 KiB", "1 MiB", "3.7 MiB", "5 GiB", "17179869184 GiB"]);
assert_eq!([150.0, 72.0 / 0.48, 205.714, 0.04, 0.001].map(ppi_number), ["150", "150", "205.7", "0.04", "0"]);
}
/// A `gradientObjects` entry's `kinds` gives the kind of each gradient listed by its kind
/// rather than by a swatch, and null for a swatch's name, even one that reads like a kind and
/// one an object's gradient of that kind shares; a type object's characters count as its own.
+1
View File
@@ -31,6 +31,7 @@ mod freehand;
mod quickpen;
mod smooth;
pub(super) use anchors::{following_anchors, remove_anchors_of};
pub use commands::specs;
pub(super) use common::{center_strokes, ids_json, replace_with_pieces, usize_opt};
pub(super) use cut::{components, erase_outline};
+2 -2
View File
@@ -166,7 +166,7 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result<Value> {
/// end. Indexes are those after the removal, without the subpaths left with fewer than two anchors.
/// `removed` is in ascending order without repeats, as a selection holds it, and each subpath reads
/// only its own pairs.
fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> {
pub(in crate::cmd) fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTreeSet<(usize, usize)> {
let mut next = BTreeSet::new();
let mut kept = 0;
let mut rest = removed;
@@ -202,7 +202,7 @@ fn following_anchors(shape: &[(usize, bool)], removed: &[(usize, usize)]) -> BTr
/// ([`vectorcraft_tools::draw2::curvature_remove`]). A subpath left with one anchor is removed,
/// and a path left with no subpath is removed through `emptied`; the caller then takes it out of
/// the selection. True when the path went.
fn remove_anchors_of(
pub(in crate::cmd) fn remove_anchors_of(
d: &mut Document,
sel: &mut Selection,
emptied: &mut Beside,
+10 -1
View File
@@ -1,7 +1,7 @@
use super::anchors::{convert_anchor, curvature, curvature_edit, remove_anchor, remove_anchors, reshape_segment};
use super::cut::{erase_region, erase_segments, knife, split};
use super::freehand::{blob, freehand};
use super::quickpen::quick_pen;
use super::quickpen::{quick_pen, quick_pen_length};
use super::smooth::{join_scrub, smooth_region};
use super::{CommandSpec, cmd, has_anchors, has_doc, has_selection};
@@ -43,6 +43,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
quick_pen
),
cmd!(
"path.quickPenLength",
"Quick Pen",
[],
None,
"{id, subpath?: index (0), end?: \"end\" (default)|\"start\", length: pt} make the line or arc at that end of the open subpath `length` long, as dragging the Quick Pen tool's length handle does: a line keeps its other point and its direction; an arc (the segments before the end that lie on one circle and turn the same way) keeps its other point, its circle and the way it turns, with a sweep of at most 359°. length runs from 0.001 to 1000000 pt for a line, and to 359° of the circle for an arc. A length the piece already has changes nothing; otherwise the path is selected, as one undo step → {id, kind: \"line\"|\"arc\", length}. An end that is neither straight nor a circular arc, a closed subpath, a locked or hidden path, a length outside the range and a result that would reach past the canvas are errors",
has_doc,
quick_pen_length
),
cmd!(
"path.removeAnchor",
"Delete Anchor Point",
+59 -1
View File
@@ -1,9 +1,12 @@
//! The Quick Pen tool's command (`path.quickPen`): a path of straight lines and circular arcs.
//! The Quick Pen tool's commands: `path.quickPen` draws a path of straight lines and circular arcs,
//! and `path.quickPenLength` makes the line or arc at an end of a path longer or shorter.
use vectorcraft_tools::quickpen::length as qpl;
use vectorcraft_tools::quickpen::{self as qp, Piece, Stroke};
use super::common::{path_kind, path_mut, point_entry, usize_opt, within_input_bound};
use super::{Color, Paint, PathData, Result, Session, SubPath, Value, add_look, bad, json, number_or, object_param, switch_or};
use crate::cmd::f64_req;
const C: &str = "path.quickPen";
/// The most pieces one request takes.
@@ -94,3 +97,58 @@ pub(super) fn quick_pen(s: &mut Session, p: &Value) -> Result<Value> {
})?;
Ok(json!({ "id": id.0 }))
}
const L: &str = "path.quickPenLength";
/// `path.quickPenLength`: the line or arc at an end of an open subpath made `length` long.
pub(super) fn quick_pen_length(s: &mut Session, p: &Value) -> Result<Value> {
let Some(id) = object_param(p, "id", L)? else { return Err(bad(L, "missing `id`")) };
let si = usize_opt(p, "subpath", L)?.unwrap_or(0);
let at_start = match p.get("end") {
None | Some(Value::Null) => false,
Some(v) => match v.as_str() {
Some("end") => false,
Some("start") => true,
_ => {
let key = "end";
return Err(bad(L, format!("`{key}` must be one of {}", ["start", "end"].join(", "))));
}
},
};
let length = f64_req(p, "length", L)?;
let d = &s.doc()?.doc;
let path = d.node(id).and_then(|n| n.path_data()).ok_or_else(|| bad(L, "`id` is not a path"))?;
if !d.is_editable(id) {
return Err(bad(L, "the path is locked or hidden"));
}
let sp = path.subpaths.get(si).ok_or_else(|| bad(L, "no such subpath"))?;
if sp.closed {
return Err(bad(L, "the subpath is closed"));
}
let piece = qpl::end_piece(sp, at_start).ok_or_else(|| bad(L, "the end is not a straight line or a circular arc"))?;
let (key, lo, hi) = ("length", qpl::MIN_LENGTH, piece.max_length());
if !(lo..=hi).contains(&length) {
// An arc's limit, 359° of its circle, is given to the thousandth of a point, rounded down.
let hi = (hi * 1000.0).floor() / 1000.0;
return Err(bad(L, format!("`{key}` must be from {lo} to {hi}")));
}
let out = qpl::with_length(sp, at_start, length).ok_or_else(|| bad(L, "the end is not a straight line or a circular arc"))?;
if !qp::on_canvas(&out) {
return Err(bad(L, "result would exceed the canvas (coordinates out of range)"));
}
let kind = match piece.shape {
qpl::EndShape::Line => "line",
qpl::EndShape::Arc { .. } => "arc",
};
if (length - piece.length).abs() <= 1e-9 * length.max(1.0) {
return Ok(json!({ "id": id.0, "kind": kind, "length": piece.length }));
}
let top = super::super::path::compound_or_self(d, id);
s.edit("Quick Pen", |d, sel| {
let slot = path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| crate::EngineError::Other("no such subpath".into()))?;
*slot = out;
sel.set([top]);
Ok(())
})?;
Ok(json!({ "id": id.0, "kind": kind, "length": length }))
}
+15 -2
View File
@@ -225,7 +225,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Clear",
["Edit"],
Some("Delete"),
"{ids?, guides?: bool (with ids: also delete the selected ruler guides)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too); without ids, refused while an object of a symbol instance's art is selected",
"{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too); without ids, refused while an object of a symbol instance's art is selected",
has_selection_or_guides,
clear
),
@@ -1221,6 +1221,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
let guides = switch_or(p, "guides", false, "edit.clear")?;
switch_or(p, "keepJoined", false, "edit.clear")?;
let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None };
// An object of a symbol instance's art can't be removed from the instance alone.
if explicit.is_none() && s.doc()?.selection.symbol_part.is_some() {
@@ -1228,7 +1229,8 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
}
// Direct-selected anchors or segments: remove those, and any objects selected whole with them.
if explicit.is_none() && (!s.doc()?.selection.anchors.is_empty() || !s.doc()?.selection.segments.is_empty()) {
return super::path::delete_anchors(s, p);
let keep_joined = keeps_paths_joined(s, p)?;
return super::path::delete_anchors_joined(s, p, keep_joined);
}
// Selected ruler guides (selected on their own).
if explicit.is_none() && s.doc()?.selection.is_empty() {
@@ -1275,6 +1277,17 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
ok()
}
/// Does Clear remove direct-selected anchors without opening their paths (`keepJoined` param, else
/// General › Delete Removes Anchor Points and Keeps Paths Joined)? Noted in the journal, so a
/// replay removes them the same way whatever the preference is at the time. A saved step without `keepJoined`
/// was recorded before the preference existed, so it opens the paths as it did then.
fn keeps_paths_joined(s: &mut Session, p: &Value) -> Result<bool> {
let default = s.prefs.delete_keeps_paths_joined && !s.replaying();
let on = switch_or(p, "keepJoined", default, "edit.clear")?;
s.note_journal("keepJoined", json!(on));
Ok(on)
}
/// Document ids scope node ids: two tabs may contain objects with the same node id.
fn drop_selection(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "edit.dropSelection";
+1 -1
View File
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export PDF",
[],
None,
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in Line truncated
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in Line truncated
has_doc,
export_pdf
),
+81
View File
@@ -333,6 +333,66 @@ fn an_item_opacity_on_a_series_mark_survives_regeneration() {
assert_eq!((kept.fill_opacity, kept.stroke_opacity), (Some(0.4), None));
}
/// `paint.setFill {opacity}` and `paint.setStroke {opacity}` on one series mark are kept by the graph as the transparency
/// commands' item opacity is: every path of that series has them after the graph is drawn again.
#[test]
fn a_paint_opacity_on_a_series_mark_survives_regeneration() {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
let id = graph(&mut s, "column");
let bar = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id;
s.execute("paint.setFill", &json!({"ids": [bar.0], "opacity": 40})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [bar.0], "color": "#ff0000", "opacity": 60})).unwrap();
let kept = spec(&s, id).series_paints[0].clone();
assert_eq!((kept.fill_opacity, kept.stroke_opacity), (Some(0.4), Some(0.6)));
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let marks = series(&n, 0).children().unwrap().to_vec();
let opacities: Vec<(f32, f32)> = marks.iter().map(|m| (m.appearance.fill().unwrap().opacity, m.appearance.stroke().unwrap().opacity)).collect();
assert!(opacities.iter().all(|o| *o == (0.4, 0.6)), "{opacities:?}");
}
/// `paint.setFill {opacity}` and `paint.setStroke {opacity}` with the opacity a mark already shows replace the opacity
/// another mark of the series left on the graph, as an explicit 100% does.
#[test]
fn a_paint_opacity_a_series_mark_already_shows_replaces_the_kept_opacity() {
let (mut s, id, _, marks) = column_marks();
s.execute("paint.setFill", &json!({"ids": [marks[0].0], "opacity": 40})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [marks[0].0], "opacity": 60})).unwrap();
let kept = spec(&s, id).series_paints[0].clone();
assert_eq!((kept.fill_opacity, kept.stroke_opacity), (Some(0.4), Some(0.6)));
// The second mark is opaque already: its row comes out as it was.
s.execute("paint.setFill", &json!({"ids": [marks[1].0], "color": "#ff0000", "opacity": 100})).unwrap();
let kept = spec(&s, id).series_paints[0].clone();
assert_eq!((kept.fill_opacity, kept.stroke_opacity), (None, Some(0.6)));
s.execute("paint.setStroke", &json!({"ids": [marks[1].0], "opacity": 100})).unwrap();
let kept = spec(&s, id).series_paints[0].clone();
assert_eq!((kept.fill_opacity, kept.stroke_opacity), (None, None));
s.execute("graph.setData", &json!({"rows": [[1, 2], [3, 4]]})).unwrap();
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
let opacities: Vec<(f32, f32)> =
series(&n, 0).children().unwrap().iter().map(|m| (m.appearance.fill().unwrap().opacity, m.appearance.stroke().unwrap().opacity)).collect();
assert!(opacities.iter().all(|o| *o == (1.0, 1.0)), "{opacities:?}");
}
/// The same for a graph's axis lines: a stroke opacity set on an opaque line replaces the one its kind keeps from another
/// line.
#[test]
fn a_stroke_opacity_an_axis_line_already_shows_replaces_the_kept_opacity() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let lines = line_nodes(&s, id);
s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "opacity": 40})).unwrap();
let kept = |s: &Session| spec(s, id).label_styles.axis_rows.and_then(|r| r.paint.stroke_opacity);
assert_eq!(kept(&s), Some(0.4));
s.execute("paint.setStroke", &json!({"ids": [lines[1].id.0], "opacity": 100})).unwrap();
assert_eq!(kept(&s), None);
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
let opacities: Vec<f32> = line_nodes(&s, id).iter().map(|n| n.appearance.stroke().map_or(1.0, |st| st.opacity)).collect();
assert!(opacities.iter().all(|o| *o == 1.0), "{opacities:?}");
}
/// Clear Appearance and Reduce to Basic Appearance on a series mark take its fill and stroke opacity away, and the
/// graph keeps none, so the series stays opaque when it is drawn again.
#[test]
@@ -1424,6 +1484,27 @@ fn paint_targets_leave_a_graph_designs_copy_out() {
assert_eq!(super::paint_targets(d, &[copy, art, mark]), [mark]);
}
/// The fill opacity the proxies show leaves out the art of a column or marker design in a series, which
/// `paint.setFill {opacity}` leaves out too: with only that art selected there is none, also with a row of the art
/// active, and with a mark selected after it the mark's.
#[test]
fn proxy_opacity_leaves_a_graph_designs_art_out() {
let (mut s, _, _, art, mark) = design_art();
let (mut m, _, marker_art) = marker_design_art();
for (s, art) in [(&mut s, art), (&mut m, marker_art)] {
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
assert_eq!(s.proxy_opacity(false), None);
assert!(s.execute("paint.setFill", &json!({"opacity": 50})).is_err());
let fill = top_row(s, art, true);
s.execute("appearance.setActiveItem", &json!({"index": fill})).unwrap();
assert_eq!(s.proxy_opacity(false), None, "with the art's fill row active");
assert!(s.execute("paint.setFill", &json!({"opacity": 50})).is_err());
}
s.execute("paint.setFill", &json!({"ids": [mark.0], "opacity": 40})).unwrap();
s.execute("select.set", &json!({"ids": [art.0, mark.0]})).unwrap();
assert!((s.proxy_opacity(false).unwrap() - 0.4).abs() < 1e-6, "the mark's fill opacity");
}
/// The art of a marker design in series 1 of a line graph: the design's copy and a path inside it.
fn marker_design_art() -> (Session, NodeId, NodeId) {
let mut s = Session::new();
+1 -1
View File
@@ -1360,7 +1360,7 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool, only: bool) -> Resul
// or spot color the pattern's art links to keeps the library's color, as Add to Swatches brings
// a library pattern's colors.
let current = s.doc()?.doc.clone();
let (choices, probe, imported) = super::patternlib::probe_import(&current, &doc, &name, &clip)?;
let (choices, probe, imported) = super::patternlib::probe_import(&current, &doc, &name, &clip, &Default::default())?;
drop(current);
let target = super::patternlib::imported_name(&imported, &name);
let paint = vectorcraft_doc::pattern::pattern_paint(&target);
+34 -18
View File
@@ -187,7 +187,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Rearrange All Artboards…",
["Object", "Artboards"],
None,
"{layout?: gridByRow|gridByColumn|row|column (gridByRow; byColumn?: true is gridByColumn), order?: leftToRight|rightToLeft (leftToRight: right-to-left mirrors the order along the rows), columns?: n (2; the rows for gridByColumn; row and column ignore it), spacing?: pt (20), moveArtwork?: true (each object of a layer or sublayer moves with the artboard its center is on; locked and hidden art, and art on a locked artboard, only with lockedAndHidden), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard), byColumn?: bool (an older way to ask for layout gridByColumn)} lay the artboards out in their order, the grid's top-left at the first artboard's; a locked artboard stays where it is → {artboards, rows, columns}",
"{layout?: gridByRow|gridByColumn|row|column (gridByRow; byColumn?: true is gridByColumn), order?: leftToRight|rightToLeft (leftToRight: right-to-left mirrors the order along the rows), columns?: n (2; the rows for gridByColumn; row and column ignore it), spacing?: pt (20), moveArtwork?: true (each object of a layer or sublayer moves with the artboard its center is on; locked and hidden art, and art on a locked artboard, only with lockedAndHidden), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), lockedAndHidden?: bool (default: prefs moveLockedWithArtboard), byColumn?: bool (an older way to ask for layout gridByColumn), indices?: [n] (lay out only these artboards, in document order; the others and their art and guides stay where they are), at?: [x, y] (the grid's top-left)} lay the artboards out in their order, the grid's top-left at `at`, else at the first artboard's laid out; a locked artboard stays where it is and keeps its place in the grid → {artboards, rows, columns; with indices also indices and moved, the count of artboards that moved}",
has_doc,
rearrange_artboards
),
@@ -1718,32 +1718,48 @@ fn rearrange_artboards(s: &mut Session, p: &Value) -> Result<Value> {
Some(_) => return Err(bad(CMD, "order must be leftToRight or rightToLeft")),
};
let count = s.doc()?.doc.artboards.len();
let n_ab = count.max(1);
// Columns of a grid by row, rows of a grid by column.
let lines = whole_or(p, "columns", 2, CMD)?.clamp(1, n_ab as u64) as usize;
let (rows, cols) = match layout {
L::GridByRow => (n_ab.div_ceil(lines), lines),
L::GridByColumn => (lines, n_ab.div_ceil(lines)),
L::Row => (1, n_ab),
L::Column => (n_ab, 1),
// `indices` lays out only those artboards, in document order; left out, every artboard.
let picked: Option<Vec<usize>> = match p.get("indices") {
Some(v) => Some(super::panelcmds::listed_artboards(&s.doc()?.doc, v, "indices", CMD)?),
None => None,
};
let at = match p.get("at") {
Some(v) => Some(super::finite_numbers::<2>(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(CMD, "`at` must be [x, y]"))?),
None => None,
};
// Columns of a grid by row, rows of a grid by column.
let lines = whole_or(p, "columns", 2, CMD)?;
check_numbers(p, &["spacing"], CMD)?;
let spacing = f64_or(p, "spacing", 20.0).clamp(-1.0e5, 1.0e5);
let move_art = switch_or(p, "moveArtwork", true, CMD)?;
check_switches(p, &["patterns"], CMD)?;
let locked_and_hidden = super::panelcmds::locked_and_hidden(s, p, move_art, CMD)?;
let d = &s.doc()?.doc;
let rects: Vec<Rect> = d.artboards.iter().map(|a| a.rect).collect();
let laid: Vec<usize> = picked.clone().unwrap_or_else(|| (0..count).collect());
let rects: Vec<Rect> = laid.iter().filter_map(|i| d.artboards.get(*i)).map(|a| a.rect).collect();
let sizes: Vec<(f64, f64)> = rects.iter().map(|r| (r.width(), r.height())).collect();
let first = rects.first().map_or(Point::ZERO, |r| r.origin());
let origins = super::newdoc::grid_origins_rc(&sizes, first, (rows, cols), spacing, layout == L::GridByColumn, rtl);
// A locked artboard stays where it is, and keeps its place in the grid.
let deltas: Vec<Vec2> =
rects.iter().zip(origins).zip(&d.artboards).map(|((r, o), a)| if a.locked { Vec2::ZERO } else { o - r.origin() }).collect();
// The grid's top-left: `at`, else the first artboard laid out's.
let origin = at.unwrap_or_else(|| rects.first().map_or(Point::ZERO, |r| r.origin()));
let (origins, rows, cols) = super::newdoc::rearrange_grid(&sizes, origin, layout, lines, spacing, rtl);
// A locked artboard stays where it is, and keeps its place in the grid; an artboard not laid
// out stays where it is.
let mut deltas = vec![Vec2::ZERO; count];
for ((i, r), o) in laid.iter().zip(&rects).zip(origins) {
if let Some(dl) = deltas.get_mut(*i)
&& !d.artboards.get(*i).is_some_and(|a| a.locked)
{
*dl = o - r.origin();
}
}
let moved = deltas.iter().filter(|dl| dl.x.abs() > 1e-9 || dl.y.abs() > 1e-9).count();
let result = match &picked {
Some(indices) => json!({ "artboards": count, "indices": indices, "moved": moved, "rows": rows, "columns": cols }),
None => json!({ "artboards": count, "rows": rows, "columns": cols }),
};
// When no artboard moves more than 1e-9 pt on either axis, or there is none, the document and
// its undo history stay as they are.
if deltas.iter().all(|dl| dl.x.abs() <= 1e-9 && dl.y.abs() <= 1e-9) {
return Ok(json!({ "artboards": count, "rows": rows, "columns": cols }));
if moved == 0 {
return Ok(result);
}
// With moveArtwork, each top-level object (a child of a layer or sublayer) moves with the
// artboard its center is on, with symbol instances measured by their art as
@@ -1791,5 +1807,5 @@ fn rearrange_artboards(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(())
})?;
Ok(json!({ "artboards": count, "rows": rows, "columns": cols }))
Ok(result)
}
+24
View File
@@ -601,6 +601,30 @@ pub(crate) fn grid_origins_rc(
.collect()
}
/// Rearrange Artboards' grid for artboards of `sizes`, in their order, its top-left at `origin`:
/// `lines` is the column count of a grid by row and the row count of a grid by column (kept to 1
/// to the artboard count), and `rtl` puts the first column at the right. Returns each artboard's
/// top-left corner and the grid's rows and columns.
pub fn rearrange_grid(
sizes: &[(f64, f64)],
origin: Point,
layout: ArtboardLayout,
lines: u64,
spacing: f64,
rtl: bool,
) -> (Vec<Point>, usize, usize) {
let n = sizes.len().max(1);
let lines = usize::try_from(lines).unwrap_or(usize::MAX).clamp(1, n);
let (rows, cols) = match layout {
ArtboardLayout::GridByRow => (n.div_ceil(lines), lines),
ArtboardLayout::GridByColumn => (lines, n.div_ceil(lines)),
ArtboardLayout::Row => (1, n),
ArtboardLayout::Column => (n, 1),
};
let origins = grid_origins_rc(sizes, origin, (rows, cols), spacing, layout == ArtboardLayout::GridByColumn, rtl);
(origins, rows, cols)
}
/// The built-in presets: (category, presets as (name, width, height, units)), with the category's
/// colour mode and raster effects resolution. Sizes in `units` (converted to points on use).
type Category = (&'static str, ColorMode, f64, &'static [(&'static str, f64, f64, Unit)]);
+290 -97
View File
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fill",
[],
None,
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change the bucket made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row o Line truncated
has_doc,
|s, p| set_paint(s, p, true)
),
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke",
[],
None,
"{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke; without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
"{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill), opacity?: 0..100 (the opacity of that stroke item, as paint.setFill's for the fill item)} same as paint.setFill, for the stroke; without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
has_doc,
|s, p| { set_paint(s, p, false) }
),
@@ -161,7 +161,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Fill and Stroke",
[],
None,
"{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors)}",
"{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors), fillOpacity, strokeOpacity: 0..100, the opacity of the fill item that paint.setFill {opacity} sets (the stroke item that paint.setStroke {opacity} sets), from the first selected object (or painted object in a selected group; a selected path of a compound path stands for its compound, and a Live Paint group for its faces' fills and its edges' strokes) that has one (a gradient mesh's first picked point's), or null with nothing selected (the defaults for new art), for an object selected in a symbol instance, while the Live Paint Bucket is the active tool, while the Type tool has characters selected, and when only type characters or objects without that item are selected}",
always,
proxies
),
@@ -239,6 +239,80 @@ impl Session {
None
}
/// The opacity (0..1) of the fill that `paint.setFill {opacity}` sets (or of the stroke that
/// `paint.setStroke {opacity}` sets): the item's, or for a gradient mesh with points picked the
/// first picked point's. The rows the command would edit are read in order (a group without an
/// active Appearance row stands for its contents), and the first that exists answers. `None`
/// with nothing selected, for an object selected in a symbol instance, while the Live Paint
/// Bucket is the active tool (or another tool works for it, [`Session::bucket_paints`]), while
/// the Type tool has characters selected, and when only type
/// characters, objects without that item or the art of graph designs in a graph series are
/// selected.
pub fn proxy_opacity(&self, stroke: bool) -> Option<f32> {
let st = self.active()?;
// The Live Paint Bucket takes a fill or stroke chosen as the color it paints with, and the
// selection keeps its own (for_bucket).
if st.selection.symbol_part.is_some() || self.bucket_paints() {
return None;
}
// The command would give the opacity to the characters, which have none of their own.
if super::textedit::selected_range(self).is_some_and(|(_, a, b)| a != b) {
return None;
}
let item = self.appearance_item();
let of = |n: &Node, item: Option<usize>| -> Option<f32> {
if item.is_none() && matches!(n.kind, NodeKind::Text(_)) {
return None;
}
if !stroke
&& item.is_none()
&& let NodeKind::Mesh(m) = &n.kind
&& let Some((_, points)) = picked_mesh_points(self, &[n.id]).first()
{
return points.first().and_then(|i| m.points.get(*i)).map(|q| q.opacity);
}
if stroke { n.appearance.stroke_at(item).map(|s| s.opacity) } else { n.appearance.fill_at(item).map(|f| f.opacity) }
};
let subjects = st.selection.subjects();
// The command leaves out the art of a graph design in a series, which the graph draws again
// from the design, and a series group stands for the paths directly in it
// (graph::paint_targets).
let editable = |id: &&NodeId| !super::graph::is_design_art(&st.doc, **id);
// As the command picks its rows (ItemTarget::of_kind): the active item when it is a row of
// this kind in the first selected object's stack, read in the stacks the command edits;
// else the topmost one of the painted leaves of the selected objects (a group's
// contents; for a targeted layer, its editable art, ItemTarget::targets). A row of a
// graph design's art selected first stands for nothing (item_target_at).
let first = subjects.first().filter(editable).and_then(|id| st.doc.node(*id));
let active = item.filter(|i| first.and_then(|n| n.appearance.items.get(*i)).is_some_and(|it| it.is_fill() == !stroke));
if let Some(index) = active {
// The objects whose own stacks the command edits (appearance_targets: a selected
// compound-path member stands for its compound, and an object inside another selected
// one is left out), with the one whose stack the row belongs to first.
// Each target reads the row the command edits there (ItemTarget::per_target and
// ItemTarget::resolve): the row equal to the active one, else its topmost of the kind.
let row = ItemTarget::Item { index, explicit: false, aligned: true };
let mut roots = super::appearance::appearance_targets(self, &Value::Null).ok()?;
let anchor = row.anchor(self, &roots);
if let Some(head) = roots.get_mut(..=anchor) {
head.rotate_right(1);
}
let targets: Vec<NodeId> = super::graph::series_group_marks_where(&st.doc, &roots, |n| n.extras().series_index.is_some())
.into_iter()
.filter(|id| editable(&id))
.collect();
return targets.iter().zip(row.per_target(self, &targets)).find_map(|(id, at)| {
let n = st.doc.node(*id)?;
of(n, at?.resolve(&n.appearance, !stroke, "paint.proxies").ok()?)
});
}
// A Live Paint group stands for its faces in a fill edit and for its edges in a stroke edit
// (ItemTarget::targets_for).
let leaves = super::leaf_targets(self, &st.selection.objects).ok()?;
let skipped = live_paint_parts_skipped(&st.doc, &st.selection.objects, !stroke);
leaves.iter().filter(editable).filter(|id| !skipped.contains(*id)).filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, None))
}
pub(crate) fn remember_paint_now(&mut self, p: &Paint) {
match p {
Paint::Solid { color, .. } => {
@@ -483,7 +557,12 @@ impl Session {
fn proxies(s: &mut Session, _: &Value) -> Result<Value> {
let (fill, stroke) = s.proxy_paints();
let (fill_mixed, stroke_mixed) = s.proxy_mixed();
Ok(json!({"fill": fill, "stroke": stroke, "fillActive": s.fill_active, "fillMixed": fill_mixed, "strokeMixed": stroke_mixed}))
// As transparency.info answers an opacity: a percentage to two places.
let percent = |o: Option<f32>| o.map(|o| (f64::from(o) * 10_000.0).round() / 100.0);
Ok(json!({
"fill": fill, "stroke": stroke, "fillActive": s.fill_active, "fillMixed": fill_mixed, "strokeMixed": stroke_mixed,
"fillOpacity": percent(s.proxy_opacity(false)), "strokeOpacity": percent(s.proxy_opacity(true)),
}))
}
/// `stroke` param, defaulting to the proxy that is in front.
@@ -602,13 +681,36 @@ fn set_paint(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
return Err(bad(cmd, "`tint` goes with a global or spot `swatch`"));
}
check_keep_model(p, cmd)?;
let paint = paint_from(s, p)?.ok_or_else(|| bad(cmd, "give color, none, swatch or gradient"))?;
let opacity = opacity_param(p, cmd)?;
let paint = paint_from(s, p)?;
// A `swatch` that is no name gives no paint, and does not turn the request into an opacity alone.
let swatch_not_a_name = p.get("swatch").is_some_and(|v| !v.is_null() && !v.is_string());
if paint.is_none() && (opacity.is_none() || swatch_not_a_name) {
return Err(bad(cmd, "give color, none, swatch, gradient or opacity"));
}
// As `paint.editGradient`: a `dither` given applies to gradient fills only. A gradient swatch
// (named) keeps its own dither; `"swatch": null` names none.
if !fill && matches!(&paint, Paint::Gradient(g) if g.gradient.dither) && p.get("swatch").and_then(Value::as_str).is_none() {
if !fill && matches!(&paint, Some(Paint::Gradient(g)) if g.gradient.dither) && p.get("swatch").and_then(Value::as_str).is_none() {
return Err(bad(cmd, "`dither` applies to gradient fills (paint.setFill)"));
}
apply_paint(s, p, paint, fill)
apply_paint_opacity(s, p, paint, opacity, fill)
}
/// The `opacity` param of `paint.setFill` and `paint.setStroke` (a percentage) as 0..1; `None`
/// when it is left out or null.
fn opacity_param(p: &Value, cmd: &str) -> Result<Option<f32>> {
match p.get("opacity") {
None | Some(Value::Null) => Ok(None),
Some(v) => match v.as_f64() {
Some(o) if (0.0..=100.0).contains(&o) => Ok(Some((o / 100.0) as f32)),
_ => Err(bad(cmd, "`opacity` must be a number from 0 to 100")),
},
}
}
/// The error for an `opacity` that would go to type characters, which have no opacity of their own.
fn characters_have_no_opacity(cmd: &str) -> EngineError {
bad(cmd, "type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke")
}
/// [`apply_paint`] on the proxy named by `stroke` (default: the active one), focusing it.
@@ -621,17 +723,31 @@ fn apply_to_proxy(s: &mut Session, p: &Value, paint: Paint, cmd: &str) -> Result
/// `paint.setFill`) and of the defaults for new art, focus its proxy unless `focus` is false, and
/// remember the paint. Replies `{objects}`: how many objects took the paint.
pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) -> Result<Value> {
apply_paint_opacity(s, p, Some(paint), None, fill)
}
/// [`apply_paint`] with `paint` optional, which also sets the `opacity` (0..1) of the fill (or
/// stroke) item each target takes it on, in the same undo step: the picked gradient mesh points'
/// own opacity for a fill (with no paint or a solid color), nothing on a target without that item.
/// The opacity alone changes neither the defaults for new art nor the remembered colors; with New
/// Art Has Basic Appearance off, new art copies the first selected object's appearance after any
/// command, its opacity included. An opacity that would go only to type
/// characters, to an object selected in a symbol instance, or to no target at all is an error.
fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option<Paint>, opacity: Option<f32>, fill: bool) -> Result<Value> {
let cmd = if fill { "paint.setFill" } else { "paint.setStroke" };
let bucket = bucket_color_params(s, p, cmd)?;
let p = bucket.as_ref().unwrap_or(p);
let focus = switch_or(p, "focus", true, cmd)?;
let span = spans_targets(p, &paint).map_err(|e| bad(cmd, e))?;
// Characters selected with the Type tool take the paint, not the whole type object (#1063).
if p.get("ids").is_none()
// An opacity alone places no gradient, so `span` may only be "object" with it.
let span = spans_targets(p, paint.as_ref().unwrap_or(&Paint::None)).map_err(|e| bad(cmd, e))?;
// Characters selected with the Type tool take the paint, not the whole type object (#1063). A
// null `ids` or `id` names no object, as `given_nodes` reads it.
if ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null))
&& p.get("item").is_none()
&& let Some((id, a, b)) = super::textedit::editing_range(s)?
&& a != b
{
let (Some(paint), None) = (paint, opacity) else { return Err(characters_have_no_opacity(cmd)) };
// After Select All in threaded text, every frame's text takes it.
let story = super::textedit::editing_story(s);
let ranges: Vec<(NodeId, usize, usize)> =
@@ -684,6 +800,9 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
// An object of a dynamic symbol instance's art selected with Direct Selection: that object's
// fill or stroke changes for this instance only (solid, none, gradient or pattern).
if let Some((id, path)) = selected_part_target(s, p, cmd)? {
let Some(paint) = paint.filter(|_| opacity.is_none()) else {
return Err(bad(cmd, "an object selected in a symbol instance has no fill or stroke opacity of its own"));
};
super::brushsym::edit_part(s, id, &path, if fill { "Fill Color" } else { "Stroke Color" }, |o| {
if fill {
o.fill = Some(paint.clone());
@@ -702,36 +821,146 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
let item = item_target(s, p, cmd)?.of_kind(s, fill);
let selected = item.targets_for(s, p, fill)?;
let ids = super::graph::paint_targets(&s.doc()?.doc, &selected);
// An opacity has nothing to go to without targets; with a paint, the defaults then stay too.
if opacity.is_some() && ids.is_empty() {
return Err(bad(cmd, "select objects or give ids"));
}
let of = super::appearance::reference_of(s, p, item, cmd)?;
let paint = if span {
// With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. Each
// object's box is that of the row it edits.
let d = &s.doc()?.doc;
let mut spanned = Vec::with_capacity(ids.len());
for (id, it) in ids.iter().zip(item.per_target_of(s, of, &ids)) {
let (Some(it), Some(n)) = (it, d.node(*id)) else { continue };
spanned.push((*id, it.resolve(&n.appearance, fill, cmd)?));
let paint = match paint {
Some(paint) if span => {
// With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. Each
// object's box is that of the row it edits.
let d = &s.doc()?.doc;
let mut spanned = Vec::with_capacity(ids.len());
for (id, it) in ids.iter().zip(item.per_target_of(s, of, &ids)) {
let (Some(it), Some(n)) = (it, d.node(*id)) else { continue };
spanned.push((*id, it.resolve(&n.appearance, fill, cmd)?));
}
Some(placed_across(d, &spanned, paint, p, fill))
}
placed_across(d, &spanned, paint, p, fill)
} else {
paint
paint => paint,
};
// The gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso: a solid
// fill recolors just those points of their meshes (the proxies show them: `fill_mesh_points`).
let mesh_points = if fill && matches!(paint, Paint::Solid { .. }) { picked_mesh_points(s, &ids) } else { vec![] };
// fill recolors just those points of their meshes (the proxies show them: `fill_mesh_points`),
// and a fill opacity fades just them.
let mesh_points = if fill && matches!(paint, Some(Paint::Solid { .. }) | None) { picked_mesh_points(s, &ids) } else { vec![] };
// Without `item`, unless the Appearance panel's active fill item takes the paint.
let colorized = if fill && p.get("item").is_none() && item == ItemTarget::Top {
colorized_images(&s.doc()?.doc, &ids, &paint).map_err(|e| bad(cmd, e))?
} else {
vec![]
let colorized = match &paint {
Some(paint) if fill && p.get("item").is_none() && item == ItemTarget::Top => {
colorized_images(&s.doc()?.doc, &ids, paint).map_err(|e| bad(cmd, e))?
}
_ => vec![],
};
let label = match paint {
None => "Opacity",
Some(_) if fill => "Fill Color",
Some(_) => "Stroke Color",
};
let label = if fill { "Fill Color" } else { "Stroke Color" };
// Each object whose appearance took the paint, with the row it went to, for the paint a graph stores for its series
// (a series mark is a path, so it always has a row here).
let written = std::cell::RefCell::new(Vec::new());
// The type objects whose characters took the paint (no row targeted): only those change what a graph's labels keep
// for their characters; a row edit is kept with the label's rows.
let characters = std::cell::RefCell::new(Vec::new());
// The targets that took the opacity, and whether one would have given it to its characters.
let (took_opacity, characters_skipped) = (std::cell::RefCell::new(std::collections::BTreeSet::new()), std::cell::Cell::new(false));
// The row each target took the opacity on, for what a graph keeps.
let opacity_written = std::cell::RefCell::new(Vec::new());
let paint_one = |n: &mut Node, index: Option<usize>, paint: &Paint| -> Result<()> {
if index.is_none() && matches!(n.kind, NodeKind::Text(_)) {
characters.borrow_mut().push(n.id);
}
if index.is_none() && colorized.contains(&n.id) {
let colorize = paint.color().map(|_| Box::new(paint.clone()));
// Without a color the image has nothing to overprint, and a later color starts
// knocking out.
if colorize.is_none() {
n.extras_mut().colorize_overprint = false;
}
n.extras_mut().colorize = colorize;
return Ok(());
}
if index.is_none()
&& let Paint::Solid { color, .. } = paint
&& let Some((_, points)) = mesh_points.iter().find(|(id, _)| *id == n.id)
&& let NodeKind::Mesh(m) = &mut n.kind
{
for i in points {
if let Some(q) = m.points.get_mut(*i) {
q.color = *color;
}
}
return Ok(());
}
if index.is_none()
&& let NodeKind::Text(t) = &mut n.kind
{
let (xf, lb) = (t.xf, t.local_bounds());
for r in &mut t.runs {
if !fill && !paint.is_none() {
run_stroke_weight(&mut r.style);
}
let (cur, b) = run_paint_mut(r, !fill, lb);
*cur = place_run_paint(paint, p, xf, b);
}
return Ok(());
}
// A missing top fill or stroke is created first: a new stroke's weight sizes the box its
// gradient fits.
if n.appearance.paint_at(index, fill).is_none() {
n.appearance.set_paint_at(index, fill, Paint::None);
}
if !fill {
restore_unpainted_stroke(&mut n.appearance, index, paint);
}
let new_paint = keep_pattern_xf(paint, p, n.appearance.paint_at(index, fill));
let placed = place_paint(&new_paint, p, item_paint_bounds(n, index, fill));
n.appearance.set_paint_at(index, fill, placed);
if !fill
&& paint.is_none()
&& let Some(stroke) = n.appearance.stroke_at_mut(index)
{
// A stroke without paint has no weight; painting it again restores the 1 pt default.
stroke.width = 0.0;
}
if !fill {
super::object::snap_if_aligned(n);
}
let at = match index {
Some(_) => n.appearance.item_of_kind(index, fill),
None => n.appearance.items.iter().rposition(|it| it.is_fill() == fill),
};
written.borrow_mut().extend(at.map(|at| (n.id, at)));
Ok(())
};
// The opacity goes to what the paint went to: the picked mesh points, else the fill or stroke
// item. Characters, and targets without that item, are left as they are.
let opacity_one = |n: &mut Node, index: Option<usize>, o: f32| {
if index.is_none() && matches!(n.kind, NodeKind::Text(_)) {
characters_skipped.set(true);
return;
}
if index.is_none()
&& let Some((_, points)) = mesh_points.iter().find(|(id, _)| *id == n.id)
&& let NodeKind::Mesh(m) = &mut n.kind
{
for i in points {
if let Some(q) = m.points.get_mut(*i) {
q.opacity = o;
took_opacity.borrow_mut().insert(n.id);
}
}
return;
}
let item =
if fill { n.appearance.fill_at_mut(index).map(|f| &mut f.opacity) } else { n.appearance.stroke_at_mut(index).map(|s| &mut s.opacity) };
if let Some(item) = item {
*item = o;
took_opacity.borrow_mut().insert(n.id);
let at = index.or_else(|| n.appearance.items.iter().rposition(|it| it.is_fill() == fill));
opacity_written.borrow_mut().extend(at.map(|at| (n.id, at)));
}
};
// The objects counted: with a design's art, those with a row equal to the art's.
let ids = edit_items_then(
s,
@@ -742,96 +971,60 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
label,
fill,
|n, index| {
if index.is_none() && matches!(n.kind, NodeKind::Text(_)) {
characters.borrow_mut().push(n.id);
if let Some(paint) = &paint {
paint_one(n, index, paint)?;
}
if index.is_none() && colorized.contains(&n.id) {
let colorize = paint.color().map(|_| Box::new(paint.clone()));
// Without a color the image has nothing to overprint, and a later color starts
// knocking out.
if colorize.is_none() {
n.extras_mut().colorize_overprint = false;
}
n.extras_mut().colorize = colorize;
return Ok(());
if let Some(o) = opacity {
opacity_one(n, index, o);
}
if index.is_none()
&& let Paint::Solid { color, .. } = &paint
&& let Some((_, points)) = mesh_points.iter().find(|(id, _)| *id == n.id)
&& let NodeKind::Mesh(m) = &mut n.kind
{
for i in points {
if let Some(q) = m.points.get_mut(*i) {
q.color = *color;
}
}
return Ok(());
}
if index.is_none()
&& let NodeKind::Text(t) = &mut n.kind
{
let (xf, lb) = (t.xf, t.local_bounds());
for r in &mut t.runs {
if !fill && !paint.is_none() {
run_stroke_weight(&mut r.style);
}
let (cur, b) = run_paint_mut(r, !fill, lb);
*cur = place_run_paint(&paint, p, xf, b);
}
return Ok(());
}
// A missing top fill or stroke is created first: a new stroke's weight sizes the box its
// gradient fits.
if n.appearance.paint_at(index, fill).is_none() {
n.appearance.set_paint_at(index, fill, Paint::None);
}
if !fill {
restore_unpainted_stroke(&mut n.appearance, index, &paint);
}
let new_paint = keep_pattern_xf(&paint, p, n.appearance.paint_at(index, fill));
let placed = place_paint(&new_paint, p, item_paint_bounds(n, index, fill));
n.appearance.set_paint_at(index, fill, placed);
if !fill
&& paint.is_none()
&& let Some(stroke) = n.appearance.stroke_at_mut(index)
{
// A stroke without paint has no weight; painting it again restores the 1 pt default.
stroke.width = 0.0;
}
if !fill {
super::object::snap_if_aligned(n);
}
let at = match index {
Some(_) => n.appearance.item_of_kind(index, fill),
None => n.appearance.items.iter().rposition(|it| it.is_fill() == fill),
};
written.borrow_mut().extend(at.map(|at| (n.id, at)));
Ok(())
},
|before, d, changed| {
// An opacity that no target took is an error, which also takes back the paint given with it.
if opacity.is_some() && took_opacity.borrow().is_empty() {
if characters_skipped.get() {
return Err(characters_have_no_opacity(cmd));
}
return Err(bad(cmd, "no target has that fill or stroke to take the opacity"));
}
// A graph keeps the opacity of a series mark's topmost visible fill and stroke for the whole series, and of a
// graph line's, also when the object already showed it.
let kept = opacity.is_some() && {
let rows = opacity_written.borrow();
let on = super::graph::RowWrites { opacity: true, ..super::graph::RowWrites::NONE };
let (on_fill, on_stroke) = if fill { (on, super::graph::RowWrites::NONE) } else { (super::graph::RowWrites::NONE, on) };
let marks = super::appearance::capture_series_changes(before, d, changed);
let written = super::appearance::capture_series_opacity_writes(d, &rows);
marks | written | super::graph::capture_line_row_writes(d, &rows, on_fill, on_stroke)
};
let Some(paint) = &paint else { return Ok(kept) };
let series = super::appearance::capture_series_paint_writes(before, d, changed, &written.borrow());
// A graph line keeps the paint written to it, also when it already showed it.
let lines = super::graph::capture_line_paint_writes(d, &written.borrow());
let labels = super::graph::capture_label_styles(d, &characters.borrow(), &|st| {
if fill {
st.fill = unplaced(&paint);
st.fill = unplaced(paint);
} else {
if !paint.is_none() {
run_stroke_weight(st);
}
st.stroke = unplaced(&paint);
st.stroke = unplaced(paint);
}
});
Ok(series || lines || labels)
Ok(series || lines || labels || kept)
},
)?;
// Rejected edits leave the next shape's appearance and active proxy untouched.
paint_new_art(s, &paint, fill);
if focus {
s.fill_active = fill;
}
s.remember_paint(&paint);
Ok(json!({"objects": ids.iter().collect::<std::collections::BTreeSet<_>>().len()}))
// Rejected edits leave the next shape's appearance and active proxy untouched.
if let Some(paint) = &paint {
paint_new_art(s, paint, fill);
s.remember_paint(paint);
}
// An opacity alone counts only the targets that took it.
let objects = if paint.is_none() { took_opacity.borrow().len() } else { ids.iter().collect::<std::collections::BTreeSet<_>>().len() };
Ok(json!({"objects": objects}))
}
/// Does `p` name no `ids`, `id` or `item`?
+35 -1
View File
@@ -122,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Delete Anchor Points",
[],
None,
"{} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key)",
"{} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key, unless the deleteKeepsPathsJoined preference is on)",
has_anchors,
delete_anchors
),
@@ -1652,6 +1652,17 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result<Value> {
/// Layers are retained, and an object removed with a selected ancestor is not removed twice.
/// Returns JSON `null` on success; selection is replaced by the surviving object IDs.
pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
delete_anchors_joined(s, p, false)
}
/// [`delete_anchors`], and with `keep_joined` (General › Delete Removes Anchor Points and Keeps
/// Paths Joined) a path with direct-selected anchors and no selected segment loses those anchors
/// as Remove Anchor Points takes them, without opening it, and stays selected with the next
/// anchor along (the one before at an open subpath's end), so the next Delete goes on along the
/// path. When no subpath it changed keeps two anchors, the path stays selected whole, as Remove
/// Anchor Points leaves it. Paths with a selected segment are cut there, as without `keep_joined`
/// (their selected anchors stay in the path), and objects selected whole are deleted, in the same undo step.
pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: bool) -> Result<Value> {
// `guides: true` (Cut, #3226): the selected ruler guides go in the same undo step.
let with_guides = switch_or(p, "guides", false, "path.deleteAnchors")?;
let st = s.doc()?;
@@ -1681,6 +1692,7 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
d.remove_many(&whole_ids)?;
}
let mut survivors = vec![];
let mut following = vec![];
let remaining: Vec<NodeId> = sel.keys().copied().filter(|id| d.node(*id).is_some()).collect();
let mut emptied = Beside::replacing(d, &remaining);
for (id, set) in &sel {
@@ -1688,6 +1700,23 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
if d.node(*id).is_none() {
continue;
}
if keep_joined
&& !set.is_empty()
&& !segments.contains_key(id)
&& let Some(path) = d.node(*id).and_then(|n| match &n.kind {
NodeKind::Path { path, .. } => Some(path),
_ => None,
})
{
let shape: Vec<(usize, bool)> = path.subpaths.iter().map(|sp| (sp.anchors.len(), sp.closed)).collect();
let anchors: Vec<(usize, usize)> = set.iter().copied().collect();
let next = super::draw2::following_anchors(&shape, &anchors);
if !super::draw2::remove_anchors_of(d, selection, &mut emptied, *id, anchors, false)? {
survivors.push(*id);
following.push((*id, next));
}
continue;
}
let original = deletion_source(d, *id)?;
let subpaths: Vec<SubPath> = {
let path = path_mut(d, *id)?;
@@ -1731,6 +1760,11 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
}
}
selection.set(survivors);
for (id, next) in following {
if !next.is_empty() {
selection.anchors.insert(id, next);
}
}
Ok(())
})?;
ok()
+82 -20
View File
@@ -3,6 +3,7 @@
//! document holding its patterns, drawn here from plain shapes ([`PATTERN_LIBRARIES`]).
//! `swatch.library.add` copies a pattern into the document with its swatch.
use std::collections::BTreeMap;
use std::sync::{Arc, LazyLock};
use vectorcraft_color::{Color, Paint, Swatch, SwatchLibrary};
@@ -15,6 +16,10 @@ use super::clipboard::Clipboard;
use super::clipboard::resources::{Imported, SwatchChoices};
use super::swatchlib::LibraryInfo;
/// Names that swatches and patterns coming in under a numbered name skip, each with the library
/// swatch it is reserved for ([`SwatchChoices::reserving`]).
pub(crate) type Reserved = Arc<BTreeMap<String, Swatch>>;
/// A built-in pattern library: a stable id, its menu name and the function that adds its patterns.
pub struct BuiltinPatternLibrary {
pub id: &'static str,
@@ -96,17 +101,18 @@ pub(crate) type SwatchNames = Vec<(String, String)>;
/// A global or spot color whose name `d` gives another color comes in under a free name, as Add
/// to Swatches adds such a color, so that the pattern keeps the library's colors. Those colors
/// merge instead when that reuses a pattern of `d` that keeping them would add again
/// ([`probe_import`]).
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str) -> Result<(String, SwatchNames, SwatchNames)> {
/// ([`probe_import`]). A swatch that comes in under a numbered name skips the names in
/// `reserved`.
pub(crate) fn import(d: &mut Document, lib: &Document, name: &str, reserved: &Reserved) -> Result<(String, SwatchNames, SwatchNames)> {
let gathered = gather(lib, name);
let had: std::collections::HashSet<String> = d.swatches_iter().map(|w| w.name.clone()).collect();
// Without a color to merge or a pattern to reuse, the document is not copied.
let imported = if !gathered.swatches.is_empty() && has_candidate(d, lib, name) {
let (_, probed, imported) = probe_import(d, lib, name, &gathered)?;
let (_, probed, imported) = probe_import(d, lib, name, &gathered, reserved)?;
*d = probed;
imported
} else {
gathered.import_into(d, &SwatchChoices::add_all(), false)?
gathered.import_into(d, &SwatchChoices::add_all().reserving(reserved), false)?
};
let from = |to: &str| {
let renamed = imported.renamed.iter().find(|r| r["kind"] == "swatch" && r["to"] == to).and_then(|r| r["from"].as_str());
@@ -138,9 +144,11 @@ pub(crate) fn brought_names(lib: &Document, name: &str) -> std::collections::Has
gather(lib, name).swatches.into_iter().map(|w| w.name).collect()
}
/// The names in `lib` of pattern `name` and of the patterns its art brings.
pub(crate) fn brought_patterns(lib: &Document, name: &str) -> std::collections::HashSet<String> {
gather(lib, name).patterns.into_iter().map(|p| p.name).collect()
/// The names in `lib` of the swatches and patterns that pattern `name` of `lib` brings, itself
/// included.
pub(crate) fn brought_resource_names(lib: &Document, name: &str) -> std::collections::HashSet<String> {
let gathered = gather(lib, name);
gathered.swatches.into_iter().map(|w| w.name).chain(gathered.patterns.into_iter().map(|p| p.name)).collect()
}
/// The name pattern `name` has in the document `imported` went into.
@@ -154,8 +162,8 @@ pub(crate) fn imported_name(imported: &Imported, name: &str) -> String {
/// name than its own, as [`import`] lists them. A pattern whose art uses no other resource is
/// compared as [`existing_pattern`] does. One whose art uses other resources, such as a pattern it
/// is painted with, is imported into a copy of `d` as [`probe_import`] does, so that those
/// resources are compared too.
pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Option<(String, SwatchNames)> {
/// resources are compared too, with numbered names skipping `reserved`.
pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str, reserved: &Reserved) -> Option<(String, SwatchNames)> {
let gathered = gather(lib, name);
let only_pattern = gathered.patterns.len() == 1
&& gathered.symbols.is_empty()
@@ -173,7 +181,7 @@ pub(crate) fn present_pattern(d: &Document, lib: &Document, name: &str) -> Optio
if !has_candidate(d, lib, name) {
return None;
}
let (_, _, imported) = probe_import(d, lib, name, &gathered).ok()?;
let (_, _, imported) = probe_import(d, lib, name, &gathered, reserved).ok()?;
if imported.added != 0 {
return None;
}
@@ -203,19 +211,73 @@ pub(crate) fn has_candidate(d: &Document, lib: &Document, name: &str) -> bool {
/// another color comes in under a free name (Add). Those colors merge instead when Add would add
/// the pattern again while merging reuses a pattern of `d`: such a pattern has its art linked to
/// the document's own colors of those names, as pasting with Merge, or adding it from a library
/// before, leaves it.
pub(crate) fn probe_import(d: &Document, lib: &Document, name: &str, gathered: &Clipboard) -> Result<(SwatchChoices, Document, Imported)> {
/// before, leaves it. A swatch or pattern that comes in under a numbered name skips the names in
/// `reserved` ([`SwatchChoices::reserving`]). When that changed a name and the pattern would come
/// in again, or would be reused only by merging colors, an import that does not skip them is used
/// if it reuses a pattern of `d` (one pasted there), without merging in the second case, and uses
/// none of those names that `d` does not use, other than for the swatch a name is reserved for.
pub(crate) fn probe_import(
d: &Document,
lib: &Document,
name: &str,
gathered: &Clipboard,
reserved: &Reserved,
) -> Result<(SwatchChoices, Document, Imported)> {
let reused = |i: &Imported| d.pattern(&imported_name(i, name)).is_some();
let mut with_add = d.clone();
let added = gathered.import_into(&mut with_add, &SwatchChoices::add_all(), false)?;
if !reused(&added) && added.renamed.iter().any(|r| r["kind"] == "swatch") && has_candidate(d, lib, name) {
let mut merged = d.clone();
let found = gathered.import_into(&mut merged, &SwatchChoices::default(), false)?;
if reused(&found) {
return Ok((SwatchChoices::default(), merged, found));
let found = probe_skipping(d, lib, name, gathered, reserved)?;
// A reuse that merges colors gives the pattern the document's colors, so one that keeps the
// library's is tried too.
let merged = |i: &Imported| reused(i) && i.merged != 0;
if found.2.reserved_named && (!reused(&found.2) || merged(&found.2)) && has_candidate(d, lib, name) {
let pasted = probe_skipping(d, lib, name, gathered, &Reserved::default())?;
let better = !reused(&found.2) || !merged(&pasted.2);
if reused(&pasted.2) && better && !takes_reserved(d, &pasted.1, &pasted.2, gathered, reserved) {
return Ok(pasted);
}
}
Ok((SwatchChoices::add_all(), with_add, added))
Ok(found)
}
/// Whether `probed`, the import of `gathered` into a copy of `d` that `imported` describes, gives a
/// name in `reserved` that `d` does not use to a pattern, or to a swatch other than the one the name
/// is reserved for coming in under its own name.
fn takes_reserved(d: &Document, probed: &Document, imported: &Imported, gathered: &Clipboard, reserved: &Reserved) -> bool {
let had: std::collections::HashSet<&str> =
d.swatches_iter().map(|w| w.name.as_str()).chain(d.swatch_groups.iter().map(|g| g.name.as_str())).collect();
let renamed_to = |n: &str| imported.renamed.iter().any(|r| r["kind"] == "swatch" && r["to"] == n && r["from"] != n);
let owner_only = |n: &str, owner: &Swatch| gathered.swatches.iter().filter(|w| w.name == n).all(|w| w == owner);
let swatch = probed
.swatches_iter()
.map(|w| w.name.as_str())
.filter(|n| !had.contains(n))
.any(|n| reserved.get(n).is_some_and(|owner| !owner_only(n, owner) || renamed_to(n)));
let patterns: std::collections::HashSet<&str> = d.patterns.iter().map(|p| p.name.as_str()).collect();
swatch || probed.patterns.iter().any(|p| !patterns.contains(p.name.as_str()) && reserved.contains_key(&p.name))
}
/// [`probe_import`] with numbered names skipping `reserved`.
fn probe_skipping(
d: &Document,
lib: &Document,
name: &str,
gathered: &Clipboard,
reserved: &Reserved,
) -> Result<(SwatchChoices, Document, Imported)> {
let reused = |i: &Imported| d.pattern(&imported_name(i, name)).is_some();
let (add, merge) = (SwatchChoices::add_all().reserving(reserved), SwatchChoices::default().reserving(reserved));
let mut with_add = d.clone();
let mut added = gathered.import_into(&mut with_add, &add, false)?;
if !reused(&added) && added.renamed.iter().any(|r| r["kind"] == "swatch") && has_candidate(d, lib, name) {
let mut merged = d.clone();
let mut found = gathered.import_into(&mut merged, &merge, false)?;
// Whether a reservation changed a name counts for either import.
found.reserved_named |= added.reserved_named;
if reused(&found) {
return Ok((merge, merged, found));
}
added.reserved_named |= found.reserved_named;
}
Ok((add, with_add, added))
}
/// The pattern of `d` that is pattern `name` of library `lib`: the same tile options and art under
+286 -8
View File
@@ -44,6 +44,7 @@
//! images or symbol instances of those kinds, to read only: its output must return each of them
//! unchanged ([`objects::decode_output_with`]).
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
use serde_json::{Map, Value, json};
@@ -113,8 +114,19 @@ pub fn describe(p: &Plugin) -> Value {
.iter()
.map(|c| {
let run = m.for_command(c);
json!({"id": c.id, "command": command_id(&m.id, &c.id), "label": c.shown_label(), "params": run.params_doc(),
"paramsSchema": serde_json::to_value(&run).ok().and_then(|v| v.get("params").cloned())})
let mut entry = json!({"id": c.id, "command": command_id(&m.id, &c.id), "label": c.shown_label(), "params": run.params_doc(),
"paramsSchema": serde_json::to_value(&run).ok().and_then(|v| v.get("params").cloned())});
if let Some(place) = &c.place {
let mut menu = json!({"path": place.path});
if let Some(after) = &place.after {
menu["after"] = json!(permissions::display_text(after, permissions::MAX_SHOWN_NAME));
}
if placed_menu(p, c).is_none() {
menu["placed"] = json!(false);
}
entry["menu"] = menu;
}
entry
})
.collect();
v["commands"] = json!(commands);
@@ -497,15 +509,278 @@ pub fn find_spec(id: &str) -> Option<&'static CommandSpec> {
command_specs().into_iter().find(|c| c.id == id)
}
/// The letters and digits of `label`, lowercased. Two labels with the same key read alike in a menu
/// (`Paste (in Place)` and `Paste in Place`).
fn label_key(label: &str) -> String {
label.chars().filter(|ch| ch.is_alphanumeric()).flat_map(char::to_lowercase).collect()
}
/// The labels of engine commands whose menu item switches to the label of [`other_state`] (the
/// desktop app's dynamic labels).
pub const SWITCHING_LABELS: &[&str] = &[
"Preview",
"Outline",
"Show Rulers",
"Change to Global Rulers",
"Show Transparency Grid",
"Lock Guides",
"Hide Slices",
"Show Print Tiling",
"Lock Grid",
"Edit Envelope",
"Edit Contents",
"Start Global Edit",
];
/// The label of `label`'s other state, for a menu item that switches between two labels: `Show
/// Edges` for `Hide Edges`, `Unlock Guides` for `Lock Guides`, `Stop Global Edit` for `Start Global
/// Edit`, and the reverse.
pub fn other_state(label: &str) -> Option<String> {
const PAIRS: &[(&str, &str)] = &[
("Preview", "Outline"),
("Change to Global Rulers", "Change to Artboard Rulers"),
("Edit Envelope", "Edit Contents"),
("Start Global Edit", "Stop Global Edit"),
];
let paired = |&(a, b): &(&'static str, &'static str)| {
if label == a {
Some(b)
} else if label == b {
Some(a)
} else {
None
}
};
if let Some(other) = PAIRS.iter().find_map(paired) {
return Some(other.to_string());
}
[("Hide ", "Show "), ("Show ", "Hide "), ("Lock ", "Unlock "), ("Unlock ", "Lock ")]
.iter()
.find_map(|(from, to)| label.strip_prefix(from).map(|rest| format!("{to}{rest}")))
}
/// The menu that plug-in `p`'s command `c` is listed in when its manifest's `menu` places it in
/// another menu: that menu's path, or `None` when `c` stays in its plug-in's submenu. It stays
/// there when its menu label ([`Command::menu_label`]) has the same letters and digits, ignoring
/// case, as an engine command listed in that menu (either label of one of [`SWITCHING_LABELS`]),
/// an item of [`DESKTOP_MENU_ITEMS`] there, or a command that a plug-in with a lower id, or an
/// earlier command of `p`, places in that menu. The result is the same with and without the
/// desktop app. Results for installed plug-ins are kept until the registry changes.
pub fn placed_menu(p: &Plugin, c: &Command) -> Option<&'static [&'static str]> {
type Placed = HashMap<String, Option<&'static [&'static str]>>;
static PLACED: Mutex<Option<(u64, Placed)>> = Mutex::new(None);
c.place.as_ref()?;
let m = p.manifest();
// Read before the registry, so a result found while the registry changes is kept under the
// revision before the change.
let revision = registry::revision();
// `plugin.inspect` describes a module that is not installed, or not yet in place of the
// installed one: never kept.
if !registry::get(&m.id).is_some_and(|q| std::ptr::eq(&*q, p)) {
return find_place(p, c);
}
let id = command_id(&m.id, &c.id);
if let Ok(placed) = PLACED.lock()
&& let Some((at, known)) = placed.as_ref()
&& *at == revision
&& let Some(found) = known.get(&id)
{
return *found;
}
let found = find_place(p, c);
if let Ok(mut placed) = PLACED.lock() {
let (at, known) = placed.get_or_insert_with(|| (revision, HashMap::new()));
if *at != revision {
*at = revision;
known.clear();
}
known.insert(id, found);
}
found
}
/// [`placed_menu`], found again.
fn find_place(p: &Plugin, c: &Command) -> Option<&'static [&'static str]> {
let place = c.place.as_ref()?;
let m = p.manifest();
let key = label_key(&c.menu_label(&m.name));
let reads_like =
|label: &str| label_key(label) == key || SWITCHING_LABELS.contains(&label) && other_state(label).is_some_and(|o| label_key(&o) == key);
if super::command_specs().iter().any(|s| s.menu == place.path && reads_like(s.label))
|| DESKTOP_MENU_ITEMS.iter().any(|(path, label)| *path == place.path && label_key(label) == key)
{
return None;
}
let taken = |name: &str, d: &Command| d.place.as_ref().is_some_and(|e| e.path == place.path) && label_key(&d.menu_label(name)) == key;
// The registry lists plug-ins in id order. `p` itself may not be installed yet (`plugin.inspect`),
// or be replacing the installed module of its id, so its own commands come from `m`.
for q in registry::list() {
let qm = q.manifest();
if qm.id >= m.id {
break;
}
if qm.commands.iter().any(|d| taken(&qm.name, d)) {
return None;
}
}
for d in &m.commands {
if d.id == c.id {
return Some(place.path);
}
if taken(&m.name, d) {
return None;
}
}
Some(place.path)
}
/// The labels of the desktop app's own items (not engine commands) in the menus of
/// [`vectorcraft_plugins::manifest::MENU_PLACES`], with both labels of an item that switches
/// between two. [`placed_menu`] reads them, so its result is the same with and without the desktop
/// app.
pub const DESKTOP_MENU_ITEMS: &[(&[&str], &str)] = &[
(&["Edit"], "Spelling"),
(&["Edit"], "Edit Custom Dictionary…"),
(&["Edit"], "Edit Colors"),
(&["Edit"], "Edit Original"),
(&["Edit"], "Transparency Flattener Presets…"),
(&["Edit"], "Print Presets…"),
(&["Edit"], "PDF Presets…"),
(&["Edit"], "Tracing Presets…"),
(&["Edit"], "Perspective Grid Presets…"),
(&["Edit"], "Refresh Monitor Profile"),
(&["Edit"], "Keyboard Shortcuts…"),
(&["Edit"], "Preferences…"),
(&["Edit", "Edit Colors"], "Recolor with Preset"),
(&["Object"], "Transform"),
(&["Object"], "Arrange"),
(&["Object"], "Align"),
(&["Object"], "Distribute"),
(&["Object"], "Lock"),
(&["Object"], "Hide"),
(&["Object"], "Slice"),
(&["Object"], "Path"),
(&["Object"], "Shape"),
(&["Object"], "Pattern"),
(&["Object"], "Repeat"),
(&["Object"], "Intertwine"),
(&["Object"], "Objects on Path"),
(&["Object"], "Blend"),
(&["Object"], "Envelope Distort"),
(&["Object"], "Perspective"),
(&["Object"], "Live Paint"),
(&["Object"], "Image Trace"),
(&["Object"], "Text Wrap"),
(&["Object"], "Clipping Mask"),
(&["Object"], "Compound Path"),
(&["Object"], "Artboards"),
(&["Object"], "Graph"),
(&["Object"], "Collect for Export"),
(&["Object"], "Plug-ins"),
(&["Type"], "Font"),
(&["Type"], "Recent Fonts"),
(&["Type"], "Size"),
(&["Type"], "Bold"),
(&["Type"], "Italic"),
(&["Type"], "Glyphs"),
(&["Type"], "Insert Special Character"),
(&["Type"], "Insert Whitespace Character"),
(&["Type"], "Insert Break Character"),
(&["Type"], "Type on a Path"),
(&["Type"], "Dynamic Text Presets"),
(&["Type"], "Threaded Text"),
(&["Type"], "Find Font…"),
(&["Type"], "Change Case"),
(&["Type"], "Bullets and Numbering"),
(&["Type"], "Show Hidden Characters"),
(&["Type"], "Hide Hidden Characters"),
(&["Type"], "Type Orientation"),
(&["Select"], "Same"),
(&["Select"], "Object"),
(&["Select"], "Saved Selection"),
(&["Effect"], "Apply Last Effect"),
(&["Effect"], "Last Effect…"),
(&["Effect"], "3D and Materials"),
(&["Effect"], "Color Adjustments"),
(&["Effect"], "Color Effects"),
(&["Effect"], "Convert to Shape"),
(&["Effect"], "Crop Marks"),
(&["Effect"], "Distort & Transform"),
(&["Effect"], "Path"),
(&["Effect"], "Path Effects"),
(&["Effect"], "Pathfinder"),
(&["Effect"], "Rasterize…"),
(&["Effect"], "Stylize"),
(&["Effect"], "SVG Filters"),
(&["Effect"], "Warp"),
(&["Effect"], "Effect Gallery…"),
(&["Effect"], "Artistic"),
(&["Effect"], "Blur"),
(&["Effect"], "Brush Strokes"),
(&["Effect"], "Distort"),
(&["Effect"], "Pixelate"),
(&["Effect"], "Sharpen"),
(&["Effect"], "Sketch"),
(&["Effect"], "Texture"),
(&["Effect"], "Video"),
(&["Effect"], "Plug-ins"),
(&["View"], "Outline"),
(&["View"], "Preview"),
(&["View"], "Pixel Preview"),
(&["View"], "Trim View"),
(&["View"], "Presentation Mode"),
(&["View"], "Screen Mode"),
(&["View"], "Proof Setup"),
(&["View"], "Zoom In"),
(&["View"], "Zoom Out"),
(&["View"], "Fit Artboard in Window"),
(&["View"], "Fit All in Window"),
(&["View"], "Actual Size"),
(&["View"], "Rotate View"),
(&["View"], "Rotate View to Selection"),
(&["View"], "Reset Rotate View"),
(&["View"], "Hide Edges"),
(&["View"], "Show Edges"),
(&["View"], "Hide Artboards"),
(&["View"], "Show Artboards"),
(&["View"], "Hide Template"),
(&["View"], "Show Template"),
(&["View"], "Rulers"),
(&["View"], "Hide Bounding Box"),
(&["View"], "Show Bounding Box"),
(&["View"], "Hide Text Threads"),
(&["View"], "Show Text Threads"),
(&["View"], "Hide Gradient Annotator"),
(&["View"], "Show Gradient Annotator"),
(&["View"], "Hide Corner Widget"),
(&["View"], "Show Corner Widget"),
(&["View"], "Show Live Paint Gaps"),
(&["View"], "Hide Live Paint Gaps"),
(&["View"], "Guides"),
(&["View"], "Smart Guides"),
(&["View"], "Perspective Grid"),
(&["View"], "Show Grid"),
(&["View"], "Hide Grid"),
(&["View"], "Snap to Grid"),
(&["View"], "Snap to Pixel"),
(&["View"], "Snap to Point"),
(&["View"], "Snap to Glyph"),
(&["View"], "Saved View"),
];
/// The command spec of plug-in `p`'s command `c`: its id, its label as menus show it (escaped and
/// capped), its menu (Object › Plug-ins › the plug-in's name, or Effect › Plug-ins › it for a live
/// effect: never a menu the manifest names) and its params description.
/// capped, and followed by the plug-in's name when it is listed in another menu), its menu
/// ([`placed_menu`], else Object › Plug-ins › the plug-in's name, or Effect › Plug-ins › it for a
/// live effect) and its params description.
fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec {
let m = p.manifest();
let id = command_id(&m.id, &c.id);
let label = c.shown_label();
let placed = placed_menu(p, c);
let label = if placed.is_some() { c.menu_label(&m.name) } else { c.shown_label() };
let top = if m.kind == Kind::Effect { "Effect" } else { "Object" };
let name = permissions::display_text(m.name.trim(), permissions::MAX_SHOWN_NAME);
let submenu = [top, "Plug-ins", name.as_str()];
let path: &[&str] = placed.unwrap_or(&submenu);
let mut fields =
String::from("ids?: [object id] (left out or null: the selection), params?: {…} (its parameters; or give them as top-level keys)");
let doc = m.for_command(c).params_doc();
@@ -518,11 +793,14 @@ fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec {
m.id, c.id
);
let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
let same = |s: &&&'static CommandSpec| s.id == id && s.label == label && s.menu == [top, "Plug-ins", name.as_str()] && s.params == params;
let same = |s: &&&'static CommandSpec| s.id == id && s.label == label && s.menu == path && s.params == params;
if let Some(s) = made.iter().find(same) {
return s;
}
let menu: &'static [&'static str] = Box::leak(vec![top, "Plug-ins", registry::intern(&name)].into_boxed_slice());
let menu: &'static [&'static str] = match placed {
Some(path) => path,
None => Box::leak(vec![top, "Plug-ins", registry::intern(&name)].into_boxed_slice()),
};
let spec: &'static CommandSpec = Box::leak(Box::new(CommandSpec {
id: registry::intern(&id),
label: registry::intern(&label),
@@ -1301,7 +1579,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List Plug-ins",
[],
None,
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
"{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.<id>), format? and extensions? (an exporter's or importer's format id, plugin.<id>, for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.<id>.<command id>, which runs it), label, params (doc), paramsSchema, menu?: {path: [menu label], after?: item label (escaped), placed?: false (it stays in its plug-in's submenu: its label reads like a built-in item or submenu of that menu or another plug-in command placed there)} (the menu its manifest places it in, see docs/plugins.md)}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}], leftOut} | null (under automation read roots, a folder outside them is null, and a failed file and a plug-in's source outside them are named by their file name), safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}",
always,
list
),
@@ -60,6 +60,7 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.pathtools.erase",
"addon.pathtools.expandDashes",
"addon.pathtools.extend",
"addon.pathtools.inscribedCircle",
"addon.pathtools.inspect",
"addon.pathtools.mergeEdge",
"addon.pathtools.removeKeepShape",
@@ -466,6 +467,7 @@ pub(super) const ALLOWED: &[&str] = &[
"path.moveAnchor",
"path.moveAnchors",
"path.quickPen",
"path.quickPenLength",
"path.rectCut",
"path.removeAnchor",
"path.removeAnchors",
+1
View File
@@ -140,6 +140,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[
p!("pasteOffset", "General", "", "Paste Offset", len(0.0, 1296.0, General)),
p!("disableAutoAddDelete", "General", "Options", "Disable Auto Add/Delete", bool),
p!("interpolateControlPoints", "General", "Options", "Interpolate Control Points When Moving Anchors", bool),
p!("deleteKeepsPathsJoined", "General", "Options", "Delete Removes Anchor Points and Keeps Paths Joined", bool),
p!("usePreciseCursors", "General", "Options", "Use Precise Cursors", bool),
p!("showToolTips", "General", "Options", "Show Tool Tips", bool),
p!("showToolCards", "General", "Options", "Show Tool Cards", bool),
+3 -2
View File
@@ -95,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List Script File Permissions",
[],
None,
"{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web)}",
"{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web)}; a missing grants file lists none, and one that is there but cannot be read, is too large, is not a grants file of this version or holds no list of grants, or whose lock cannot be taken, is an error (a grant in it that is not well formed is left out)",
always,
grants
),
@@ -369,7 +369,8 @@ fn grants(s: &mut Session, _: &Value) -> Result<Value> {
let Some(dir) = s.script_data_dir() else { return Ok(json!({"grants": [], "file": null})) };
let file = dir.with_file_name(script::files::GRANTS_FILE);
// A script or a granted path outside the automation read roots is named by its file name alone.
let mut grants = script::files::stored_grants(dir);
let mut grants =
script::files::stored_grants(dir).map_err(|e| EngineError::Other(format!("the script file permissions could not be read: {e}")))?;
for g in &mut grants {
for key in ["script", "path"] {
if let Some(name) = g[key].as_str().and_then(hidden_name) {
+44 -56
View File
@@ -17,6 +17,7 @@ use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_color::{Paint, Swatch, SwatchGroup, SwatchLibrary, default_swatches};
use vectorcraft_doc::pattern::pattern_paint;
use super::clipboard::resources::numbered_name;
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;
@@ -49,7 +50,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add to Swatches",
["Window", "Swatch Libraries"],
None,
"{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy), defaultsOnly?: bool (with apply: apply it to the defaults only, as paint.setFill does; the journal records it for swatches applied while the Live Paint Bucket is the active tool)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, skipping the names of the library's other swatches, and the pattern links to it → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}",
"{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy), defaultsOnly?: bool (with apply: apply it to the defaults only, as paint.setFill does; the journal records it for swatches applied while the Live Paint Bucket is the active tool)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, skipping the names of the library's other swatches, and the pattern links to it, not to a numbered copy that is the library's other swatch of that name; a swatch of a numbered library name that the art brings, such as a tint \"Ink 2\" or a pattern's swatch when its pattern comes in under another name, keeps that name when the document does not use it, and a pattern swatch or a pattern the art is painted with that comes in numbered skips the library's other names too → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}",
has_doc,
add
),
@@ -1029,55 +1030,27 @@ fn free_copy_in(taken: &mut HashSet<String>, base: &str, reserved: impl Fn(&str)
name
}
/// [`patternlib::import`] of pattern `pattern` of `src` into `d`, keeping the library's numbered
/// swatch names (the keys of `names`, such as "Ink 2") that `d` does not use for the library's own
/// swatches of those names, so that a color the art brings under a numbered name does not take one
/// of them. While the import runs, a placeholder swatch holds each such name the art does not
/// bring, and a copy of the library's color holds each one the art brings, which the art then
/// takes. The placeholders are removed before it returns, and so is a copy the art did not take;
/// a copy the art took is listed with the colors the import brought. Names of the patterns the
/// import brings are not held.
fn import_holding(
d: &mut vectorcraft_doc::Document,
src: &vectorcraft_doc::Document,
pattern: &str,
names: &HashMap<&str, &Swatch>,
) -> Result<(String, patternlib::SwatchNames, patternlib::SwatchNames)> {
let numbered = |n: &str| n.rsplit_once(' ').is_some_and(|(_, k)| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit()));
let taken = taken_names(d);
let mut free: Vec<&str> = names.keys().copied().filter(|n| numbered(n) && !taken.contains(*n)).collect();
free.sort_unstable();
let (mut held, mut copies): (Vec<Swatch>, Vec<Swatch>) = (vec![], vec![]);
if !free.is_empty() {
let brings = patternlib::brought_names(src, pattern);
let patterns = patternlib::brought_patterns(src, pattern);
for n in free.into_iter().filter(|n| !patterns.contains(*n)) {
if !brings.contains(n) {
held.push(Swatch { name: n.to_string(), paint: Paint::None, global: false, spot: false });
} else if let Some(w) = names.get(n).filter(|w| w.paint.color().is_some() && linked_names(&w.paint).is_empty()) {
copies.push((*w).clone());
}
/// The name of the document's swatch for library pattern swatch `w`, whose pattern came in as
/// `target`, the import having made swatch `made` for it (removed again). A numbered name skips
/// the names of the library's other swatches (`lib_by_name`), as for a color; so does a swatch
/// named after its pattern when the pattern's name is one of them. The swatch takes the library
/// swatch's numbered name when it is free and the library has no other swatch of that name, and leaves a
/// numbered name the library gives an earlier swatch to that one.
fn pattern_swatch_name(w: &Swatch, target: &str, made: Option<String>, taken: &mut HashSet<String>, lib_by_name: &HashMap<&str, &Swatch>) -> String {
let reserved = |n: &str| lib_by_name.contains_key(n);
let owns = lib_by_name.get(w.name.as_str()).is_some_and(|o| *o == w);
let named_after = matches!(&w.paint, Paint::Pattern { pattern, .. } if *pattern == w.name);
match made {
_ if named_after && owns && numbered_name(&w.name) && !taken.contains(&w.name) => w.name.clone(),
_ if !owns && numbered_name(&w.name) && !taken.contains(&w.name) => {
let mut held = taken.clone();
held.insert(w.name.clone());
free_copy_in(&mut held, &w.name, reserved)
}
Some(made) if named_after => made,
None if named_after && (target == w.name || !reserved(target)) => free_copy_in(taken, target, reserved),
_ => free_copy_in(taken, &w.name, reserved),
}
let start = d.swatches.len();
d.swatches.extend(held.iter().chain(&copies).cloned());
let imported = patternlib::import(d, src, pattern);
let used = |n: &str| {
imported
.as_ref()
.is_ok_and(|(_, colors, took)| !colors.iter().any(|(from, _)| from == n) && !took.iter().any(|(from, to)| from == n && to != n))
};
let used: HashSet<String> = copies.iter().map(|w| w.name.clone()).filter(|n| used(n)).collect();
let mut i = 0;
d.swatches.retain(|w| {
i += 1;
let ours = held.iter().chain(&copies).any(|h| h.name == w.name && h.paint == w.paint);
!(i > start && ours && !used.contains(&w.name))
});
let (target, mut colors, mut took) = imported?;
took.retain(|(from, _)| !used.contains(from));
colors.extend(copies.into_iter().map(|w| w.name).filter(|n| used.contains(n)).map(|n| (n.clone(), n)));
Ok((target, colors, took))
}
/// Link the swatches of `d` that `pending` names (document name, library swatch) to their colors
@@ -1202,6 +1175,25 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
for w in lib.swatches.iter().chain(lib.groups.iter().flat_map(|g| &g.swatches)) {
lib_by_name.entry(w.name.as_str()).or_insert(w);
}
// A swatch a pattern's art brings under a numbered name skips the library's numbered names,
// which a later add looks up as those swatches'. Only the names a picked pattern's swatches and
// patterns can come in under, their own or one numbered after them, are needed.
let mut brings_names: HashSet<String> = HashSet::new();
if let Some(src) = patterns.as_ref().filter(|_| lib_by_name.keys().any(|n| numbered_name(n))) {
let picked_patterns: BTreeSet<&str> = picked
.iter()
.filter_map(|(_, w)| match &w.paint {
Paint::Pattern { pattern, .. } => Some(pattern.as_str()),
_ => None,
})
.collect();
for pattern in picked_patterns {
brings_names.extend(patternlib::brought_resource_names(src, pattern));
}
}
let can_take = |n: &str| brings_names.contains(n) || n.rsplit_once(' ').is_some_and(|(base, _)| brings_names.contains(base));
let lib_names: patternlib::Reserved =
Arc::new(lib_by_name.iter().filter(|(n, _)| numbered_name(n) && can_take(n)).map(|(n, w)| (n.to_string(), (*w).clone())).collect());
let group_names: HashSet<&str> = d.swatch_groups.iter().map(|g| g.name.as_str()).collect();
// A color whose name the document gives another color, or a color group, is the numbered copy
// of it that an earlier add or a pattern's art brought in, when that copy is the same color. A
@@ -1233,7 +1225,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(src) = &patterns {
for (_, w) in &picked {
let Paint::Pattern { pattern, .. } = &w.paint else { continue };
present.entry(pattern.as_str()).or_insert_with(|| patternlib::present_pattern(d, src, pattern));
present.entry(pattern.as_str()).or_insert_with(|| patternlib::present_pattern(d, src, pattern, &lib_names));
}
}
// Whether the document's swatch `x` of the name of library swatch `w` is `w` with its colors
@@ -1438,7 +1430,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
let mut learned = vec![];
if pending.iter().any(|(_, w)| linked_names(&w.paint).iter().any(waited)) {
let mut probe = d.clone();
let (_, colors, took) = import_holding(&mut probe, src, pattern, &lib_by_name)?;
let (_, colors, took) = patternlib::import(&mut probe, src, pattern, &lib_names)?;
for (from, to) in colors_of(&probe, &colors, &took) {
if let std::collections::hash_map::Entry::Vacant(e) = links.entry(from.clone()) {
e.insert(to);
@@ -1448,7 +1440,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
}
let settled = settle(d, &mut pending, &links);
let had = taken_names(d);
let (target, colors, took) = import_holding(d, src, pattern, &lib_by_name)?;
let (target, colors, took) = patternlib::import(d, src, pattern, &lib_names)?;
// Those colors are the ones the library's tints of them link to, unless the
// document already has one for them. A name the copy gave that the import
// into the document did not give is replaced, and the tints linked to it are
@@ -1483,11 +1475,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
d.swatches.retain(|x| x.name != *made);
}
taken = taken_names(d);
let name = match made {
Some(made) if w.name == *pattern => made,
None if w.name == *pattern => d.free_swatch_name(&target),
_ => free_in(&mut taken, &w.name),
};
let name = pattern_swatch_name(w, &target, made, &mut taken, &lib_by_name);
taken.insert(name.clone());
// The library swatch's placement of its pattern is kept.
let paint = match &w.paint {
+10 -3
View File
@@ -1895,14 +1895,21 @@ enum Step {
/// The Type tool's selected text while it edits (its typing session ends first: one undo step,
/// with typing that Real-time Drawing off left unapplied applied first).
pub(crate) fn editing_range(s: &mut Session) -> Result<Option<(NodeId, usize, usize)>> {
let o = s.tool_options();
let Some(id) = o.get("editing").and_then(Value::as_u64).map(NodeId) else { return Ok(None) };
let Some(range) = selected_range(s) else { return Ok(None) };
if super::edit::typing_in_progress(s) {
s.set_tool_option("commitTyping", &Value::Bool(true));
super::edit::settle_interaction(s)?;
}
Ok(Some(range))
}
/// The Type tool's selected text while it edits, as [`editing_range`] reads it, with its typing
/// session left running.
pub(crate) fn selected_range(s: &Session) -> Option<(NodeId, usize, usize)> {
let o = s.tool_options();
let id = o.get("editing").and_then(Value::as_u64).map(NodeId)?;
let at = |k: &str| byte_param(&o, k).unwrap_or(0);
Ok(Some((id, at("start"), at("end"))))
Some((id, at("start"), at("end")))
}
/// The frames of the story whose whole text the Type tool has selected after Select All in a
+13
View File
@@ -107,6 +107,19 @@ pub struct Session {
/// The selection tool chosen last (Selection, Direct Selection or Group Selection): the one Cmd
/// lends the other tools. None until one is chosen.
pub(crate) last_selection_tool: Option<&'static str>,
/// Direct Selection or Group Selection, whichever was chosen last: the one Cmd lends the
/// Selection tool. None until one is chosen.
pub(crate) last_part_selection_tool: Option<&'static str>,
/// The selection tool Cmd lent the last press, which also takes the double-click or
/// triple-click that follows it, with the uid of the document and the id of the tool it was
/// lent from: a follow-up in another document, after a tool switch (also one back to the same
/// tool) or after the tool starts afresh is not lent. None when the press was not lent.
pub(crate) press_lent: Option<(Option<u64>, &'static str, &'static str)>,
/// The selection tool a Cmd press would borrow at the pointer, as [`Session::hover_tool_at`]
/// or [`Session::cursor`] last found it with Cmd held (None inside when it found none), with
/// the document state, active tool and keys it was found for. None when it was last asked
/// without Cmd.
pub(crate) hover_lent: Option<(tooling::HoverKey, Option<&'static str>)>,
pub(crate) last_view: ViewInfo,
/// The selection tools' measurements for the active document as it is: a pointer move or a
/// cursor asked for again over an unchanged document and selection measures nothing again.
+7
View File
@@ -55,6 +55,12 @@ pub struct Prefs {
/// re-mapped by the turn, scale and move that take its old ends to its new ends. Off (the
/// default), the handles of a moved anchor move with it and the other handles stay.
pub interpolate_control_points: bool,
/// General › Delete Removes Anchor Points and Keeps Paths Joined: the default of the
/// `keepJoined` param of `edit.clear` (the Delete and Backspace keys and Edit › Clear). On,
/// Clear removes the direct-selected anchors of a path as Remove Anchor Points does, refitting
/// the curve around each one, instead of deleting them with their segments. Off (the default),
/// Clear opens the path there.
pub delete_keeps_paths_joined: bool,
pub use_precise_cursors: bool,
pub show_tool_tips: bool,
/// General › Show Tool Cards: with tool tips on, a tool button's tool tip is a card with what the
@@ -479,6 +485,7 @@ impl Default for Prefs {
corner_radius: 12.0,
disable_auto_add_delete: false,
interpolate_control_points: false,
delete_keeps_paths_joined: false,
use_precise_cursors: false,
show_tool_tips: true,
show_tool_cards: false,
+16 -8
View File
@@ -923,8 +923,15 @@ fn read_head(real: &Path, max: usize) -> std::io::Result<Vec<u8>> {
/// that is not well formed is left out. It is read under [`lock_store`]'s lock, so it is read
/// between two changes, and none are read when the lock cannot be taken.
fn read_store(store: &Path) -> Vec<serde_json::Value> {
let Ok(_lock) = lock_store(store) else { return Vec::new() };
load_store(store, false).unwrap_or_default()
list_store(store).unwrap_or_default()
}
/// The grants [`read_store`] reads; none when the grants file is missing, and `Err` when the lock
/// cannot be taken or the file is there but cannot be read, is too large, is not a grants file of
/// this version or holds no list of grants.
fn list_store(store: &Path) -> std::io::Result<Vec<serde_json::Value>> {
let _lock = lock_store(store)?;
load_store(store, false)
}
/// The grants the grants file at `store` holds, to change and write back; none when it is missing,
@@ -940,7 +947,8 @@ fn try_read_store(store: &Path) -> std::io::Result<Vec<serde_json::Value>> {
fn load_store(store: &Path, strict: bool) -> std::io::Result<Vec<serde_json::Value>> {
let bytes = match read_head(store, MAX_STORE_BYTES) {
Ok(bytes) => bytes,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
// A link whose target is missing is there but cannot be read.
Err(e) if e.kind() == std::io::ErrorKind::NotFound && std::fs::symlink_metadata(store).is_err() => return Ok(Vec::new()),
Err(e) => return Err(e),
};
if bytes.len() > MAX_STORE_BYTES {
@@ -958,14 +966,14 @@ fn load_store(store: &Path, strict: bool) -> std::io::Result<Vec<serde_json::Val
&& g["write"].is_boolean()
&& g["folder"].is_boolean()
};
let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?;
if strict {
let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?;
if grants.len() > MAX_STORED_GRANTS || !grants.iter().all(valid) {
return Err(std::io::Error::other("the grants file holds a grant that cannot be read"));
}
return Ok(grants.clone());
}
Ok(v["grants"].as_array().map(|a| a.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()).unwrap_or_default())
Ok(grants.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect())
}
/// The number in the name of the next file [`write_store`] writes before it takes the grants file's
@@ -1065,9 +1073,9 @@ fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
}
/// The grants the grants file beside the data folder `data_dir` keeps: each script, the SHA-256 of
/// its text, the path and whether it may be written (`script.grants`).
pub(crate) fn stored_grants(data_dir: &Path) -> Vec<serde_json::Value> {
read_store(&data_dir.with_file_name(GRANTS_FILE))
/// its text, the path and whether it may be written (`script.grants`); as [`list_store`] reads them.
pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result<Vec<serde_json::Value>> {
list_store(&data_dir.with_file_name(GRANTS_FILE))
}
/// Removes from the grants file beside `data_dir` the grants of the script `script` and of the path
+4
View File
@@ -69,6 +69,9 @@ impl Session {
selection_at_lend: None,
lent_selection: None,
last_selection_tool: None,
last_part_selection_tool: None,
press_lent: None,
hover_lent: None,
last_view: ViewInfo::default(),
preview_memo: Default::default(),
depth: 0,
@@ -211,6 +214,7 @@ impl Session {
return;
}
self.press_type_selection = None;
self.press_lent = None;
let view = self.last_view;
// The edit the tool computes on another thread and the input held for it belong to the
// document being left. The switch goes on whatever they did, as for the deactivation.
+2
View File
@@ -49,6 +49,7 @@ mod curvature_circle;
mod cut;
mod dashalign;
mod dcs;
mod delete_keeps_joined;
mod distort;
mod docsetup;
mod document_close;
@@ -123,6 +124,7 @@ mod outlineobject;
pub(super) mod outlinestroke;
mod overprint;
mod package;
mod paintopacity;
mod paintproxy;
mod panelcmds;
mod paragraphs;
+9
View File
@@ -776,6 +776,15 @@ fn overprint_black_and_print_fixes_reach_a_colorized_images_color() {
let v = s.execute("addon.color.printFixes", &json!({"removeWhiteOverprint": true})).unwrap();
assert_eq!(v["whiteOverprintRemoved"], 1, "{v}");
assert!(!overprints(&s), "white knocks out again");
// A white spot ink is an ink: Remove White Overprint leaves its overprint.
s.execute("swatch.new", &json!({"name": "Opaque White", "color": {"c": 0, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("paint.setFill", &json!({"swatch": "Opaque White"})).unwrap();
s.execute("object.setOverprint", &json!({"fill": true})).unwrap();
assert!(overprints(&s), "the spot white overprints");
let v = s.execute("addon.color.printFixes", &json!({"removeWhiteOverprint": true})).unwrap();
assert_eq!(v["whiteOverprintRemoved"], 0, "{v}");
assert!(overprints(&s), "the spot white keeps overprinting");
}
/// A flattening for a file that writes colorized images in their ink (EPS) keeps the image, and
@@ -0,0 +1,227 @@
//! General › Delete Removes Anchor Points and Keeps Paths Joined (`deleteKeepsPathsJoined`). With
//! it on, Delete (`edit.clear`) removes the direct-selected anchors of a path as Remove Anchor
//! Points does, without opening the path. Off (the default), Delete removes them with their
//! segments.
use serde_json::json;
use vectorcraft_geom::{PathData, Point};
use super::history;
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
s
}
fn keep_joined(s: &mut Session, on: bool) {
s.execute("prefs.set", &json!({"key": "deleteKeepsPathsJoined", "value": on})).unwrap();
}
fn path_of(s: &Session, id: NodeId) -> Option<PathData> {
s.doc().unwrap().doc.node(id).and_then(|n| n.path_data().cloned())
}
fn points(s: &Session, id: NodeId) -> Vec<Point> {
path_of(s, id).unwrap().subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect()
}
fn create(s: &mut Session, anchors: serde_json::Value, closed: bool) -> NodeId {
NodeId(s.execute("path.create", &json!({ "anchors": anchors, "closed": closed })).unwrap()["id"].as_u64().unwrap())
}
fn square(s: &mut Session, x: f64) -> NodeId {
create(s, json!([{"x": x, "y": 100}, {"x": x + 100.0, "y": 100}, {"x": x + 100.0, "y": 200}, {"x": x, "y": 200}]), true)
}
fn line(s: &mut Session, y: f64) -> NodeId {
create(s, json!([{"x": 100, "y": y}, {"x": 150, "y": y - 20.0}, {"x": 200, "y": y}, {"x": 250, "y": y + 20.0}, {"x": 300, "y": y}]), false)
}
fn select(s: &mut Session, id: NodeId, anchors: serde_json::Value, mode: &str) {
s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors, "mode": mode})).unwrap();
}
fn objects(s: &Session) -> usize {
s.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, |c| c.len())).sum()
}
#[test]
fn off_by_default_delete_opens_a_closed_path() {
let mut s = session();
assert!(!s.prefs.delete_keeps_paths_joined);
let id = square(&mut s, 100.0);
select(&mut s, id, json!([[0, 1]]), "set");
s.execute("edit.clear", &json!({})).unwrap();
let path = path_of(&s, id).unwrap();
assert!(!path.subpaths[0].closed, "the path opens where the anchor was");
assert_eq!(path.subpaths[0].anchors.len(), 3);
}
#[test]
fn with_the_preference_on_delete_keeps_a_closed_path_closed_and_selects_the_next_anchor() {
let mut s = session();
keep_joined(&mut s, true);
let id = square(&mut s, 100.0);
select(&mut s, id, json!([[0, 1]]), "set");
let before = history(&s).0;
s.execute("edit.clear", &json!({})).unwrap();
assert_eq!(history(&s).0, before + 1, "one undo step");
let path = path_of(&s, id).unwrap();
assert_eq!(path.subpaths.len(), 1);
assert!(path.subpaths[0].closed, "the path stays closed");
assert!(!points(&s, id).contains(&Point::new(200.0, 100.0)), "the selected anchor is gone");
let st = s.doc().unwrap();
assert_eq!(st.selection.objects, vec![id], "the path stays selected");
assert_eq!(st.selection.anchors[&id], [(0, 1)].into(), "the anchor after the removed one is selected");
// A second Delete goes on along the path.
s.execute("edit.clear", &json!({})).unwrap();
assert_eq!(points(&s, id), vec![Point::new(100.0, 100.0), Point::new(100.0, 200.0)]);
}
#[test]
fn an_open_path_loses_an_end_anchor_and_an_interior_anchor_without_splitting() {
let mut s = session();
keep_joined(&mut s, true);
let id = line(&mut s, 300.0);
select(&mut s, id, json!([[0, 0], [0, 2]]), "set");
s.execute("edit.clear", &json!({})).unwrap();
let path = path_of(&s, id).unwrap();
assert_eq!(path.subpaths.len(), 1, "one piece");
assert!(!path.subpaths[0].closed);
assert_eq!(
points(&s, id),
vec![Point::new(150.0, 280.0), Point::new(250.0, 320.0), Point::new(300.0, 300.0)],
"the path is shorter at its start"
);
assert_eq!(objects(&s), 1, "no new object");
assert_eq!(s.doc().unwrap().selection.anchors[&id], [(0, 1)].into(), "the anchor after the last removed one is selected");
// Removing the last anchor of an open path selects the one before it.
select(&mut s, id, json!([[0, 2]]), "set");
s.execute("edit.clear", &json!({})).unwrap();
assert_eq!(points(&s, id), vec![Point::new(150.0, 280.0), Point::new(250.0, 320.0)], "the path is shorter at its end");
assert_eq!(s.doc().unwrap().selection.anchors[&id], [(0, 1)].into(), "the new end anchor is selected");
}
#[test]
fn a_subpath_left_with_one_anchor_goes_and_the_path_stays_selected_whole() {
let mut s = session();
keep_joined(&mut s, true);
let id = square(&mut s, 100.0);
let sq = json!({"closed": true, "anchors": [{"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 200, "y": 200}, {"x": 100, "y": 200}]});
let pair = json!({"closed": false, "anchors": [{"x": 300, "y": 100}, {"x": 400, "y": 100}]});
s.execute("path.setAnchors", &json!({"id": id.0, "subpaths": [sq, pair]})).unwrap();
select(&mut s, id, json!([[1, 0]]), "set");
s.execute("edit.clear", &json!({})).unwrap();
let path = path_of(&s, id).unwrap();
assert_eq!(path.subpaths.len(), 1, "the subpath left with one anchor goes");
assert!(path.subpaths[0].closed && path.subpaths[0].anchors.len() == 4, "the other subpath is untouched");
let st = s.doc().unwrap();
assert_eq!(st.selection.objects, vec![id], "the path stays selected");
assert!(st.selection.anchors.get(&id).is_none_or(|a| a.is_empty()), "no anchor is left to go on from");
}
#[test]
fn a_path_left_with_fewer_than_two_anchors_is_deleted() {
let mut s = session();
keep_joined(&mut s, true);
let id = create(&mut s, json!([{"x": 100, "y": 100}, {"x": 200, "y": 100}]), false);
let other = square(&mut s, 400.0);
select(&mut s, id, json!([[0, 1]]), "set");
select(&mut s, other, json!([[0, 0]]), "add");
s.execute("edit.clear", &json!({})).unwrap();
assert!(path_of(&s, id).is_none(), "a single anchor is no path");
assert!(path_of(&s, other).unwrap().subpaths[0].closed, "the other path keeps its other anchors joined");
assert_eq!(s.doc().unwrap().selection.objects, vec![other]);
}
#[test]
fn several_paths_and_an_object_selected_whole_change_in_one_undo_step() {
let mut s = session();
keep_joined(&mut s, true);
let (a, b, whole) = (square(&mut s, 100.0), line(&mut s, 400.0), square(&mut s, 500.0));
select(&mut s, a, json!([[0, 0]]), "set");
select(&mut s, b, json!([[0, 1], [0, 3]]), "add");
s.execute("select.add", &json!({"ids": [whole.0]})).unwrap();
let doc = s.doc().unwrap().doc.clone();
let before = history(&s).0;
s.execute("edit.clear", &json!({})).unwrap();
assert_eq!(history(&s).0, before + 1, "one undo step");
assert!(path_of(&s, whole).is_none(), "the object selected whole is deleted");
assert!(path_of(&s, a).unwrap().subpaths[0].closed);
assert_eq!(path_of(&s, a).unwrap().subpaths[0].anchors.len(), 3);
assert_eq!(points(&s, b), vec![Point::new(100.0, 400.0), Point::new(200.0, 400.0), Point::new(300.0, 400.0)]);
let st = s.doc().unwrap();
assert!(st.selection.anchors.contains_key(&a) && st.selection.anchors.contains_key(&b), "both paths keep an anchor selected");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().doc, doc, "Undo restores every path");
}
#[test]
fn a_compound_path_keeps_its_members_and_loses_one_left_with_no_segment() {
let mut s = session();
keep_joined(&mut s, true);
let (outer, inner) = (square(&mut s, 100.0), create(&mut s, json!([{"x": 130, "y": 150}, {"x": 170, "y": 150}]), false));
s.execute("select.set", &json!({"ids": [outer.0, inner.0]})).unwrap();
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
select(&mut s, outer, json!([[0, 2]]), "set");
select(&mut s, inner, json!([[0, 0]]), "add");
s.execute("edit.clear", &json!({})).unwrap();
let d = &s.doc().unwrap().doc;
assert!(d.node(inner).is_none(), "the member left with one anchor goes");
assert_eq!(d.parent_of(outer), Some(compound), "the other member stays in the compound path");
assert!(path_of(&s, outer).unwrap().subpaths[0].closed);
assert_eq!(path_of(&s, outer).unwrap().subpaths[0].anchors.len(), 3);
}
#[test]
fn a_selected_segment_is_still_cut() {
let mut s = session();
keep_joined(&mut s, true);
let id = square(&mut s, 100.0);
s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 0]]})).unwrap();
s.execute("edit.clear", &json!({})).unwrap();
let path = path_of(&s, id).unwrap();
assert!(!path.subpaths[0].closed, "the segment's connection is removed");
assert_eq!(path.subpaths[0].anchors.len(), 4, "every anchor stays");
}
#[test]
fn the_keep_joined_param_overrides_the_preference_and_must_be_a_boolean() {
let mut s = session();
let id = square(&mut s, 100.0);
select(&mut s, id, json!([[0, 1]]), "set");
assert!(s.execute("edit.clear", &json!({"keepJoined": "yes"})).is_err());
assert_eq!(path_of(&s, id).unwrap().subpaths[0].anchors.len(), 4, "a refused call changes nothing");
s.execute("edit.clear", &json!({"keepJoined": true})).unwrap();
assert!(path_of(&s, id).unwrap().subpaths[0].closed);
keep_joined(&mut s, true);
s.execute("edit.clear", &json!({"keepJoined": false})).unwrap();
assert!(!path_of(&s, id).unwrap().subpaths[0].closed, "false opens the path with the preference on");
}
#[test]
fn a_replay_removes_anchors_as_the_recorded_step_did() {
let mut s = session();
keep_joined(&mut s, true);
let id = square(&mut s, 100.0);
select(&mut s, id, json!([[0, 1]]), "set");
let start = s.journal.len();
s.execute("edit.clear", &json!({})).unwrap();
let removed = path_of(&s, id);
assert!(removed.as_ref().is_some_and(|p| p.subpaths[0].closed), "the path stays closed");
let (cmd, params) = s.journal.since(start).last().cloned().unwrap();
assert_eq!(params["keepJoined"], json!(true), "{cmd}: journaled");
s.execute("edit.undo", &json!({})).unwrap();
keep_joined(&mut s, false);
select(&mut s, id, json!([[0, 1]]), "set");
s.replay(&cmd, &params).unwrap();
assert_eq!(path_of(&s, id), removed);
// A step saved before the preference existed has no `keepJoined` and still opens the path.
s.execute("edit.undo", &json!({})).unwrap();
keep_joined(&mut s, true);
select(&mut s, id, json!([[0, 1]]), "set");
s.replay("edit.clear", &json!({})).unwrap();
assert!(!path_of(&s, id).unwrap().subpaths[0].closed);
}
+7
View File
@@ -482,6 +482,13 @@ fn discard_white_overprint_keeps_white_overprints_in_overprint_preview() {
s.execute("document.setup", &json!({"discardWhiteOverprint": false})).unwrap();
let [r, g, b, _] = centre(&s);
assert!(r > 200 && g < 60 && b < 60, "a white overprint vanishes: {:?}", [r, g, b]);
// A white spot ink is an ink: it overprints with the option on too.
s.execute("document.setup", &json!({"discardWhiteOverprint": true})).unwrap();
s.execute("swatch.new", &json!({"name": "Opaque White", "color": {"c": 0, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap();
s.execute("select.set", &json!({"ids": [white]})).unwrap();
s.execute("paint.setFill", &json!({"swatch": "Opaque White"})).unwrap();
let [r, g, b, _] = centre(&s);
assert!(r > 200 && g < 60 && b < 60, "the spot white overprints: {:?}", [r, g, b]);
}
#[test]
+454
View File
@@ -4860,6 +4860,460 @@ fn cmd_alt_lends_group_selection_while_direct_selection_is_active() {
s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 80.0).with_mods(cmd_alt), v).unwrap();
}
#[test]
fn cmd_lends_the_selection_tool_direct_selection_or_group_selection_chosen_last() {
// Cmd held with the Selection tool: Direct Selection takes the press until the release, so a
// Cmd-click picks one path inside a group where a plain click picks the group.
let (none, cmd) = (Mods::default(), Mods { cmd: true, ..Mods::default() });
let v = view();
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0);
let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap());
s.execute("select.none", &json!({})).unwrap();
s.select_tool("selection", v).unwrap();
assert_eq!(s.lent_tool_id(&none), None);
assert_eq!(s.lent_tool_id(&cmd), Some("directSelection"));
assert_eq!(s.shown_tool_id(&cmd), "directSelection");
assert_eq!(s.shown_tool_id(&none), "selection");
s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 150.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "directSelection");
s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 150.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "selection");
let picked = &s.active().unwrap().selection;
assert!(picked.contains(a) && !picked.contains(group), "the Cmd-click picks the path, not its group");
s.execute("select.none", &json!({})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 150.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 150.0), v).unwrap();
assert!(s.active().unwrap().selection.contains(group), "a plain click picks the group");
// Cmd pressed once a drag is under way lends nothing: the pointer and the named tool stay.
s.pointer(&PointerEvent::new(PointerKind::Down, 600.0, 500.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 650.0, 550.0), v).unwrap();
assert_eq!(s.cursor(Point::new(650.0, 550.0), cmd, v), s.cursor(Point::new(650.0, 550.0), none, v));
assert_eq!(s.shown_tool_id(&cmd), "selection");
s.pointer(&PointerEvent::new(PointerKind::Up, 650.0, 550.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "selection");
// Group Selection lends the Selection tool, and once chosen, is what the Selection tool borrows.
s.select_tool("groupSelection", v).unwrap();
assert_eq!(s.lent_tool_id(&cmd), Some("selection"));
s.select_tool("selection", v).unwrap();
assert_eq!(s.lent_tool_id(&cmd), Some("groupSelection"));
s.select_tool("directSelection", v).unwrap();
s.select_tool("selection", v).unwrap();
assert_eq!(s.lent_tool_id(&cmd), Some("directSelection"));
}
#[test]
fn a_cmd_double_click_goes_to_the_tool_the_clicks_went_to() {
// With the Selection tool, Cmd-clicks go to Direct Selection, and so does the double-click
// after them: it does not isolate the group as the Selection tool's double-click would.
let cmd = Mods { cmd: true, ..Mods::default() };
let v = view();
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0);
s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("select.none", &json!({})).unwrap();
s.select_tool("selection", v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
s.pointer(&PointerEvent::new(kind, 150.0, 150.0).with_mods(cmd), v).unwrap();
}
assert_eq!(s.tool_id(), "selection");
assert_eq!(s.doc().unwrap().isolation, None, "Direct Selection's double-click does not isolate the group");
// With Group Selection chosen last, the second click selects the group, and the double-click
// still goes to Group Selection, as both clicks did.
s.select_tool("groupSelection", v).unwrap();
s.select_tool("selection", v).unwrap();
s.execute("select.none", &json!({})).unwrap();
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
s.pointer(&PointerEvent::new(kind, 150.0, 150.0).with_mods(cmd), v).unwrap();
}
assert_eq!(s.doc().unwrap().isolation, None, "Group Selection's double-click does not isolate the group");
s.execute("select.none", &json!({})).unwrap();
// A plain double-click is the Selection tool's: it isolates the group.
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
s.pointer(&PointerEvent::new(kind, 150.0, 150.0), v).unwrap();
}
assert!(s.doc().unwrap().isolation.is_some());
}
#[test]
fn a_cmd_double_click_after_a_tool_switch_goes_to_the_new_tool() {
// With the Selection tool, a Cmd-click on type goes to Direct Selection, and so does the
// Cmd double-click after it, which edits the type. Once another tool is chosen, the
// double-click is that tool's: Group Selection's does not edit the type.
let cmd = Mods { cmd: true, ..Mods::default() };
let v = view();
let mut s = session();
let id = NodeId(s.execute("text.create", &json!({"x": 100, "y": 200, "size": 48, "text": "Type"})).unwrap()["id"].as_u64().unwrap());
let c = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().center();
let clicks = |s: &mut Session, then: Option<&str>| {
s.execute("select.none", &json!({})).unwrap();
s.select_tool("selection", v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, c.x, c.y).with_mods(cmd), v).unwrap();
}
if let Some(tool) = then {
s.select_tool(tool, v).unwrap();
}
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, c.x, c.y).with_mods(cmd), v).unwrap()
};
assert_eq!(clicks(&mut s, None), [UiRequest::SwitchTool("type".into())], "Direct Selection's double-click edits the type");
assert_eq!(clicks(&mut s, Some("groupSelection")), [], "Group Selection's double-click does not");
assert_eq!(s.tool_id(), "groupSelection");
}
#[test]
fn a_cmd_double_click_after_switching_away_and_back_goes_to_the_active_tool() {
// A Cmd-click with the Selection tool goes to Direct Selection. After a switch to another tool
// and back to the Selection tool, or a fresh start of the tool (another view of the document),
// the Cmd double-click is the Selection tool's: it isolates the group.
let cmd = Mods { cmd: true, ..Mods::default() };
let v = view();
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0);
let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0);
s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap();
for reset in [false, true] {
s.execute("select.none", &json!({})).unwrap();
s.select_tool("selection", v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 150.0, 150.0).with_mods(cmd), v).unwrap();
}
if reset {
s.reset_tool();
} else {
s.select_tool("rectangle", v).unwrap();
s.select_tool("selection", v).unwrap();
}
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 150.0, 150.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "selection");
assert!(s.doc().unwrap().isolation.is_some(), "the Selection tool's double-click isolates the group (reset: {reset})");
s.execute("object.exitIsolation", &json!({})).unwrap();
}
}
#[test]
fn a_cmd_press_on_a_selected_object_keeps_select_behind() {
// Over a selected object, a Cmd-click with the Selection tool selects the object behind it;
// with Select Behind off, Direct Selection takes the press there too.
let cmd = Mods { cmd: true, ..Mods::default() };
let v = view();
let mut s = session();
let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
s.select_tool("selection", v).unwrap();
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
// The canvas shows the marks of the tool a press at the pointer takes, and the status bar and
// the help bar name it.
s.cursor(Point::new(200.0, 200.0), cmd, v);
assert_eq!(s.hover_tool_id(&cmd), "selection");
assert_eq!(s.shown_tool_id(&cmd), "selection", "the press selects behind: nothing is lent");
s.cursor(Point::new(500.0, 500.0), cmd, v);
assert_eq!(s.hover_tool_id(&cmd), "directSelection");
assert_eq!(s.shown_tool_id(&cmd), "directSelection");
// The bounding box's top middle handle, on the middle of the top segment: the press is lent.
assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 150.0)), &cmd, v), "directSelection", "on a box handle");
// Turning Select Behind off changes what the bars name over the selection.
s.cursor(Point::new(200.0, 200.0), cmd, v);
s.prefs.ctrl_click_selects_behind = false;
assert_eq!(s.shown_tool_id(&cmd), "directSelection");
s.prefs.ctrl_click_selects_behind = true;
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "selection");
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap();
let picked = &s.active().unwrap().selection;
assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind");
// On a selected object's anchor, Direct Selection takes the press.
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 250.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "directSelection");
s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 250.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "selection");
s.prefs.ctrl_click_selects_behind = false;
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "directSelection");
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "selection");
}
#[test]
fn a_cmd_press_on_a_wide_strokes_outer_half_selects_behind() {
// Without Use Preview Bounds the bounding box leaves out the outer half of a wide stroke, which
// the Selection tool still hits: a Cmd press there selects the object behind.
let cmd = Mods { cmd: true, ..Mods::default() };
let v = view();
let mut s = session();
assert!(!s.prefs.use_preview_bounds);
let back = rect(&mut s, 50.0, 50.0, 300.0, 300.0);
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
s.execute("stroke.set", &json!({"ids": [front.0], "weight": 40})).unwrap();
s.select_tool("selection", v).unwrap();
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
// 15 pt outside the path, on its stroke.
let at = Point::new(200.0, 135.0);
assert_eq!(s.hover_tool_at(Some(at), &cmd, v), "selection", "the press selects behind");
s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "selection");
s.pointer(&PointerEvent::new(PointerKind::Up, at.x, at.y).with_mods(cmd), v).unwrap();
let picked = &s.active().unwrap().selection;
assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind");
}
#[test]
fn a_cmd_press_on_a_lone_selected_object_is_lent() {
// With nothing behind the selected object, there is nothing to select behind: Direct Selection
// takes the press.
let cmd = Mods { cmd: true, ..Mods::default() };
let v = view();
let mut s = session();
let lone = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
s.select_tool("selection", v).unwrap();
s.execute("select.set", &json!({"ids": [lone.0]})).unwrap();
assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "directSelection");
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "directSelection");
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "selection");
}
#[test]
fn a_layer_effect_that_moves_art_moves_where_a_cmd_press_selects_behind() {
// A layer effect draws the selected object 250 pt to the right of its path, over the object
// behind it: a Cmd press where it is drawn selects behind. A drop shadow there is not hit, so
// the press is lent. Outline view hits the path where it is, and Preview afterwards still finds
// the moved art.
let cmd = Mods { cmd: true, ..Mods::default() };
let v = view();
let outline = ViewInfo { outline: true, ..view() };
let drawn = Point::new(450.0, 200.0);
// On both rectangles' top edges, which Outline view hits, away from the box's handles.
let path = Point::new(170.0, 150.0);
for effect in ["distort.transform", "stylize.dropShadow"] {
let mut s = session();
let back = rect(&mut s, 50.0, 150.0, 700.0, 300.0);
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
let layer = s.doc().unwrap().doc.layers[0].id;
let params = if effect == "distort.transform" { json!({"moveH": 250}) } else { json!({"x": 250, "y": 0, "blur": 0}) };
s.execute("effect.apply", &json!({"effect": effect, "params": params, "ids": [layer.0], "item": null})).unwrap();
s.select_tool("selection", v).unwrap();
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
// The back rectangle is drawn moved too, so it is under both points.
if effect == "distort.transform" {
assert_eq!(s.hover_tool_at(Some(path), &cmd, outline), "selection", "Outline view: on the path");
assert_eq!(s.hover_tool_at(Some(drawn), &cmd, v), "selection", "Preview: where the effect draws it");
s.pointer(&PointerEvent::new(PointerKind::Down, drawn.x, drawn.y).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "selection");
s.pointer(&PointerEvent::new(PointerKind::Up, drawn.x, drawn.y).with_mods(cmd), v).unwrap();
let picked = &s.active().unwrap().selection;
assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind");
} else {
assert_eq!(s.hover_tool_at(Some(drawn), &cmd, v), "directSelection", "on the shadow");
}
}
}
#[test]
fn repeated_cmd_clicks_select_behind_a_group_whose_member_is_selected() {
// The first Cmd-click on an unselected group lends Direct Selection, which selects the path
// under the pointer. The group holds that selected path, so the next Cmd-click there selects
// the object behind the group.
let cmd = Mods { cmd: true, ..Mods::default() };
let v = view();
let mut s = session();
let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
let a = rect(&mut s, 150.0, 150.0, 40.0, 40.0);
let b = rect(&mut s, 210.0, 150.0, 40.0, 40.0);
let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap());
s.execute("select.none", &json!({})).unwrap();
s.select_tool("selection", v).unwrap();
let click = |s: &mut Session| {
s.pointer(&PointerEvent::new(PointerKind::Down, 170.0, 170.0).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 170.0, 170.0).with_mods(cmd), v).unwrap();
};
click(&mut s);
let picked = &s.active().unwrap().selection;
assert!(picked.contains(a) && !picked.contains(group), "the first Cmd-click picks the path");
assert_eq!(s.hover_tool_at(Some(Point::new(170.0, 170.0)), &cmd, v), "selection", "the next press selects behind");
click(&mut s);
// Made quickly, the two clicks are also a double-click, which neither isolates the group nor
// changes what the second click selected, also with Cmd let go before it.
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 170.0, 170.0), v).unwrap();
assert_eq!(s.doc().unwrap().isolation, None);
let picked = &s.active().unwrap().selection;
assert!(picked.contains(back) && !picked.contains(a), "the second Cmd-click selects the object behind the group");
}
#[test]
fn a_double_click_after_a_selection_change_is_not_kept_for_select_behind() {
// A double-click that follows a Cmd-click selecting behind keeps what it selected, but only
// while the document stays as that click left it.
let cmd = Mods { cmd: true, ..Mods::default() };
let v = view();
let mut s = session();
rect(&mut s, 100.0, 100.0, 200.0, 200.0);
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
s.select_tool("selection", v).unwrap();
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap();
assert!(!s.active().unwrap().selection.contains(front), "the Cmd-click selects behind");
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0), v).unwrap();
assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other");
}
#[test]
fn a_double_click_after_the_pointer_moved_away_is_not_kept_for_select_behind() {
let cmd = Mods { cmd: true, ..Mods::default() };
let v = view();
let mut s = session();
rect(&mut s, 100.0, 100.0, 200.0, 200.0);
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
s.select_tool("selection", v).unwrap();
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap();
assert!(!s.active().unwrap().selection.contains(front), "the Cmd-click selects behind");
s.pointer(&PointerEvent::new(PointerKind::Move, 400.0, 400.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 200.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0), v).unwrap();
assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other");
}
#[test]
fn a_double_click_after_a_select_behind_drag_is_not_kept_for_select_behind() {
// A Cmd press that selects behind and then drags is not a click, also when the drag ends where
// it began and moves nothing, so a double-click there is a double-click of its own.
let cmd = Mods { cmd: true, ..Mods::default() };
let v = view();
let mut s = session();
let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
s.select_tool("selection", v).unwrap();
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 260.0, 200.0).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap();
assert!(s.active().unwrap().selection.contains(back), "the Cmd press selects behind");
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0), v).unwrap();
assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other");
}
#[test]
fn a_double_click_after_a_select_behind_press_released_away_is_not_kept_for_select_behind() {
// The automation interface can send the release far from the press with no drag between.
let cmd = Mods { cmd: true, ..Mods::default() };
let v = view();
let mut s = session();
let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
s.select_tool("selection", v).unwrap();
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 270.0, 270.0).with_mods(cmd), v).unwrap();
assert!(s.active().unwrap().selection.contains(back), "the Cmd press selects behind");
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 270.0, 270.0), v).unwrap();
assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other");
}
#[test]
fn a_double_click_in_the_frame_of_a_select_behind_press_keeps_what_it_selected() {
// The second press and the double-click can come in one frame, before the release.
let cmd = Mods { cmd: true, ..Mods::default() };
let v = view();
let mut s = session();
let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
s.select_tool("selection", v).unwrap();
s.execute("select.set", &json!({"ids": [back.0]})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0).with_mods(cmd), v).unwrap();
assert_eq!(s.doc().unwrap().isolation, None, "the double-click neither isolates nor edits");
let picked = &s.active().unwrap().selection;
assert!(picked.contains(front) && !picked.contains(back), "the press selects behind, back to the topmost");
}
#[test]
fn a_cmd_click_on_an_unselected_member_of_a_group_holding_the_selection_selects_behind() {
// The group counts as selected wherever its art is, not only over its selected member.
let cmd = Mods { cmd: true, ..Mods::default() };
let v = view();
let mut s = session();
let back = rect(&mut s, 100.0, 100.0, 300.0, 200.0);
let a = rect(&mut s, 150.0, 150.0, 40.0, 40.0);
let b = rect(&mut s, 300.0, 150.0, 40.0, 40.0);
s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap();
s.select_tool("selection", v).unwrap();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
assert_eq!(s.hover_tool_at(Some(Point::new(320.0, 170.0)), &cmd, v), "selection", "on the unselected member");
s.pointer(&PointerEvent::new(PointerKind::Down, 320.0, 170.0).with_mods(cmd), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 320.0, 170.0).with_mods(cmd), v).unwrap();
let picked = &s.active().unwrap().selection;
assert!(picked.contains(back) && !picked.contains(b), "the Cmd-click selects the object behind the group");
}
#[test]
fn a_cmd_click_on_a_selected_lines_segment_selects_behind() {
// An open, unfilled path is only hit near its segments: a Cmd press there selects the object
// behind it, and a Cmd press on its anchor is Direct Selection's.
let cmd = Mods { cmd: true, ..Mods::default() };
let v = view();
let mut s = session();
let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0);
let front = line(&mut s, 150.0, 150.0, 250.0, 250.0);
s.select_tool("selection", v).unwrap();
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
assert_eq!(s.hover_tool_at(Some(Point::new(150.0, 150.0)), &cmd, v), "directSelection", "on its anchor");
// On the segment, away from the anchors and the bounding box's handles.
s.pointer(&PointerEvent::new(PointerKind::Down, 180.0, 180.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "selection");
s.pointer(&PointerEvent::new(PointerKind::Up, 180.0, 180.0).with_mods(cmd), v).unwrap();
let picked = &s.active().unwrap().selection;
assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind");
}
#[test]
fn a_hovers_lend_decision_holds_only_for_the_tool_and_selection_it_was_found_for() {
// While the view moves, the canvas reads the last hover's decision: it does not carry over to
// another tool or another selection.
let cmd = Mods { cmd: true, ..Mods::default() };
let v = view();
let mut s = session();
rect(&mut s, 100.0, 100.0, 200.0, 200.0);
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
s.select_tool("selection", v).unwrap();
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "selection");
s.execute("select.none", &json!({})).unwrap();
assert_eq!(s.hover_tool_id(&cmd), "directSelection", "nothing is selected now");
assert_eq!(s.hover_tool_at(Some(Point::new(500.0, 500.0)), &cmd, v), "directSelection");
s.select_tool("rectangle", v).unwrap();
assert_eq!(s.hover_tool_id(&cmd), s.lent_tool_id(&cmd).unwrap(), "the new tool's lend");
}
#[test]
fn the_marks_follow_this_frames_pointer_with_cmd_held() {
// The canvas asks which tool's marks to draw before it asks for the cursor: the answer is for
// the pointer where it is now, and with the pointer off the canvas, the tool Cmd lends.
let cmd = Mods { cmd: true, ..Mods::default() };
let v = view();
let mut s = session();
rect(&mut s, 100.0, 100.0, 200.0, 200.0);
let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0);
s.select_tool("selection", v).unwrap();
s.execute("select.set", &json!({"ids": [front.0]})).unwrap();
s.cursor(Point::new(200.0, 200.0), cmd, v);
assert_eq!(s.hover_tool_id(&cmd), "selection");
assert_eq!(s.hover_tool_at(Some(Point::new(500.0, 500.0)), &cmd, v), "directSelection", "away from the selection");
assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "selection", "over the selection");
assert_eq!(s.hover_tool_at(None, &cmd, v), "directSelection", "off the canvas");
assert_eq!(s.hover_tool_id(&cmd), "directSelection", "kept while the view moves");
assert_eq!(s.hover_tool_at(None, &Mods::default(), v), "selection", "without Cmd");
}
#[test]
fn cmd_lends_the_selection_tool_and_its_bounding_box_to_direct_selection() {
// #3901: with Direct Selection, Cmd held gives the Selection tool for the press: its cursor,
@@ -1212,6 +1212,26 @@ fn select_part_refuses_hidden_and_locked_objects_of_the_art() {
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1, 1]})).unwrap();
}
#[test]
fn a_cmd_click_with_the_selection_tool_keeps_the_instance_selected_whole() {
// Cmd lends Direct Selection the Selection tool: the press picks one object of a dynamic
// instance, and back with the Selection tool after the release, the instance stays selected,
// whole, as choosing the Selection tool leaves it.
let mut s = session();
let inst = pair(&mut s, "dynamic");
let v = ViewInfo { smart_guides: false, ..Default::default() };
let cmd = Mods { cmd: true, ..Mods::default() };
s.select_tool("selection", v).unwrap();
s.execute("select.none", &json!({})).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 80.0, 30.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "directSelection");
assert!(s.doc().unwrap().selection.symbol_part.is_some(), "the lent tool picks the object");
s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 30.0).with_mods(cmd), v).unwrap();
assert_eq!(s.tool_id(), "selection");
let sel = &s.doc().unwrap().selection;
assert_eq!((&sel.objects, &sel.symbol_part), (&vec![inst], &None));
}
#[test]
fn choosing_the_selection_tool_again_picks_the_instance_whole() {
let mut s = session();
+96
View File
@@ -532,6 +532,102 @@ fn rearrange_that_moves_no_artboard_records_no_undo_step() {
assert_eq!(history(&s), before);
}
/// Rearrange with `indices` lays out only those artboards, in document order whatever order they
/// are listed in, with the grid's top-left at `at`: their art and guides go along, and the other
/// artboards, their art and their guides stay where they are, all in one undo step.
#[test]
fn rearrange_lays_out_only_the_listed_artboards() {
let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 4}));
let before = boards(&s);
let art: Vec<NodeId> = before
.iter()
.map(|r| {
NodeId(
s.execute("shape.rectangle", &json!({"x": r.x0 + 10.0, "y": r.y0 + 10.0, "width": 10, "height": 10})).unwrap()["id"]
.as_u64()
.unwrap(),
)
})
.collect();
for i in [0, 1] {
s.execute("guide.add", &json!({"vertical": true, "pos": before[i].x0 + 5.0, "artboard": i})).unwrap();
}
let undo = s.doc().unwrap().history.undo.len();
let p = json!({"indices": [3, 1], "layout": "row", "spacing": 10, "at": [500, 400]});
let r = s.execute("artboard.rearrange", &p).unwrap();
assert_eq!(r, json!({"artboards": 4, "indices": [1, 3], "moved": 2, "rows": 1, "columns": 2}));
let after = boards(&s);
assert_eq!((after[0], after[2]), (before[0], before[2]), "the artboards not listed stay");
assert_eq!((after[1], after[3]), (Rect::new(500.0, 400.0, 600.0, 450.0), Rect::new(610.0, 400.0, 710.0, 450.0)));
let d = &s.doc().unwrap().doc;
for (id, r) in art.iter().zip(&after) {
let b = d.node(*id).unwrap().geometric_bounds().unwrap();
assert_eq!((b.x0, b.y0), (r.x0 + 10.0, r.y0 + 10.0), "the art is on its artboard");
}
let guides: Vec<f64> = d.ruler_guides().iter().map(|g| g.pos).collect();
assert_eq!(guides, [before[0].x0 + 5.0, 505.0]);
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(boards(&s), before);
}
/// Without `at`, the grid of the listed artboards starts at the first one's top-left; one listed
/// artboard is laid out alone; a listed locked artboard stays and keeps its cell; when every listed
/// artboard is locked, nothing moves, no undo step is recorded and `moved` is 0.
#[test]
fn rearrange_of_listed_artboards_starts_at_the_first_and_keeps_locked_ones() {
let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 4, "artboardLayout": {"layout": "row", "spacing": 20}}));
let before = boards(&s);
// Artboards 1 and 3 in one column, from artboard 1's corner.
let r = s.execute("artboard.rearrange", &json!({"indices": [1, 3], "layout": "column", "spacing": 10})).unwrap();
assert_eq!(r["moved"], 1);
let after = boards(&s);
assert_eq!(after[1], before[1]);
assert_eq!(after[3], Rect::new(before[1].x0, before[1].y1 + 10.0, before[1].x1, before[1].y1 + 60.0));
// One artboard goes to `at`.
s.execute("artboard.rearrange", &json!({"indices": [2], "at": [-300, -200]})).unwrap();
assert_eq!(boards(&s)[2], Rect::new(-300.0, -200.0, -200.0, -150.0));
// Artboard 0 locked keeps its place and its cell: artboard 2 goes to the second cell from 0's.
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
let r = s.execute("artboard.rearrange", &json!({"indices": [0, 2], "layout": "row", "spacing": 5, "at": [1000, 0]})).unwrap();
assert_eq!(r["moved"], 1);
assert_eq!((boards(&s)[0], boards(&s)[2]), (before[0], Rect::new(1105.0, 0.0, 1205.0, 50.0)));
// Every listed artboard locked: nothing moves.
let placed = boards(&s);
let undo = s.doc().unwrap().history.undo.len();
let r = s.execute("artboard.rearrange", &json!({"indices": [0], "at": [3000, 3000]})).unwrap();
assert_eq!(r, json!({"artboards": 4, "indices": [0], "moved": 0, "rows": 1, "columns": 1}));
assert_eq!((boards(&s), s.doc().unwrap().history.undo.len()), (placed, undo));
}
/// Rearrange refuses `indices` that are not a non-empty list of artboards, and an `at` that is not
/// [x, y], before anything moves, and leaves the document as it was when `at` would put an
/// artboard past the canvas; a listed index given twice counts once.
#[test]
fn rearrange_refuses_bad_indices_and_at() {
let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 3}));
let before = (boards(&s), s.doc().unwrap().history.undo.len());
for (p, msg) in [
(json!({"indices": []}), "invalid parameters for `artboard.rearrange`: `indices` must be a non-empty list of artboard indices"),
(json!({"indices": 1}), "invalid parameters for `artboard.rearrange`: `indices` must be a list of artboard indices"),
(json!({"indices": [1.5]}), "invalid parameters for `artboard.rearrange`: `indices` must contain whole numbers"),
(json!({"indices": [-1]}), "invalid parameters for `artboard.rearrange`: `indices` must contain whole numbers"),
(json!({"indices": ["1"]}), "invalid parameters for `artboard.rearrange`: `indices` must contain whole numbers"),
(json!({"indices": [0, 3]}), "no such artboard"),
(json!({"indices": [0, 1], "at": [1]}), "invalid parameters for `artboard.rearrange`: `at` must be [x, y]"),
(json!({"indices": [0, 1], "at": "0,0"}), "invalid parameters for `artboard.rearrange`: `at` must be [x, y]"),
(json!({"at": [0, "1"]}), "invalid parameters for `artboard.rearrange`: `at` must be [x, y]"),
(json!({"indices": [0], "at": [1e20, 0]}), "result would exceed the canvas (coordinates out of range)"),
(json!({"at": [0, -4.000001e6]}), "result would exceed the canvas (coordinates out of range)"),
] {
let err = s.execute("artboard.rearrange", &p).unwrap_err().to_string();
assert_eq!(err, msg, "{p}");
assert_eq!((boards(&s), s.doc().unwrap().history.undo.len()), before, "{p}");
}
let r = s.execute("artboard.rearrange", &json!({"indices": [2, 2], "at": [0, 500]})).unwrap();
assert_eq!((r["indices"].clone(), boards(&s)[2]), (json!([2]), Rect::new(0.0, 500.0, 100.0, 550.0)));
}
/// A session whose New Document profiles are in a fresh folder for test `name` (not made yet).
fn with_profiles(name: &str) -> (Session, std::path::PathBuf) {
let dir = std::env::temp_dir().join(format!("vc-newdoc-profiles-{name}-{}", std::process::id()));
+2 -2
View File
@@ -792,7 +792,7 @@ fn the_document_info_report_has_every_category() {
assert!(text.contains(&format!("\n{h}\n")), "{h}: {text}");
}
assert!(text.contains("Images: 3") && text.contains("Source Sans 3 Regular: built in; embedding allowed"), "{text}");
assert!(text.contains("red.png: 600 × 300 px — ") && text.contains("Color Mode: RGB") && text.contains("\nSwatches: "), "{text}");
assert!(text.contains("red.png: PNG; 600 × 300 px; 72 ppi — ") && text.contains("Color Mode: RGB") && text.contains("\nSwatches: "), "{text}");
let fonts = run(&mut s, "document.info", json!({"format": "text", "category": "fonts"}))["text"].as_str().unwrap().to_string();
assert!(fonts.contains("FONTS") && !fonts.contains("OBJECTS"), "{fonts}");
let i = run(&mut s, "document.info", json!({"category": "linkedImages"}));
@@ -802,7 +802,7 @@ fn the_document_info_report_has_every_category() {
// embedded one with no file.
let linked: Vec<Value> = i["imageObjects"].as_array().unwrap().iter().filter(|o| o["linked"] == true).cloned().collect();
for (o, r) in linked.iter().zip(i["sections"][0]["rows"].as_array().unwrap()) {
let shown = format!("{} × {} px — {}", o["width"], o["height"], o["file"].as_str().unwrap());
let shown = format!("PNG; {} × {} px; 72 ppi — {}", o["width"], o["height"], o["file"].as_str().unwrap());
assert_eq!((&o["name"], shown.as_str()), (&r[0], r[1].as_str().unwrap()));
}
assert_eq!(linked.len(), 2);
+485
View File
@@ -0,0 +1,485 @@
//! `opacity` on `paint.setFill` and `paint.setStroke`: the opacity of the fill or stroke item the
//! paint goes to, and `fillOpacity` and `strokeOpacity` on `paint.proxies`.
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Node, NodeKind};
use vectorcraft_tools::{PointerEvent, PointerKind};
use crate::tooling::ViewInfo;
use crate::*;
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s
}
fn rect(s: &mut Session, x: f64) -> NodeId {
let r = s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 100, "height": 50})).unwrap();
NodeId(r["id"].as_u64().unwrap())
}
fn text(s: &mut Session) -> NodeId {
let r = s.execute("text.create", &json!({"x": 10, "y": 150, "text": "Hi"})).unwrap();
NodeId(r["id"].as_u64().unwrap())
}
fn node(s: &Session, id: NodeId) -> Node {
s.doc().unwrap().doc.node(id).unwrap().clone()
}
fn select(s: &mut Session, ids: &[NodeId]) {
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
}
fn fill_opacity(s: &Session, id: NodeId) -> f32 {
node(s, id).appearance.fill().unwrap().opacity
}
fn undo_labels(s: &Session) -> Vec<String> {
s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect()
}
fn proxies(s: &mut Session) -> Value {
s.execute("paint.proxies", &json!({})).unwrap()
}
/// `paint.setFill {opacity}` alone sets the opacity of the selected object's top fill item, as one
/// undo step named Opacity, and leaves its paint, its stroke and the object's own opacity as they
/// were; `paint.setStroke {opacity}` does the same for the top stroke, and `paint.proxies` answers
/// both.
#[test]
fn opacity_alone_sets_the_fill_or_stroke_item() {
let mut s = session();
let id = rect(&mut s, 10.0);
select(&mut s, &[id]);
let before = node(&s, id);
let undo = undo_labels(&s).len();
s.execute("paint.setFill", &json!({"opacity": 40})).unwrap();
let n = node(&s, id);
assert!((fill_opacity(&s, id) - 0.4).abs() < 1e-6);
assert_eq!(n.appearance.fill_paint(), before.appearance.fill_paint());
assert_eq!(n.appearance.stroke().unwrap().opacity, 1.0);
assert_eq!(n.opacity, 1.0);
let labels = undo_labels(&s);
assert_eq!((labels.len(), labels.last().map(String::as_str)), (undo + 1, Some("Opacity")));
assert_eq!(proxies(&mut s)["fillOpacity"], 40.0);
assert_eq!(proxies(&mut s)["strokeOpacity"], 100.0);
// The defaults for new art keep their paint.
assert_eq!(s.paint.fill, Paint::solid(Color::WHITE));
s.execute("paint.setStroke", &json!({"opacity": 25})).unwrap();
assert!((node(&s, id).appearance.stroke().unwrap().opacity - 0.25).abs() < 1e-6);
assert!((fill_opacity(&s, id) - 0.4).abs() < 1e-6);
assert_eq!(proxies(&mut s)["strokeOpacity"], 25.0);
}
/// A selected group stands for its contents: every member's fill takes the opacity, as one undo step.
#[test]
fn a_group_sets_every_member_in_one_step() {
let mut s = session();
let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0));
select(&mut s, &[a, b]);
s.execute("object.group", &json!({})).unwrap();
let undo = undo_labels(&s).len();
s.execute("paint.setFill", &json!({"opacity": 60})).unwrap();
assert!((fill_opacity(&s, a) - 0.6).abs() < 1e-6 && (fill_opacity(&s, b) - 0.6).abs() < 1e-6);
assert_eq!(undo_labels(&s).len(), undo + 1);
}
/// A group with a fill of its own: without an active Appearance row, `paint.proxies` answers the
/// opacity of the contents' fills, which `paint.setFill {opacity}` sets, not the group's own fill.
#[test]
fn a_group_with_its_own_fill_answers_for_its_contents() {
let mut s = session();
let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0));
select(&mut s, &[a, b]);
s.execute("object.group", &json!({})).unwrap();
let g = s.doc().unwrap().selection.subjects()[0];
select(&mut s, &[g]);
s.execute("appearance.addFill", &json!({})).unwrap();
let own = node(&s, g).appearance.items.iter().position(|it| it.is_fill()).unwrap();
s.execute("paint.setFill", &json!({"item": own, "opacity": 30})).unwrap();
select(&mut s, &[g]);
assert_eq!(proxies(&mut s)["fillOpacity"], 100.0);
s.execute("paint.setFill", &json!({"opacity": 60})).unwrap();
assert_eq!(proxies(&mut s)["fillOpacity"], 60.0);
assert!((node(&s, g).appearance.items[own].opacity() - 0.3).abs() < 1e-6, "the group's own fill keeps its opacity");
}
/// A targeted layer without an active Appearance row: `paint.proxies` answers the opacity of the
/// layer's editable art, which `paint.setFill {opacity}` sets, not that of a locked object before it.
#[test]
fn a_targeted_layer_answers_for_its_editable_art() {
let mut s = session();
let (locked, open) = (rect(&mut s, 10.0), rect(&mut s, 200.0));
s.execute("paint.setFill", &json!({"ids": [locked.0], "opacity": 20})).unwrap();
s.execute("paint.setFill", &json!({"ids": [open.0], "opacity": 80})).unwrap();
s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap();
let layer = s.doc().unwrap().doc.layers[0].id;
s.execute("layer.target", &json!({"id": layer.0})).unwrap();
assert_eq!(proxies(&mut s)["fillOpacity"], 80.0);
s.execute("paint.setFill", &json!({"opacity": 40})).unwrap();
assert!((fill_opacity(&s, open) - 0.4).abs() < 1e-6);
assert!((fill_opacity(&s, locked) - 0.2).abs() < 1e-6, "the locked object keeps its opacity");
assert_eq!(proxies(&mut s)["fillOpacity"], 40.0);
}
/// With the Appearance panel's lower fill row active, that row takes the opacity and the top fill
/// keeps its own.
#[test]
fn the_active_appearance_row_takes_the_opacity() {
let mut s = session();
let id = rect(&mut s, 10.0);
select(&mut s, &[id]);
s.execute("appearance.addFill", &json!({})).unwrap(); // [Fill, Stroke, Fill]
s.execute("appearance.setActiveItem", &json!({"index": 0})).unwrap();
s.execute("paint.setFill", &json!({"opacity": 30})).unwrap();
let ap = node(&s, id).appearance;
assert!((ap.items[0].opacity() - 0.3).abs() < 1e-6);
assert_eq!(ap.items[2].opacity(), 1.0);
assert_eq!(proxies(&mut s)["fillOpacity"], 30.0);
}
/// With a path of a compound path selected and its fill row active, the command edits the compound
/// path's fill, and `paint.proxies` answers that fill's opacity, not the member's own.
#[test]
fn an_active_row_of_a_compound_member_answers_for_its_compound() {
let mut s = session();
let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0));
select(&mut s, &[a, b]);
let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("paint.setFill", &json!({"ids": [compound.0], "opacity": 40})).unwrap();
// A fill row of the member's own, at 100%.
s.execute("appearance.addFill", &json!({"ids": [a.0]})).unwrap();
assert_eq!(fill_opacity(&s, a), 1.0);
select(&mut s, &[a]);
let row = node(&s, a).appearance.items.iter().position(|it| it.is_fill()).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": row})).unwrap();
assert_eq!(proxies(&mut s)["fillOpacity"], 40.0);
s.execute("paint.setFill", &json!({"opacity": 70})).unwrap();
assert!((fill_opacity(&s, compound) - 0.7).abs() < 1e-6);
assert_eq!(proxies(&mut s)["fillOpacity"], 70.0);
// A fill row of the member's at an index that is not a fill in the compound path: the command
// edits the compound path's top fill, which the proxy answers.
s.execute("appearance.addFill", &json!({"ids": [a.0]})).unwrap();
let (member, outer) = (node(&s, a).appearance, node(&s, compound).appearance);
let row = (0..member.items.len()).find(|i| member.items[*i].is_fill() && !outer.items.get(*i).is_some_and(|it| it.is_fill())).unwrap();
select(&mut s, &[a]);
s.execute("appearance.setActiveItem", &json!({"index": row})).unwrap();
assert_eq!(proxies(&mut s)["fillOpacity"], 70.0);
s.execute("paint.setFill", &json!({"opacity": 20})).unwrap();
assert!((fill_opacity(&s, compound) - 0.2).abs() < 1e-6);
assert_eq!(proxies(&mut s)["fillOpacity"], 20.0);
}
/// A color and an opacity change together in one undo step, and the same call again records no
/// step.
#[test]
fn color_and_opacity_are_one_step_and_a_repeat_records_none() {
let mut s = session();
let id = rect(&mut s, 10.0);
select(&mut s, &[id]);
let undo = undo_labels(&s).len();
let p = json!({"color": "#ff0000", "opacity": 50});
s.execute("paint.setFill", &p).unwrap();
assert_eq!(node(&s, id).appearance.fill_paint(), Paint::solid(Color::rgb8(255, 0, 0)));
assert!((fill_opacity(&s, id) - 0.5).abs() < 1e-6);
assert_eq!(undo_labels(&s).len(), undo + 1);
assert_eq!(undo_labels(&s).last().map(String::as_str), Some("Fill Color"));
s.execute("paint.setFill", &p).unwrap();
s.execute("paint.setFill", &json!({"opacity": 50})).unwrap();
assert_eq!(undo_labels(&s).len(), undo + 1);
}
/// Bad values, nothing selected, and characters selected with the Type tool answer errors and leave
/// the document and the defaults for new art as they were.
#[test]
fn errors_leave_the_document_and_defaults_alone() {
let mut s = session();
let id = rect(&mut s, 10.0);
select(&mut s, &[id]);
for bad in [json!(101), json!(-1), json!("50"), json!(true)] {
let e = s.execute("paint.setFill", &json!({"opacity": bad})).unwrap_err();
assert!(e.to_string().contains("`opacity` must be a number from 0 to 100"), "{bad}: {e}");
}
let e = s.execute("paint.setFill", &json!({})).unwrap_err();
assert!(e.to_string().contains("give color, none, swatch, gradient or opacity"), "{e}");
// An opacity alone places no gradient across the selection.
let doc = s.doc().unwrap().doc.clone();
for (span, says) in [(json!("selection"), "give `gradient`"), (json!("all"), "span must be \"object\" or \"selection\"")] {
let e = s.execute("paint.setFill", &json!({"opacity": 40, "span": span})).unwrap_err();
assert!(e.to_string().contains(says), "{span}: {e}");
}
assert_eq!(*s.doc().unwrap().doc, *doc);
s.execute("paint.setFill", &json!({"opacity": 40, "span": "object"})).unwrap();
assert!((fill_opacity(&s, id) - 0.4).abs() < 1e-6);
s.execute("select.none", &json!({})).unwrap();
let doc = s.doc().unwrap().doc.clone();
for p in [json!({"opacity": 40}), json!({"color": "#ff0000", "opacity": 40})] {
let e = s.execute("paint.setFill", &p).unwrap_err();
assert!(e.to_string().contains("select objects or give ids"), "{p}: {e}");
}
assert_eq!(s.paint.fill, Paint::solid(Color::WHITE));
assert_eq!(*s.doc().unwrap().doc, *doc);
// Characters selected with the Type tool.
let v = ViewInfo::default();
s.select_tool("type", v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, 50.0, 250.0), v).unwrap();
}
s.tool_text("Sample", v).unwrap();
s.set_tool_option("select", &json!({"start": 0, "end": 3}));
let doc = s.doc().unwrap().doc.clone();
for p in [json!({"opacity": 40}), json!({"color": "#ff0000", "opacity": 40})] {
let e = s.execute("paint.setFill", &p).unwrap_err();
assert!(e.to_string().contains("type characters have no opacity of their own"), "{p}: {e}");
}
assert_eq!(*s.doc().unwrap().doc, *doc);
assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null);
}
/// Select characters of `t` with the Type tool.
fn select_characters(s: &mut Session, t: NodeId) {
s.select_tool("type", ViewInfo::default()).unwrap();
s.set_tool_option("textSelection", &json!({"editing": t.0, "anchor": 0, "caret": 2}));
}
/// While the Type tool has characters selected, `paint.proxies` answers no opacity even when the
/// type object has a fill row of its own that the Appearance panel has active, since
/// `paint.setFill {opacity}` would give the opacity to the characters.
#[test]
fn with_characters_selected_the_proxy_answers_no_opacity() {
let mut s = session();
let t = text(&mut s);
select(&mut s, &[t]);
s.execute("appearance.addFill", &json!({})).unwrap();
let row = node(&s, t).appearance.items.iter().position(|it| it.is_fill()).unwrap();
s.execute("appearance.setActiveItem", &json!({"index": row})).unwrap();
assert_eq!(proxies(&mut s)["fillOpacity"], 100.0, "the type object's own fill row");
select_characters(&mut s, t);
let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err();
assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}");
assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null);
}
/// While the Type tool has characters selected, an object named by `id` takes the opacity and the
/// paint, and the characters keep theirs.
#[test]
fn with_characters_selected_an_id_takes_the_opacity() {
let mut s = session();
let r = rect(&mut s, 10.0);
let t = text(&mut s);
select(&mut s, &[t]);
select_characters(&mut s, t);
let before = node(&s, t);
s.execute("paint.setFill", &json!({"id": r.0, "opacity": 40})).unwrap();
assert!((fill_opacity(&s, r) - 0.4).abs() < 1e-6);
s.execute("paint.setStroke", &json!({"id": r.0, "color": "#ff0000", "opacity": 30})).unwrap();
let stroke = node(&s, r).appearance.stroke().unwrap().clone();
assert!((stroke.opacity - 0.3).abs() < 1e-6);
assert_eq!(stroke.paint, Paint::solid(Color::rgb8(255, 0, 0)));
assert_eq!(node(&s, t), before, "the characters keep their paint");
}
/// A type object whose characters take the paint is left alone beside a rectangle that takes the
/// opacity, with no error; alone, it answers the characters error.
#[test]
fn type_beside_other_art_is_left_alone() {
let mut s = session();
let r = rect(&mut s, 10.0);
let t = text(&mut s);
let runs = |s: &Session| match &node(s, t).kind {
NodeKind::Text(t) => t.runs.clone(),
_ => panic!("not type"),
};
let before = (node(&s, t), runs(&s));
select(&mut s, &[r, t]);
let out = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap();
assert_eq!(out["objects"], 1, "only the rectangle took the opacity");
assert!((fill_opacity(&s, r) - 0.4).abs() < 1e-6);
assert_eq!((node(&s, t), runs(&s)), before);
select(&mut s, &[t]);
assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null);
let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err();
assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}");
assert_eq!((node(&s, t), runs(&s)), before);
}
/// A color with an opacity on type alone answers the characters error and takes the color back too.
#[test]
fn type_alone_takes_back_the_paint_given_with_an_opacity() {
let mut s = session();
let t = text(&mut s);
select(&mut s, &[t]);
let doc = s.doc().unwrap().doc.clone();
let undo = undo_labels(&s).len();
let e = s.execute("paint.setFill", &json!({"color": "#ff0000", "opacity": 40})).unwrap_err();
assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}");
assert_eq!(*s.doc().unwrap().doc, *doc);
assert_eq!(undo_labels(&s).len(), undo);
assert_eq!(s.paint.fill, Paint::solid(Color::WHITE), "the defaults keep their paint");
}
/// An opacity that no target takes (the only selected object has no fill item) is an error, with or
/// without a paint, and leaves the document as it was; `paint.proxies` answers null for it, and
/// beside an object with a fill item it answers that object's opacity.
#[test]
fn an_opacity_no_target_takes_is_an_error() {
let mut s = session();
let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0));
select(&mut s, &[a]);
s.execute("appearance.removeItem", &json!({"index": 0})).unwrap();
assert!(node(&s, a).appearance.fill().is_none());
assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null);
let doc = s.doc().unwrap().doc.clone();
let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err();
assert!(e.to_string().contains("no target has that fill or stroke to take the opacity"), "{e}");
assert_eq!(*s.doc().unwrap().doc, *doc);
// A paint given with the opacity creates the fill, which takes the opacity.
s.execute("paint.setFill", &json!({"color": "#ff0000", "opacity": 40})).unwrap();
assert!((fill_opacity(&s, a) - 0.4).abs() < 1e-6);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(*s.doc().unwrap().doc, *doc);
select(&mut s, &[b]);
s.execute("paint.setFill", &json!({"opacity": 70})).unwrap();
select(&mut s, &[a, b]);
assert_eq!(proxies(&mut s)["fillOpacity"], 70.0, "the first selected object with a fill item answers");
let out = s.execute("paint.setFill", &json!({"opacity": 20})).unwrap();
assert_eq!(out["objects"], 1, "the object without a fill item is not counted");
assert!((fill_opacity(&s, b) - 0.2).abs() < 1e-6);
assert!(node(&s, a).appearance.fill().is_none());
}
/// An object selected in a dynamic symbol instance has no opacity of its own: `opacity` is an error
/// that leaves the document alone, and `paint.proxies` answers null.
#[test]
fn an_object_in_a_symbol_instance_refuses_an_opacity() {
let mut s = session();
let id = rect(&mut s, 10.0);
select(&mut s, &[id]);
let inst = s.execute("symbol.new", &json!({"name": "One", "ids": [id.0], "type": "dynamic"})).unwrap()["id"].clone();
s.execute("symbol.instance.selectPart", &json!({"id": inst, "path": []})).unwrap();
let doc = s.doc().unwrap().doc.clone();
for p in [json!({"opacity": 40}), json!({"color": "#ff0000", "opacity": 40})] {
let e = s.execute("paint.setFill", &p).unwrap_err();
assert!(e.to_string().contains("an object selected in a symbol instance has no fill or stroke opacity of its own"), "{p}: {e}");
}
assert_eq!(*s.doc().unwrap().doc, *doc);
assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null);
}
/// A gradient mesh point picked with the Mesh tool takes a fill opacity itself, and the proxy shows
/// it; the object's fill item and the other points stay as they were.
#[test]
fn a_picked_mesh_point_takes_the_fill_opacity() {
let mut s = session();
let m = rect(&mut s, 10.0);
select(&mut s, &[m]);
s.execute("object.mesh.create", &json!({"rows": 2, "cols": 2})).unwrap();
select(&mut s, &[m]);
let v = ViewInfo::default();
let NodeKind::Mesh(g) = &node(&s, m).kind else { panic!("not a mesh") };
let q = g.points[4].p;
s.select_tool("mesh", v).unwrap();
for kind in [PointerKind::Down, PointerKind::Up] {
s.pointer(&PointerEvent::new(kind, q.x, q.y), v).unwrap();
}
s.execute("paint.setFill", &json!({"opacity": 30})).unwrap();
let NodeKind::Mesh(g) = &node(&s, m).kind else { panic!("not a mesh") };
let o: Vec<f32> = g.points.iter().map(|p| p.opacity).collect();
assert!((o[4] - 0.3).abs() < 1e-6, "{o:?}");
assert!(o.iter().enumerate().all(|(i, a)| i == 4 || *a == 1.0), "{o:?}");
assert_eq!(proxies(&mut s)["fillOpacity"], 30.0);
}
/// A null `id` or `ids` names no object, so while the Type tool has characters selected the paint
/// goes to those characters only, and the rest of the type keeps its paint.
#[test]
fn a_null_id_leaves_the_paint_to_the_selected_characters() {
for key in ["id", "ids"] {
let mut s = session();
let t = text(&mut s);
select(&mut s, &[t]);
s.select_tool("type", ViewInfo::default()).unwrap();
s.set_tool_option("textSelection", &json!({"editing": t.0, "anchor": 0, "caret": 1}));
s.execute("paint.setFill", &json!({"color": "#ff0000", key: null})).unwrap();
let NodeKind::Text(tx) = &node(&s, t).kind else { panic!("not type") };
let fills: Vec<Paint> = tx.runs.iter().map(|r| r.style.fill.clone()).collect();
assert_eq!(fills.first(), Some(&Paint::solid(Color::rgb8(255, 0, 0))), "{key}: {fills:?}");
assert!(fills.len() > 1 && fills[1..].iter().all(|f| *f != Paint::solid(Color::rgb8(255, 0, 0))), "{key}: {fills:?}");
let e = s.execute("paint.setFill", &json!({"opacity": 40, key: null})).unwrap_err();
assert!(e.to_string().contains("type characters have no opacity of their own"), "{key}: {e}");
}
}
/// A selected Live Paint group stands for its faces in a fill opacity and for its edges in a stroke
/// opacity, and `paint.proxies` answers from those same parts.
#[test]
fn a_live_paint_group_answers_from_the_parts_it_sets() {
let mut s = session();
let id = rect(&mut s, 10.0);
s.execute("livePaint.make", &json!({"ids": [id.0]})).unwrap();
let g = s.doc().unwrap().selection.objects[0];
select(&mut s, &[g]);
s.execute("paint.setStroke", &json!({"opacity": 30})).unwrap();
assert_eq!(proxies(&mut s)["strokeOpacity"], 30.0);
s.execute("paint.setFill", &json!({"opacity": 40})).unwrap();
assert_eq!(proxies(&mut s)["fillOpacity"], 40.0);
assert_eq!(proxies(&mut s)["strokeOpacity"], 30.0);
}
/// While the Live Paint Bucket is the active tool, a fill or stroke chosen goes to the bucket, so
/// `paint.proxies` answers no opacity for the selection and an opacity is an error that leaves the
/// document as it was.
#[test]
fn the_live_paint_bucket_answers_no_opacity() {
let mut s = session();
let id = rect(&mut s, 10.0);
select(&mut s, &[id]);
assert_eq!(proxies(&mut s)["fillOpacity"], 100.0);
s.select_tool("livePaintBucket", ViewInfo::default()).unwrap();
assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null);
assert_eq!(proxies(&mut s)["strokeOpacity"], Value::Null);
let doc = s.doc().unwrap().doc.clone();
assert!(s.execute("paint.setFill", &json!({"opacity": 40})).is_err());
assert_eq!(*s.doc().unwrap().doc, *doc);
}
/// The Eyedropper armed to sample into the Live Paint Bucket's gradient works for the bucket, so
/// the proxies answer no opacity for the selection then too, as they show no paint of its own.
#[test]
fn the_eyedropper_armed_for_the_bucket_answers_no_opacity() {
let mut s = session();
let id = rect(&mut s, 10.0);
select(&mut s, &[id]);
s.select_tool("eyedropper", ViewInfo::default()).unwrap();
assert_eq!(proxies(&mut s)["fillOpacity"], 100.0, "the Eyedropper alone shows the selection's");
s.set_tool_option("stop", &json!("livePaintBucket"));
assert!(s.bucket_paints());
assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null);
assert_eq!(proxies(&mut s)["strokeOpacity"], Value::Null);
}
/// A `swatch` that is no name does not turn a request into an opacity alone: it is an error and
/// leaves the document as it was.
#[test]
fn a_swatch_that_is_no_name_is_refused_with_an_opacity() {
let mut s = session();
let id = rect(&mut s, 10.0);
select(&mut s, &[id]);
let doc = s.doc().unwrap().doc.clone();
for cmd in ["paint.setFill", "paint.setStroke"] {
for swatch in [json!(5), json!(true), json!(["a"]), json!({})] {
assert!(s.execute(cmd, &json!({"swatch": swatch, "opacity": 40})).is_err(), "{cmd} {swatch}");
}
// A null swatch names none, so the opacity goes alone.
s.execute(cmd, &json!({"swatch": null, "opacity": 40})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
}
assert_eq!(*s.doc().unwrap().doc, *doc);
}
+76
View File
@@ -4798,6 +4798,82 @@ fn plugin_commands_are_registered_run_and_removed() {
assert!(s.execute(grow, &json!({})).is_err(), "removed, it no longer runs");
}
/// At API level 2 a command's `menu` lists it in that menu with its plug-in's name after its
/// label, and `plugin.list` gives its `menu` with `after` escaped. A command whose label reads like
/// a built-in command of that menu, or like a command a plug-in with a lower id places there,
/// stays in its plug-in's submenu, and `plugin.list` marks it `placed: false`. Replaced by a module
/// whose command has no `menu`, a command is back in its submenu.
#[test]
fn placed_plugin_commands_are_listed_in_their_menu() {
let mut s = session();
let placing = |id: &str, name: &str, commands: &str| {
let manifest = format!(r#"{{"id":"{id}","name":"{name}","api":2,"version":"1","kind":"filter","commands":{commands}}}"#);
tpl::returning(&manifest, r#"{"objects":[]}"#)
};
let (ant, bee, cat) = ("test.engine.place.ant", "test.engine.place.bee", "test.engine.place.cat");
let low = |id: &str| crate::cmd::plugin::command_id(id, "low");
let menu_of = |s: &Session, command: &str| listed(s, command).map(|c| c.menu.iter().map(|m| m.to_string()).collect::<Vec<_>>());
let in_select = json!([{"id": "low", "label": "Low Area", "menu": {"path": ["Select"], "after": "\u{202E}Inverse"}}]).to_string();
let in_select = in_select.as_str();
let info = install_wat(&mut s, &placing(ant, "Tidy", in_select));
let menu = &info["commands"][0]["menu"];
assert_eq!(menu["path"], json!(["Select"]));
assert!(menu["after"].as_str().is_some_and(|a| a.ends_with("Inverse") && !a.contains('\u{202E}')), "escaped: {menu}");
assert!(menu.get("placed").is_none(), "{menu}");
let c = listed(&s, &low(ant)).expect("listed");
assert_eq!((c.label, menu_of(&s, &low(ant))), ("Low Area (Tidy)", Some(vec!["Select".to_string()])));
// Another plug-in of the same name placing the same label at the same spot stays in its submenu.
let info = install_wat(&mut s, &placing(bee, "Tidy", in_select));
assert_eq!(info["commands"][0]["menu"]["placed"], json!(false));
assert_eq!(listed(&s, &low(bee)).map(|c| c.label), Some("Low Area"));
assert_eq!(menu_of(&s, &low(bee)), Some(vec!["Object".into(), "Plug-ins".into(), "Tidy".into()]));
assert_eq!(menu_of(&s, &low(ant)), Some(vec!["Select".to_string()]));
// `Paste (in Place)` reads like Edit's Paste in Place; Keep is placed.
let edit = r#"[{"id":"paste","label":"Paste","menu":{"path":["Edit"]}},{"id":"keep","label":"Keep","menu":{"path":["Edit"]}}]"#;
let info = install_wat(&mut s, &placing(cat, "in Place", edit));
assert_eq!(info["commands"][0]["menu"]["placed"], json!(false));
assert!(info["commands"][1]["menu"].get("placed").is_none());
let paste = crate::cmd::plugin::command_id(cat, "paste");
assert_eq!(menu_of(&s, &paste), Some(vec!["Object".into(), "Plug-ins".into(), "in Place".into()]));
assert_eq!(menu_of(&s, &crate::cmd::plugin::command_id(cat, "keep")), Some(vec!["Edit".to_string()]));
// `Stop Global (Edit)` reads like the other label of Select's Start Global Edit.
let dog = "test.engine.place.dog";
let info = install_wat(&mut s, &placing(dog, "Edit", r#"[{"id":"stop","label":"Stop Global","menu":{"path":["Select"]}}]"#));
assert_eq!(info["commands"][0]["menu"]["placed"], json!(false));
run(&mut s, "plugin.remove", json!({"id": dog}));
// Object's Show All has one label, so `Hide (All)` is placed beside it.
let all = "test.engine.place.all";
let info = install_wat(&mut s, &placing(all, "All", r#"[{"id":"hide","label":"Hide","menu":{"path":["Object"]}}]"#));
assert!(info["commands"][0]["menu"].get("placed").is_none(), "{}", info["commands"][0]);
assert_eq!(menu_of(&s, &crate::cmd::plugin::command_id(all, "hide")), Some(vec!["Object".to_string()]));
run(&mut s, "plugin.remove", json!({"id": all}));
// `Hide (Edges)` reads like the desktop app's View › Hide Edges, with or without the desktop app.
let edges = "test.engine.place.edges";
let info = install_wat(&mut s, &placing(edges, "Edges", r#"[{"id":"hide","label":"Hide","menu":{"path":["View"]}}]"#));
assert_eq!(info["commands"][0]["menu"]["placed"], json!(false));
run(&mut s, "plugin.remove", json!({"id": edges}));
// Inspecting a plug-in that is not installed reports what installing it gives: of two commands
// with one label at one spot, the second stays in its submenu.
let twice = r#"[{"id":"a","label":"Low","menu":{"path":["Select"]}},{"id":"b","label":"Low","menu":{"path":["Select"]}}]"#;
let data = vectorcraft_format::base64_encode(&wat::parse_str(placing("test.engine.place.eel", "Eel", twice)).unwrap());
let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": data}));
assert!(inspected["commands"][0]["menu"].get("placed").is_none(), "{inspected}");
assert_eq!(inspected["commands"][1]["menu"]["placed"], json!(false), "{inspected}");
// Replaced by a module whose command has no `menu`, Ant's command is back in its submenu and
// Bee's takes the spot.
install_wat(&mut s, &placing(ant, "Tidy", r#"[{"id":"low","label":"Low Area"}]"#));
assert_eq!(menu_of(&s, &low(ant)), Some(vec!["Object".into(), "Plug-ins".into(), "Tidy".into()]));
assert_eq!(menu_of(&s, &low(bee)), Some(vec!["Select".to_string()]));
for id in [ant, bee, cat] {
run(&mut s, "plugin.remove", json!({"id": id}));
}
assert!(listed(&s, &low(bee)).is_none());
}
/// A command run is journaled like any other, so an action records it with its parameters and
/// plays it back.
#[test]
+474 -3
View File
@@ -550,6 +550,18 @@ fn continuous_arc_after_a_line(s: &mut Session, v: ViewInfo) {
key(s, ToolKey::AltTap);
}
/// Whether the tool shows only the path's points and its length handles (a handle and the line to
/// it from the path's end): no hover preview, label or Smart Guide.
fn only_points(s: &mut Session, v: ViewInfo) -> bool {
let o = s.overlays(v);
let handles: Vec<Point> = o.iter().filter_map(|o| if let Overlay::Handle { p, .. } = o { Some(*p) } else { None }).collect();
o.iter().all(|o| match o {
Overlay::CurvePoint { .. } | Overlay::Handle { .. } => true,
Overlay::Line { b, .. } => handles.contains(b),
_ => false,
})
}
/// The last point of the path the tool drew (any other path is a two-point line).
fn drawn_end(s: &Session) -> Point {
let drawn = paths(s).into_iter().find(|(_, p)| p.subpaths[0].anchors.len() >= 3).unwrap();
@@ -710,9 +722,8 @@ fn a_hover_shows_nothing_after_smart_guides_change() {
s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), on).unwrap();
let off_anchor = label(&mut s, on).unwrap() - at;
assert!(off_anchor.x > 0.0 && (off_anchor.x - off_anchor.y).abs() < 1e-9, "the label sits diagonally off the anchor: {off_anchor:?}");
let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. }));
assert!(!only_points(&mut s, on));
assert!(only_points(&mut s, off), "only the path's points show");
assert!(only_points(&mut s, off), "only the path's points and length handles show");
// A click before the pointer moves does not bring the stale hover back.
press_in(&mut s, &[(400.0, 300.0)], off);
assert_eq!(label(&mut s, off), None, "no label for the stale hover after the click");
@@ -746,7 +757,6 @@ fn a_click_that_adds_nothing_keeps_a_stale_hover_hidden() {
s.execute("select.set", &json!({"ids": []})).unwrap();
continuous_arc_after_a_line(&mut s, on);
s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 100.0), on).unwrap();
let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. }));
assert!(!only_points(&mut s, on), "the anchor's guide shows");
assert!(only_points(&mut s, off));
let steps = undo_steps(&s);
@@ -891,6 +901,467 @@ fn path_quick_pen_refuses_bad_params() {
assert_eq!(paths(&s).len(), before.len());
}
/// The handle beyond the end of the path being drawn makes its last line longer, as one undo step,
/// and the next click goes on from the new end.
#[test]
fn dragging_the_end_handle_lengthens_the_last_line() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let undo = undo_steps(&s);
// The handle stands 20 screen points beyond the end, along the line.
press(&mut s, &[(220.0, 100.0), (250.0, 130.0), (280.0, 140.0)]);
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
assert_eq!(ends, [pt(100.0, 100.0), pt(260.0, 100.0)]);
assert_eq!(undo_steps(&s), undo + 1);
click(&mut s, 260.0, 200.0);
let ends: Vec<Point> = only_path(&s).anchors.iter().map(|a| a.p).collect();
assert_eq!(ends, [pt(100.0, 100.0), pt(260.0, 100.0), pt(260.0, 200.0)], "the drawing went on");
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(200.0, 100.0));
}
/// Dragged by its end handle, the last sharp-corner arc goes on around its circle and stays the
/// last piece, so C still flips it and `[` `]` still change its size.
#[test]
fn a_dragged_last_arc_still_flips() {
let mut s = session();
quick_pen(&mut s);
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
click(&mut s, 100.0, 300.0);
click(&mut s, 300.0, 300.0);
let undo = undo_steps(&s);
// The half circle over (200, 300) ends heading down, so its end handle is 20 points below. The
// handle turned a quarter around the center, to (180, 400), takes the end to (200, 400).
press(&mut s, &[(300.0, 320.0), (260.0, 400.0), (180.0, 400.0)]);
let sp = only_path(&s);
assert!(sp.anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6, "three quarters around: {:?}", sp.anchors.last());
assert_eq!(sp.anchors.len(), 4);
assert_eq!(undo_steps(&s), undo + 1);
assert!(s.tool_claims_key(ToolKey::Letter('c'), view()));
key(&mut s, ToolKey::Letter('c'));
let flipped = only_path(&s);
assert_ne!(flipped, sp);
assert!(flipped.anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6);
assert_eq!(undo_steps(&s), undo + 2);
// `]` makes the dragged arc 15° larger: it keeps its ends and gains its own undo step.
key(&mut s, ToolKey::BracketRight);
let larger = only_path(&s);
assert_ne!(larger, flipped);
assert!(larger.anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6);
assert_eq!(undo_steps(&s), undo + 3);
}
/// Dragged back past its start, the last sharp-corner arc stops at 1°.
#[test]
fn a_dragged_last_arc_keeps_at_least_one_degree() {
let mut s = session();
quick_pen(&mut s);
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
click(&mut s, 100.0, 300.0);
click(&mut s, 300.0, 300.0);
// The half circle about (200, 300) runs over the top from (100, 300) to (300, 300); its end
// handle is 20 points below the end. The pointer goes back around the circle from there, past
// the start of the arc.
let (c, r) = (pt(200.0, 300.0), (100.0f64 * 100.0 + 20.0 * 20.0).sqrt());
let a0 = 20.0f64.atan2(100.0);
let mut pts = vec![(300.0, 320.0)];
for d in [45.0f64, 90.0, 135.0, 175.0, 185.0] {
let a = a0 - d.to_radians();
pts.push((c.x + r * a.cos(), c.y + r * a.sin()));
}
press(&mut s, &pts);
let sp = only_path(&s);
let one = 181f64.to_radians();
let end = pt(200.0 + 100.0 * one.cos(), 300.0 + 100.0 * one.sin());
assert!(sp.anchors.last().unwrap().p.distance(end) < 1e-6, "{:?}", sp.anchors.last());
assert_eq!(sp.anchors.first().unwrap().p, pt(100.0, 300.0));
}
/// When the last arc goes on around the circle of the arc before it, its end handle still changes
/// the last arc alone, which C then still flips.
#[test]
fn the_end_handle_changes_the_last_arc_on_a_shared_circle() {
let mut s = session();
quick_pen(&mut s);
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
click(&mut s, 100.0, 300.0);
click(&mut s, 300.0, 300.0);
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "turn", "value": 90})).unwrap();
// A quarter more around the circle about (200, 300), ending heading left.
click(&mut s, 200.0, 400.0);
let r = 100.0 * std::f64::consts::FRAC_1_SQRT_2;
let to = pt(200.0 - r, 300.0 + r);
// The handle at (180, 400) turned 45° more around the center takes the end there with it.
let (sin, cos) = std::f64::consts::FRAC_PI_4.sin_cos();
let (hx, hy) = (-20.0, 100.0);
let pointer = (200.0 + hx * cos - hy * sin, 300.0 + hx * sin + hy * cos);
press(&mut s, &[(180.0, 400.0), (170.0, 400.0), pointer]);
let sp = only_path(&s);
assert!(sp.anchors.last().unwrap().p.distance(to) < 1e-6, "135° from (300, 300): {:?}", sp.anchors.last());
assert!(sp.anchors.get(2).unwrap().p.distance(pt(300.0, 300.0)) < 1e-9, "the first arc stays");
assert!(s.tool_claims_key(ToolKey::Letter('c'), view()));
}
/// Once another path is selected while one was being drawn, the selected path shows its handles.
#[test]
fn another_selected_path_shows_its_handles() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let r = s.execute("shape.line", &json!({"x1": 300, "y1": 300, "x2": 400, "y2": 300})).unwrap();
s.execute("select.set", &json!({"ids": [r["id"]]})).unwrap();
let handle =
|s: &mut Session| s.overlays(view()).iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Handle { p, .. } if *p == pt(420.0, 300.0)));
assert!(handle(&mut s));
assert_eq!(s.cursor(pt(420.0, 300.0), Mods::default(), view()), vectorcraft_tools::Cursor::Move);
}
/// A selected path that is not being drawn shows its handles: the one before its start makes the
/// first arc shorter around its circle. Escape during a drag takes the drag back.
#[test]
fn the_start_handle_of_a_selected_path_shortens_its_arc() {
let mut s = session();
let r = s
.execute("path.quickPen", &json!({"start": [100, 100], "pieces": [{"x": 200, "y": 100, "action": "sharpArc"}, {"x": 300, "y": 100}]}))
.unwrap();
s.execute("select.set", &json!({"ids": [r["id"]]})).unwrap();
quick_pen(&mut s);
let undo = undo_steps(&s);
let before = only_path(&s);
// The half circle leaves (100, 100) heading up, so its start handle is 20 points below.
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 120.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 150.0, 70.0), v).unwrap();
assert_ne!(only_path(&s), before, "previewed");
key(&mut s, ToolKey::Escape);
s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 70.0), v).unwrap();
assert_eq!(only_path(&s), before, "taken back");
assert_eq!(undo_steps(&s), undo);
// The handle turned a quarter around the center, to (130, 50), takes the start to the top of
// the circle: the arc is a quarter from there to (200, 100).
press(&mut s, &[(100.0, 120.0), (130.0, 50.0)]);
let sp = only_path(&s);
assert!(sp.anchors.first().unwrap().p.distance(pt(150.0, 50.0)) < 1e-6, "{:?}", sp.anchors.first());
assert_eq!(sp.anchors.len(), 3);
assert_eq!(undo_steps(&s), undo + 1);
}
/// A click on a length handle that does not drag is an ordinary click: while drawing it adds a
/// point there, and with no path being drawn it starts a new path.
#[test]
fn a_click_on_a_handle_adds_a_point() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let undo = undo_steps(&s);
click(&mut s, 220.0, 100.0);
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(220.0, 100.0)]);
assert_eq!(undo_steps(&s), undo + 1);
// After Escape the path stays selected with its handles; a click on one starts a new path.
key(&mut s, ToolKey::Escape);
assert_eq!(s.cursor(pt(240.0, 100.0), Mods::default(), view()), vectorcraft_tools::Cursor::Move);
click(&mut s, 240.0, 100.0);
assert_eq!(paths(&s).len(), 2);
}
/// During a length drag the tool shows the handle and no preview of a next piece to where the
/// pointer was before the press.
#[test]
fn a_length_drag_shows_no_next_piece() {
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::Move, 220.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 100.0), v).unwrap();
let o = s.overlays(v);
assert!(o.iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Handle { .. })));
assert!(!o.iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Path { .. } | vectorcraft_tools::Overlay::Measure { .. })), "{o:?}");
s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 100.0), v).unwrap();
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(260.0, 100.0));
}
/// A press on a length handle clears the Smart Guides of the hover before it, so none show during
/// the drag.
#[test]
fn a_length_drag_shows_no_smart_guide() {
let mut s = session();
s.execute("shape.line", &json!({"x1": 220, "y1": 100, "x2": 220, "y2": 300})).unwrap();
s.execute("select.set", &json!({"ids": []})).unwrap();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let on = ViewInfo { smart_guides: true, ..Default::default() };
// The end handle stands on the other line's anchor, so the hover there shows its guide.
s.pointer(&PointerEvent::new(PointerKind::Move, 220.0, 100.0), on).unwrap();
assert!(!only_points(&mut s, on), "the anchor's guide shows");
s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), on).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 140.0), on).unwrap();
assert!(only_points(&mut s, on), "no guide during the drag: {:?}", s.overlays(on));
s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 140.0), on).unwrap();
let drawn = paths(&s).into_iter().find(|(_, p)| p.subpaths[0].anchors.first().is_some_and(|a| a.p == pt(100.0, 100.0))).unwrap();
assert_eq!(drawn.1.subpaths[0].anchors.last().unwrap().p, pt(260.0, 100.0));
}
/// A length drag that would take the path past the canvas leaves it where the drag last put it,
/// and the drawing goes on from there.
#[test]
fn a_length_drag_stays_on_the_canvas() {
let mut s = session();
quick_pen(&mut s);
let x = vectorcraft_doc::MAX_COORD - 1000.0;
click(&mut s, x, 100.0);
click(&mut s, x + 500.0, 100.0);
let undo = undo_steps(&s);
let before = only_path(&s);
// The end handle is at x + 520; a drag to x + 2000 would put the end at x + 1980, past the canvas.
press(&mut s, &[(x + 520.0, 100.0), (x + 2000.0, 100.0)]);
assert_eq!(only_path(&s), before);
assert_eq!(undo_steps(&s), undo);
press(&mut s, &[(x + 520.0, 100.0), (x + 820.0, 100.0)]);
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(x + 800.0, 100.0));
assert_eq!(undo_steps(&s), undo + 1);
click(&mut s, x + 800.0, 200.0);
assert_eq!(only_path(&s).anchors.len(), 3, "the drawing went on");
}
/// A length drag across a line, or out along it and back, leaves its length as it was: it changes
/// nothing and records no undo step, on the path being drawn and on a selected path.
#[test]
fn a_length_drag_that_keeps_the_length_records_no_undo_step() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let undo = undo_steps(&s);
let before = only_path(&s);
// The end handle is at (220, 100); the first drag goes straight down from it, the second out
// along the line and back.
for drag in [[(220.0, 100.0), (220.0, 160.0), (220.0, 160.0)], [(220.0, 100.0), (260.0, 100.0), (220.0, 100.0)]] {
press(&mut s, &drag);
assert_eq!(only_path(&s), before, "{drag:?}");
assert_eq!(undo_steps(&s), undo, "{drag:?}");
}
key(&mut s, ToolKey::Escape);
let undo = undo_steps(&s);
for drag in [[(220.0, 100.0), (220.0, 160.0), (220.0, 160.0)], [(220.0, 100.0), (260.0, 100.0), (220.0, 100.0)]] {
press(&mut s, &drag);
assert_eq!(only_path(&s), before, "{drag:?}");
assert_eq!(undo_steps(&s), undo, "{drag:?}");
}
}
/// The paths of a selected compound path show length handles, also after a drag selected the
/// compound again.
#[test]
fn a_compound_path_shows_the_length_handles_of_its_paths() {
let mut s = session();
let a = s.execute("path.quickPen", &json!({"start": [100, 100], "pieces": [{"x": 200, "y": 100}]})).unwrap();
let b = s.execute("path.quickPen", &json!({"start": [100, 300], "pieces": [{"x": 200, "y": 300}]})).unwrap();
s.execute("select.set", &json!({"ids": [a["id"], b["id"]]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
quick_pen(&mut s);
press(&mut s, &[(220.0, 100.0), (250.0, 100.0), (280.0, 100.0)]);
press(&mut s, &[(220.0, 300.0), (250.0, 300.0), (270.0, 300.0)]);
let mut ends: Vec<Point> = paths(&s).iter().filter_map(|(_, pd)| pd.subpaths[0].anchors.last().map(|a| a.p)).collect();
ends.sort_by(|p, q| p.y.total_cmp(&q.y));
assert_eq!(ends, [pt(260.0, 100.0), pt(250.0, 300.0)]);
}
/// An edit made outside the tool during a length press ends the press: a later drag does not
/// preview from the path as the press found it, and so does not undo the edit.
#[test]
fn an_outside_edit_during_a_length_press_is_kept() {
// The edit comes before the first drag event, or after the drag began.
for began in [false, true] {
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();
let id = paths(&s)[0].0.0;
s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap();
if began {
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 100.0), v).unwrap();
}
s.execute("path.quickPenLength", &json!({"id": id, "length": 40})).unwrap();
let edited = only_path(&s);
s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 100.0), v).unwrap();
assert_eq!(only_path(&s), edited, "began: {began}");
}
// Escape after the edit takes the drag back without taking the edit back.
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();
let id = paths(&s)[0].0.0;
s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 100.0), v).unwrap();
s.execute("path.quickPenLength", &json!({"id": id, "length": 40})).unwrap();
let edited = only_path(&s);
key(&mut s, ToolKey::Escape);
s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 100.0), v).unwrap();
assert_eq!(only_path(&s), edited, "escape");
}
/// C and `[` `]` wait for a length drag to end: they neither add an undo step of their own nor
/// change the arc the drag is changing.
#[test]
fn piece_keys_do_nothing_during_a_length_drag() {
let mut s = session();
quick_pen(&mut s);
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
click(&mut s, 100.0, 300.0);
click(&mut s, 300.0, 300.0);
let undo = undo_steps(&s);
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 320.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 260.0, 400.0), v).unwrap();
let during = only_path(&s);
for k in [ToolKey::Letter('c'), ToolKey::BracketRight, ToolKey::BracketLeft] {
assert!(s.tool_claims_key(k, view()), "{k:?} stays with the tool");
key(&mut s, k);
assert_eq!(only_path(&s), during, "{k:?}");
}
s.pointer(&PointerEvent::new(PointerKind::Drag, 180.0, 400.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 180.0, 400.0), v).unwrap();
assert_eq!(undo_steps(&s), undo + 1);
assert!(only_path(&s).anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6);
}
/// Choosing Quick Pen again during a length drag leaves the drawing alone: the drag goes on, ends
/// where the pointer is let go, and the next click goes on drawing the same path.
#[test]
fn choosing_the_tool_again_during_a_length_drag_keeps_the_drawing() {
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, 220.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 130.0), v).unwrap();
quick_pen(&mut s);
s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 140.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 140.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(260.0, 100.0)]);
click(&mut s, 260.0, 200.0);
assert_eq!(paths(&s).len(), 1, "the drawing went on");
assert_eq!(only_path(&s).anchors.len(), 3);
}
/// A length drag ends where the pointer is let go, also when no drag event came after the press.
#[test]
fn a_length_drag_ends_at_the_release_point() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 100.0);
click(&mut s, 200.0, 100.0);
let undo = undo_steps(&s);
let v = view();
s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 100.0), v).unwrap();
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(260.0, 100.0));
assert_eq!(undo_steps(&s), undo + 1);
// A press let go away from the handle without a drag event drags too.
s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 100.0), v).unwrap();
s.pointer(&PointerEvent::new(PointerKind::Up, 320.0, 100.0), v).unwrap();
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(300.0, 100.0));
assert_eq!(only_path(&s).anchors.len(), 2);
assert_eq!(undo_steps(&s), undo + 2);
}
/// `path.quickPenLength` refuses a result past the canvas, not only one past the input limit.
#[test]
fn path_quick_pen_length_stays_on_the_canvas() {
let mut s = session();
let x = vectorcraft_doc::MAX_COORD - 500_000.0;
let r = s.execute("path.quickPen", &json!({"start": [x, 0], "pieces": [{"x": x + 10.0, "y": 0}]})).unwrap();
let id = r["id"].as_u64().unwrap();
let before = only_path(&s);
let undo = undo_steps(&s);
let e = s.execute("path.quickPenLength", &json!({"id": id, "length": 1_000_000})).unwrap_err().to_string();
assert!(e.contains("would exceed the canvas"), "{e}");
assert_eq!(only_path(&s), before);
assert_eq!(undo_steps(&s), undo);
s.execute("path.quickPenLength", &json!({"id": id, "length": 400_000})).unwrap();
assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(x + 400_000.0, 0.0));
}
/// Dragged by the start handle while the path is being drawn, the first line changes and the last
/// sharp-corner arc stays the last piece, so C still flips it.
#[test]
fn the_start_handle_keeps_the_last_arc_a_piece() {
let mut s = session();
quick_pen(&mut s);
click(&mut s, 100.0, 300.0);
click(&mut s, 200.0, 300.0);
s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap();
click(&mut s, 400.0, 300.0);
assert!(s.tool_claims_key(ToolKey::Letter('c'), view()));
let undo = undo_steps(&s);
// The line leaves (100, 300) heading left, seen from the start, so its handle is 20 points left.
press(&mut s, &[(80.0, 300.0), (60.0, 300.0), (50.0, 300.0)]);
let sp = only_path(&s);
assert_eq!(sp.anchors.first().unwrap().p, pt(70.0, 300.0));
assert_eq!(undo_steps(&s), undo + 1);
assert!(s.tool_claims_key(ToolKey::Letter('c'), view()), "the last arc is still a piece");
key(&mut s, ToolKey::Letter('c'));
let flipped = only_path(&s);
assert_ne!(flipped, sp);
assert_eq!(flipped.anchors.first().unwrap().p, pt(70.0, 300.0));
assert!(flipped.anchors.last().unwrap().p.distance(pt(400.0, 300.0)) < 1e-9);
}
/// `path.quickPenLength` sets the length of a line or an arc at either end; the same length
/// changes nothing and records no undo step; bad params are refused.
#[test]
fn path_quick_pen_length_sets_an_end() {
let mut s = session();
let r = s.execute("path.quickPen", &json!({"start": [0, 0], "pieces": [{"x": 100, "y": 0}, {"x": 200, "y": 0, "action": "sharpArc"}]})).unwrap();
let id = r["id"].as_u64().unwrap();
let r = s.execute("path.quickPenLength", &json!({"id": id, "end": "start", "length": 40})).unwrap();
assert_eq!((r["kind"].as_str(), r["length"].as_f64()), (Some("line"), Some(40.0)));
assert_eq!(only_path(&s).anchors.first().unwrap().p, pt(60.0, 0.0));
let undo = undo_steps(&s);
let r = s.execute("path.quickPenLength", &json!({"id": id, "length": std::f64::consts::PI * 50.0})).unwrap();
assert_eq!(r["kind"], "arc");
assert_eq!(undo_steps(&s), undo, "unchanged");
s.execute("path.quickPenLength", &json!({"id": id, "length": std::f64::consts::PI * 25.0})).unwrap();
assert!(only_path(&s).anchors.last().unwrap().p.distance(pt(150.0, -50.0)) < 1e-9);
assert_eq!(undo_steps(&s), undo + 1);
let before = paths(&s);
let bad: [Value; 7] = [
json!({"length": 10}),
json!({"id": id}),
json!({"id": id, "length": "10"}),
json!({"id": id, "length": 0}),
json!({"id": id, "length": 1e7, "end": "start"}),
json!({"id": id, "length": 10, "end": "middle"}),
json!({"id": id, "length": 10, "subpath": 1}),
];
for p in bad {
assert!(s.execute("path.quickPenLength", &p).is_err(), "{p}");
}
let curve = s.execute("shape.line", &json!({"x1": 0, "y1": 300, "x2": 100, "y2": 300})).unwrap();
s.execute("path.convertAnchor", &json!({"id": curve["id"], "anchor": 1, "to": "smooth", "x": 150, "y": 360})).unwrap();
assert!(s.execute("path.quickPenLength", &json!({"id": curve["id"], "length": 10})).is_err(), "not a line or an arc");
s.execute("path.quickPen", &json!({"id": id, "closed": true})).unwrap();
assert!(s.execute("path.quickPenLength", &json!({"id": id, "length": 10})).is_err(), "closed");
assert_eq!(paths(&s).len(), before.len() + 1);
}
/// With `id` and `keep`, the points after the first `keep` are replaced by the pieces.
#[test]
fn path_quick_pen_replaces_the_points_after_keep() {
+52 -2
View File
@@ -653,7 +653,7 @@ fn a_grants_change_without_its_lock_changes_nothing() {
}
/// Reading and changing the grants file wait for a lock another handle holds only for a bounded
/// number of tries: then a read gives no grants and a change fails with the file unchanged. A lock
/// number of tries: then a listing and a change fail, with the file unchanged. A lock
/// released while it waits is taken.
#[test]
fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() {
@@ -668,7 +668,8 @@ fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() {
let waits = std::rc::Rc::new(std::cell::Cell::new(0));
let counted = waits.clone();
WHILE_GRANTS_LOCKED.set(Some(Box::new(move || counted.set(counted.get() + 1))));
assert_eq!(stored_grants(&data), Vec::<Value>::new(), "grants are not read without the lock");
let listed = stored_grants(&data);
assert_eq!(listed.map_err(|e| e.kind()), Err(std::io::ErrorKind::TimedOut), "grants are not listed without the lock");
assert_eq!(waits.get(), LOCK_TRIES - 1);
waits.set(0);
let refused = revoke_grants(&data, None, None);
@@ -1319,6 +1320,55 @@ fn script_file_grants_file_that_cannot_be_read_is_left_as_it_is() {
}
}
/// `script.grants` fails on a grants file that is there but cannot be read (another version, not
/// JSON, no list of grants, over the size limit, not a file, or on Unix a link to a missing file),
/// lists none when it is missing, and
/// lists the well-formed grants of one that holds a grant that is not.
#[test]
fn script_grants_fails_on_a_grants_file_that_cannot_be_read() {
let mut big = b"{\"version\": 1, \"grants\": []}".to_vec();
big.resize((4 << 20) + 1, b' ');
let cases = [
("list-newer", br#"{"version": 2, "grants": []}"#.to_vec()),
("list-broken", b"{ not json".to_vec()),
("list-nolist", br#"{"version": 1, "grants": {}}"#.to_vec()),
("list-big", big),
];
for (name, held) in cases {
let base = folder(name);
write(&base.join("settings/Script Grants.json"), &held);
let mut s = with_data(&base);
let e = s.execute("script.grants", &json!({})).unwrap_err().to_string();
assert!(e.contains("the script file permissions could not be read"), "{name}: {e}");
let _ = std::fs::remove_dir_all(base);
}
let base = folder("list-folder");
std::fs::create_dir_all(base.join("settings/Script Grants.json")).unwrap();
let mut s = with_data(&base);
assert!(s.execute("script.grants", &json!({})).is_err(), "a folder in the grants file's place");
let _ = std::fs::remove_dir_all(base);
#[cfg(unix)]
{
let base = folder("list-dangling");
std::fs::create_dir_all(base.join("settings")).unwrap();
std::os::unix::fs::symlink(base.join("gone.json"), base.join("settings/Script Grants.json")).unwrap();
let mut s = with_data(&base);
assert!(s.execute("script.grants", &json!({})).is_err(), "a link to a missing file in the grants file's place");
let _ = std::fs::remove_dir_all(base);
}
let base = folder("list-missing");
let mut s = with_data(&base);
assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([]), "a missing grants file lists none");
let _ = std::fs::remove_dir_all(base);
let base = folder("list-mixed");
let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false});
let text = json!({"version": 1, "grants": [grant, {"script": "x"}]}).to_string();
write(&base.join("settings/Script Grants.json"), text.as_bytes());
let mut s = with_data(&base);
assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"].as_array().unwrap().len(), 1);
let _ = std::fs::remove_dir_all(base);
}
/// `copy` of a file over 8 MiB is refused, as opening one is.
#[test]
fn script_file_copy_is_held_to_the_file_limit() {
+805
View File
@@ -1313,6 +1313,811 @@ fn a_color_a_pattern_brings_leaves_links_to_a_deleted_color_alone() {
assert!(doc(&s).swatch("Ink 2").is_none(), "{r}");
}
/// A tint or gradient of a numbered library name ("Ink 2") that a library pattern's art brings
/// keeps that name when the document gives the art's color "Ink" another color, so adding the
/// library's "Ink 2" next finds it.
#[test]
fn a_numbered_tint_or_gradient_a_pattern_brings_keeps_the_librarys_name() {
let tint = json!({"name": "Ink 2", "swatch": "Ink", "tint": 50});
let gradient = json!({"name": "Ink 2", "gradient": {"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#ffffff"}]}});
for numbered in [tint, gradient] {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", numbered.clone());
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
assert!(doc(&s).swatch("Ink 2").is_some_and(|w| !w.global && !w.spot), "{numbered}: {first}");
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]}));
assert_eq!((&r["added"], &r["existing"]), (&json!([]), &json!(["Ink 2"])), "{numbered}: {first} {r}");
}
}
/// A library pattern swatch that comes in under a numbered name skips the names the library gives
/// its other swatches: adding the library's "Dots 2" next adds it under its own name.
#[test]
fn a_library_pattern_swatchs_copy_skips_the_librarys_other_names() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
s.edit("Dots", |d, _| {
let paint = vectorcraft_doc::pattern::pattern_paint("Squares");
d.swatches.push(vectorcraft_color::Swatch { name: "Dots".into(), paint, global: false, spot: false });
Ok(())
})
.unwrap();
run(&mut s, "swatch.new", json!({"name": "Dots 2", "color": "#00ff00", "global": true}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Dots", "color": "#ff0000"}));
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Dots"]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Dots 2"]}));
assert_eq!(r["added"], json!(["Dots 2"]), "{first} {r}");
assert!(is_global(&s, "Dots 2", "#00ff00"), "{first} {r}");
}
/// A library whose spot color "Ink" shares its name with a global color in a color group: a
/// pattern's art painted with both brings both. A library tint of the spot color, picked before
/// the pattern, links to the document's copy of the spot color the art takes, not to the global
/// color the art brings under a numbered name, whether that color has another paint or the same.
/// The library's own spot "Ink 2" is green, so the document's blue "Ink 2" is not that swatch.
#[test]
fn a_library_tint_is_not_linked_to_a_namesake_of_another_kind_a_pattern_brings() {
for global_color in ["#ff0000", "#0000ff"] {
a_library_tint_skips_a_namesake_the_pattern_brings(global_color);
}
}
fn a_library_tint_skips_a_namesake_the_pattern_brings(global_color: &str) {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "spot": true}));
run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50}));
run(&mut s, "swatch.new", json!({"name": "Crimson", "color": global_color, "global": true}));
let blue = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 3, "height": 6}))["id"].clone();
let red = run(&mut s, "shape.rectangle", json!({"x": 3, "y": 0, "width": 3, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [blue]}));
run(&mut s, "paint.setFill", json!({"swatch": "Crimson", "ids": [red]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [blue, red]}));
run(&mut s, "select.set", json!({"ids": [blue, red]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
// The global color becomes "Ink" in a color group, and the pattern's art links to it by that name.
s.edit("Rename", |d, _| {
let i = d.swatches.iter().position(|w| w.name == "Crimson").unwrap();
let mut global = d.swatches.remove(i);
global.name = "Ink".into();
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Reds".into(), swatches: vec![global] });
let def = d.pattern_mut("Tiles").unwrap();
for node in &mut def.art {
for it in &mut std::sync::Arc::make_mut(node).appearance.items {
it.paint_mut().map_links(&mut |_, link, _| {
let red = link.as_deref() == Some("Crimson");
if red {
*link = Some("Ink".into());
}
red
});
}
}
Ok(())
})
.unwrap();
let art_links: Vec<Option<String>> = doc(&s).pattern("Tiles").unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect();
assert_eq!(art_links, [Some("Ink".to_string()), Some("Ink".to_string())]);
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "spot": true}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half", "Tiles"]}));
assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{global_color}: {r}");
assert!(doc(&s).swatch("Ink 2").is_some_and(|w| w.spot), "{global_color}: {r}");
}
/// A color of a numbered library name ("Ink 2") that a pattern's art brings comes in under that
/// name when the document does not use it, not as the document's copy of it ("Ink 2 2"), so
/// adding the library's "Ink 2" next finds it.
#[test]
fn a_numbered_color_a_pattern_brings_keeps_its_name_beside_a_copy_of_it() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink 2 2", "color": "#00ff00", "global": true}));
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
assert!(is_global(&s, "Ink 2", "#00ff00"), "{first}");
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]}));
assert_eq!((&r["added"], &r["existing"]), (&json!([]), &json!(["Ink 2"])), "{first} {r}");
}
/// A pattern that a library pattern's art is painted with ("Inner"), brought under a numbered name
/// because the document has a swatch "Inner", skips the name "Inner 2" that the library gives a
/// color, as does the swatch that comes with it.
#[test]
fn a_nested_pattern_a_library_pattern_brings_skips_the_librarys_names() {
let mut s = session();
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone();
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Inner", "width": 6, "height": 6}));
run(&mut s, "object.pattern.done", json!({}));
let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Inner", "ids": [tile]}));
run(&mut s, "select.set", json!({"ids": [tile]}));
run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12}));
run(&mut s, "object.pattern.done", json!({}));
run(&mut s, "swatch.new", json!({"name": "Inner 2", "color": "#00ff00", "global": true}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Inner", "color": "#ff0000"}));
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Outer"]}));
assert!(doc(&s).pattern("Inner 2").is_none(), "{first}");
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Inner 2"]}));
assert_eq!(r["added"], json!(["Inner 2"]), "{first} {r}");
assert!(is_global(&s, "Inner 2", "#00ff00"), "{first} {r}");
}
/// A library pattern that was pasted into the document with its art linked to the document's
/// copy of a numbered library color ("Ink 2 2" for "Ink 2") is found when it is added from the
/// library, not added again.
#[test]
fn a_pasted_pattern_linked_to_a_copy_of_a_numbered_color_is_found() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]}));
run(&mut s, "select.set", json!({"ids": [r]}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink 2 2", "color": "#00ff00", "global": true}));
run(&mut s, "edit.paste", json!({}));
assert!(doc(&s).swatch("Ink 2").is_none(), "the paste reused the copy");
run(&mut s, "swatch.delete", json!({"names": ["Tiles"]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
assert_eq!(doc(&s).patterns.len(), 1, "{r}");
}
/// A library pattern swatch named after its pattern ("Tiles 2") that comes in with a new pattern
/// under a numbered name ("Tiles 2 2"), because the document has another pattern of that name
/// without a swatch, takes the library swatch's name.
#[test]
fn a_new_patterns_swatch_takes_the_library_swatchs_free_name() {
let mut s = session();
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone();
run(&mut s, "select.set", json!({"ids": [own]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 12, "height": 12}));
run(&mut s, "object.pattern.done", json!({}));
run(&mut s, "swatch.delete", json!({"names": ["Tiles 2"]}));
assert!(doc(&s).pattern("Tiles 2").is_some(), "the document keeps its pattern");
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]}));
assert_eq!(r["added"], json!(["Tiles 2"]), "{r}");
let paint = doc(&s).swatch("Tiles 2").map(|w| w.paint.clone());
assert!(matches!(&paint, Some(Paint::Pattern { pattern, .. }) if pattern != "Tiles 2"), "{r} {paint:?}");
// Added again after its swatch is deleted, it reuses the pattern under the same swatch name.
run(&mut s, "swatch.delete", json!({"names": ["Tiles 2"]}));
let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]}));
assert_eq!(again["added"], json!(["Tiles 2"]), "{r} {again}");
assert_eq!(doc(&s).swatch("Tiles 2").map(|w| w.paint.clone()), paint, "{r} {again}");
}
/// A library pattern swatch "Tiles" named after its pattern, added to a document that has another
/// pattern "Tiles" without a swatch, is named after the pattern that comes in ("Tiles 2"), as
/// before numbered names were reserved: only a numbered name is kept for the library swatch.
#[test]
fn a_new_patterns_swatch_of_an_unnumbered_name_is_named_after_its_pattern() {
let mut s = session();
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone();
run(&mut s, "select.set", json!({"ids": [own]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 12}));
run(&mut s, "object.pattern.done", json!({}));
run(&mut s, "swatch.delete", json!({"names": ["Tiles"]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
let added = r["added"].as_array().and_then(|a| a.first()).and_then(|n| n.as_str()).unwrap_or_default().to_string();
assert_ne!(added, "Tiles", "{r}");
let paint = doc(&s).swatch(&added).map(|w| w.paint.clone());
assert!(matches!(&paint, Some(Paint::Pattern { pattern, .. }) if *pattern == added), "{r} {paint:?}");
assert!(doc(&s).swatch("Tiles").is_none(), "{r}");
}
/// A library whose process color "Ink 2" shares its name with a global color in a color group
/// that a pattern's art is painted with: the global color comes in numbered, so adding the
/// library's "Ink 2" next adds the process color under its own name.
#[test]
fn a_numbered_name_is_kept_for_the_library_swatch_it_names() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00"}));
run(&mut s, "swatch.new", json!({"name": "Crimson", "color": "#0000ff", "global": true}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Crimson", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
group_as(&mut s, "Crimson", "Ink 2");
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]}));
assert_eq!(r["added"], json!(["Ink 2"]), "{first} {r}");
assert!(doc(&s).swatch("Ink 2").is_some_and(|w| !w.global && !w.spot), "{first} {r}");
}
/// A library pattern pasted with Add, whose color came in as "Ink 2" and was then deleted without
/// unlinking the art, is not reused through a new "Ink 2" when the library gives that name another
/// color: adding that color next adds it under its own name. This holds too when the document has
/// a pattern "Ink 2" without a swatch.
#[test]
fn a_pasted_pattern_is_not_reused_by_taking_a_librarys_name() {
for bare in [false, true] {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]}));
run(&mut s, "select.set", json!({"ids": [r]}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
if bare {
let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone();
run(&mut s, "select.set", json!({"ids": [own]}));
run(&mut s, "object.pattern.make", json!({"name": "Ink 2", "width": 12, "height": 12}));
run(&mut s, "object.pattern.done", json!({}));
run(&mut s, "swatch.delete", json!({"names": ["Ink 2"]}));
assert!(doc(&s).pattern("Ink 2").is_some(), "the document keeps its pattern");
}
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
run(&mut s, "edit.paste", json!({"swatchConflict": "add"}));
assert!(is_global(&s, "Ink 2", "#0000ff"), "the paste brings the blue color as Ink 2 ({bare})");
run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false}));
run(&mut s, "swatch.delete", json!({"names": ["Tiles"]}));
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]}));
assert_eq!(r["added"], json!(["Ink 2"]), "{bare} {first} {r}");
assert!(is_global(&s, "Ink 2", "#00ff00"), "{bare} {first} {r}");
}
}
/// A library pattern painted with two global colors of one paint, "Ink" and "Ink 2", added beside
/// the document's red "Ink" brings them as "Ink 3" and "Ink 2". Adding the pattern again finds it,
/// in either order of the library's colors: "Ink" does not reuse the library's "Ink 2".
#[test]
fn a_color_a_pattern_brings_again_does_not_reuse_a_copy_the_library_names() {
for ink_first in [true, false] {
let mut s = session();
let names = if ink_first { ["Ink", "Ink 2"] } else { ["Ink 2", "Ink"] };
for n in names {
run(&mut s, "swatch.new", json!({"name": n, "color": "#0000ff", "global": true}));
}
let mut dots = vec![];
for (i, n) in ["Ink", "Ink 2"].iter().enumerate() {
let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
dots.push(dot);
}
run(&mut s, "select.set", json!({"ids": dots}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
assert!(is_global(&s, "Ink 2", "#0000ff") && is_global(&s, "Ink 3", "#0000ff"), "{ink_first} {first}");
run(&mut s, "swatch.delete", json!({"names": ["Tiles"]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
assert_eq!(doc(&s).patterns.len(), 1, "{ink_first} {first} {r}");
}
}
/// A library pattern painted with a blue global "Ink" and a green global "Ink 2", added to a
/// document with a red "Ink" and a blue global "Ink 2": the art's "Ink" is the document's "Ink 2",
/// since that is not the library's "Ink 2", and no third copy comes in.
#[test]
fn a_color_a_pattern_brings_reuses_a_copy_that_is_not_the_librarys_namesake() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true}));
let mut dots = vec![];
for (i, n) in ["Ink", "Ink 2"].iter().enumerate() {
let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
dots.push(dot);
}
run(&mut s, "select.set", json!({"ids": dots}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
assert!(doc(&s).swatch("Ink 3").is_none(), "{r}");
assert!(is_global(&s, "Ink 2", "#0000ff") && is_global(&s, "Ink 2 2", "#00ff00"), "{r}");
}
/// A library pattern painted with a blue global "Ink", from a library that also has a blue global
/// "Ink 2" the art does not use, added beside the document's red "Ink" after the library's "Ink 2"
/// came in: the art's "Ink" does not reuse the library's "Ink 2" and comes in as "Ink 3".
#[test]
fn a_color_a_pattern_brings_does_not_reuse_another_library_colors_copy() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]}));
assert!(is_global(&s, "Ink 2", "#0000ff"), "{first}");
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
assert!(is_global(&s, "Ink 3", "#0000ff"), "{first} {r}");
let links: Vec<Option<String>> = doc(&s).pattern("Tiles").unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect();
assert_eq!(links, vec![Some("Ink 3".to_string())], "{first} {r}");
}
/// A library pattern painted with a blue global "Ink", pasted beside the document's red "Ink" and
/// then left without its color "Ink 2" (deleted without unlinking), is not reused by bringing the
/// library's "Ink" back as "Ink 2" when the library has its own blue "Ink 2": the pattern links to
/// another copy.
#[test]
fn a_pasted_pattern_is_not_reused_by_giving_a_librarys_name_to_another_color() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]}));
run(&mut s, "select.set", json!({"ids": [r]}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
run(&mut s, "edit.paste", json!({"swatchConflict": "add"}));
assert!(is_global(&s, "Ink 2", "#0000ff"), "the paste brings the blue color as Ink 2");
run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false}));
run(&mut s, "swatch.delete", json!({"names": ["Tiles"]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
let added = r["added"].as_array().and_then(|a| a.first()).and_then(|n| n.as_str()).unwrap_or_default().to_string();
let pattern = match doc(&s).swatch(&added).map(|w| w.paint.clone()) {
Some(Paint::Pattern { pattern, .. }) => pattern,
p => panic!("{r} {p:?}"),
};
let links: Vec<Option<String>> = doc(&s).pattern(&pattern).unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect();
assert!(!links.contains(&Some("Ink 2".to_string())), "{r} {links:?}");
}
/// A library pattern painted with two alike gradients of its blue global "Ink", "Ramp 2" and then
/// "Ramp", added beside the document's red "Ink": the color comes in as "Ink 2", and both
/// gradients come in under their own names, linked to it, instead of "Ramp" taking "Ramp 2".
#[test]
fn alike_gradients_a_pattern_brings_keep_their_names_when_their_color_is_renamed() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
let ramp = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#ffffff"}]});
run(&mut s, "swatch.new", json!({"name": "Ramp 2", "gradient": ramp}));
run(&mut s, "swatch.new", json!({"name": "Ramp", "gradient": ramp}));
let mut dots = vec![];
for (i, n) in ["Ramp 2", "Ramp"].iter().enumerate() {
let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
dots.push(dot);
}
run(&mut s, "select.set", json!({"ids": dots}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
assert!(is_global(&s, "Ink 2", "#0000ff"), "{r}");
assert!(doc(&s).swatch("Ramp").is_some() && doc(&s).swatch("Ramp 2").is_some(), "{r}");
}
/// A library pattern painted with blue globals "Ink" and "Ink 2", pasted twice beside the
/// document's red "Ink" and blue "Ink 2" (with Add, both fills on "Ink 2"; with Merge, one on the
/// red "Ink"), is found again as the copy that keeps its blue, not the merged one.
#[test]
fn a_pattern_pasted_with_add_and_with_merge_is_found_as_the_copy_with_its_colors() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
let mut dots = vec![];
for (i, n) in ["Ink", "Ink 2"].iter().enumerate() {
let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
dots.push(dot);
}
run(&mut s, "select.set", json!({"ids": dots}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]}));
run(&mut s, "select.set", json!({"ids": [r]}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true}));
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true}));
run(&mut s, "edit.paste", json!({"swatchConflict": "add"}));
run(&mut s, "edit.paste", json!({"swatchConflict": "merge"}));
let links = |s: &Session, p: &str| -> Vec<Option<String>> {
doc(s).pattern(p).unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect()
};
let kept: Vec<String> = doc(&s).patterns.iter().map(|p| p.name.clone()).filter(|p| !links(&s, p).contains(&Some("Ink".into()))).collect();
assert_eq!((doc(&s).patterns.len(), kept.len()), (2, 1), "one pasted copy keeps the blue color");
for w in doc(&s).swatches.clone().iter().filter(|w| matches!(w.paint, Paint::Pattern { .. })) {
run(&mut s, "swatch.delete", json!({"names": [w.name]}));
}
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
let pattern = match doc(&s).swatch("Tiles").map(|w| w.paint.clone()) {
Some(Paint::Pattern { pattern, .. }) => pattern,
p => panic!("{r} {p:?}"),
};
assert_eq!((doc(&s).patterns.len(), &pattern), (2, &kept[0]), "{r}");
}
/// A library whose color "Tiles 2" shares its name with a pattern swatch in a color group: adding
/// the group gives the pattern swatch another name, so adding the color next adds it under its own.
#[test]
fn a_grouped_pattern_swatch_leaves_a_numbered_name_to_the_librarys_color() {
let mut s = session();
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone();
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Dots", "width": 6, "height": 6}));
run(&mut s, "object.pattern.done", json!({}));
run(&mut s, "swatch.new", json!({"name": "Tiles 2", "color": "#00ff00", "global": true}));
s.edit("Group", |d, _| {
let i = d.swatches.iter().position(|w| w.name == "Dots").unwrap();
let mut w = d.swatches.remove(i);
w.name = "Tiles 2".into();
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] });
Ok(())
})
.unwrap();
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Dots.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Group"]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]}));
assert_eq!(r["added"], json!(["Tiles 2"]), "{first} {r}");
assert!(is_global(&s, "Tiles 2", "#00ff00"), "{first} {r}");
}
/// As above, with the grouped swatch named after its pattern "Tiles 2", which the document holds
/// (pasted there) without a swatch: the reused pattern's swatch leaves the name to the color too.
#[test]
fn a_grouped_swatch_of_a_reused_pattern_leaves_a_numbered_name_to_the_librarys_color() {
let mut s = session();
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone();
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 6, "height": 6}));
run(&mut s, "object.pattern.done", json!({}));
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Tiles 2", "ids": [r]}));
run(&mut s, "select.set", json!({"ids": [r]}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "swatch.new", json!({"name": "Bright", "color": "#00ff00", "global": true}));
s.edit("Group", |d, _| {
let i = d.swatches.iter().position(|w| w.name == "Tiles 2").unwrap();
let w = d.swatches.remove(i);
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] });
d.swatches.iter_mut().find(|w| w.name == "Bright").unwrap().name = "Tiles 2".into();
Ok(())
})
.unwrap();
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "edit.paste", json!({}));
run(&mut s, "swatch.delete", json!({"names": ["Tiles 2"]}));
assert!(doc(&s).pattern("Tiles 2").is_some() && doc(&s).swatch("Tiles 2").is_none(), "the pasted pattern stays");
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Group"]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]}));
assert_eq!(r["added"], json!(["Tiles 2"]), "{first} {r}");
assert!(is_global(&s, "Tiles 2", "#00ff00"), "{first} {r}");
}
/// A pattern "Inner 2" that a library pattern's art is painted with, whose library swatch "Inner 2"
/// places it with an offset, leaves the name to that swatch: adding the library's "Inner 2" next
/// adds it under its own name with its placement. Picked first, "Inner 2" comes in under its own
/// name too.
#[test]
fn a_nested_pattern_leaves_its_name_to_a_library_swatch_that_places_it_otherwise() {
for outer_first in [true, false] {
let mut s = session();
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone();
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 6, "height": 6}));
run(&mut s, "object.pattern.done", json!({}));
let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Inner 2", "ids": [tile]}));
run(&mut s, "select.set", json!({"ids": [tile]}));
run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12}));
run(&mut s, "object.pattern.done", json!({}));
let offset = Paint::Pattern { pattern: "Inner 2".into(), xf: kurbo::Affine::translate((3.0, 0.0)) };
let lib_paint = offset.clone();
s.edit("Offset", move |d, _| {
d.swatches.iter_mut().find(|w| w.name == "Inner 2").unwrap().paint = lib_paint;
Ok(())
})
.unwrap();
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
let picks = if outer_first { ["Outer", "Inner 2"] } else { ["Inner 2", "Outer"] };
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": [picks[0]]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": [picks[1]]}));
assert_eq!(doc(&s).swatch("Inner 2").map(|w| w.paint.clone()), Some(offset), "{outer_first} {first} {r}");
assert_eq!(doc(&s).patterns.len(), 2, "{outer_first} {first} {r}");
}
}
/// A pattern "Inner 2" that a library pattern's art is painted with, brought under a numbered name
/// because the document has another pattern "Inner 2" without a swatch, comes with a swatch under
/// the library swatch's free name "Inner 2": adding the library's "Inner 2" next finds it.
#[test]
fn a_nested_patterns_swatch_takes_the_library_swatchs_free_name() {
let mut s = session();
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone();
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 6, "height": 6}));
run(&mut s, "object.pattern.done", json!({}));
let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Inner 2", "ids": [tile]}));
run(&mut s, "select.set", json!({"ids": [tile]}));
run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12}));
run(&mut s, "object.pattern.done", json!({}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone();
run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [own]}));
run(&mut s, "select.set", json!({"ids": [own]}));
run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 14, "height": 14}));
run(&mut s, "object.pattern.done", json!({}));
run(&mut s, "swatch.delete", json!({"names": ["Inner 2"]}));
assert!(doc(&s).pattern("Inner 2").is_some(), "the document keeps its pattern");
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Outer"]}));
let paint = doc(&s).swatch("Inner 2").map(|w| w.paint.clone());
assert!(
matches!(&paint, Some(Paint::Pattern { pattern, .. }) if pattern != "Inner 2" && doc(&s).pattern(pattern).is_some()),
"{first} {paint:?}"
);
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Inner 2"]}));
assert_eq!(r["added"], json!([]), "{first} {r}");
assert_eq!(doc(&s).swatch("Inner 2").map(|w| w.paint.clone()), paint, "{first} {r}");
assert_eq!(doc(&s).patterns.len(), 3, "{first} {r}");
}
/// A library with a pattern swatch "Tiles 2" and, in a color group, a swatch of the same name that
/// places the same pattern with an offset: adding the group first leaves the name to the
/// ungrouped swatch, which comes in under it next.
#[test]
fn a_grouped_namesake_of_a_pattern_swatch_leaves_it_the_name() {
let mut s = session();
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone();
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 6, "height": 6}));
run(&mut s, "object.pattern.done", json!({}));
s.edit("Group", |d, _| {
let offset = Paint::Pattern { pattern: "Tiles 2".into(), xf: kurbo::Affine::translate((3.0, 0.0)) };
let w = vectorcraft_color::Swatch { name: "Tiles 2".into(), paint: offset, global: false, spot: false };
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] });
Ok(())
})
.unwrap();
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Group"]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]}));
let paint = doc(&s).swatch("Tiles 2").map(|w| w.paint.clone());
assert!(matches!(&paint, Some(Paint::Pattern { xf, .. }) if *xf == kurbo::Affine::IDENTITY), "{first} {r} {paint:?}");
}
/// A pattern "Inner 2" that a library pattern's art is painted with, whose swatch the library
/// deleted before giving the name "Inner 2" to a color, comes in under another name, so adding
/// that color next adds it under its own name.
#[test]
fn a_nested_pattern_does_not_take_a_name_the_library_gives_a_color() {
let mut s = session();
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone();
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 6, "height": 6}));
run(&mut s, "object.pattern.done", json!({}));
let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Inner 2", "ids": [tile]}));
run(&mut s, "select.set", json!({"ids": [tile]}));
run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12}));
run(&mut s, "object.pattern.done", json!({}));
run(&mut s, "swatch.delete", json!({"names": ["Inner 2"]}));
assert!(doc(&s).pattern("Inner 2").is_some(), "the library keeps the pattern");
run(&mut s, "swatch.new", json!({"name": "Inner 2", "color": "#00ff00", "global": true}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone();
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Outer"]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Inner 2"]}));
assert_eq!(r["added"], json!(["Inner 2"]), "{first} {r}");
assert!(is_global(&s, "Inner 2", "#00ff00"), "{first} {r}");
}
/// A library pattern pasted into the document, whose global color "Ink 2" (in a color group) was
/// then deleted without unlinking the art, is not reused by bringing that color back as "Ink 2"
/// when the library also has a process color "Ink 2": adding that color next adds it under its
/// own name.
#[test]
fn a_pasted_pattern_is_not_reused_by_bringing_back_a_librarys_name() {
let mut s = session();
run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00"}));
run(&mut s, "swatch.new", json!({"name": "Crimson", "color": "#0000ff", "global": true}));
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Crimson", "ids": [dot]}));
run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]}));
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
group_as(&mut s, "Crimson", "Ink 2");
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]}));
run(&mut s, "select.set", json!({"ids": [r]}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "edit.paste", json!({}));
assert!(is_global(&s, "Ink 2", "#0000ff"), "the paste brings the global color as Ink 2");
run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false}));
run(&mut s, "swatch.delete", json!({"names": ["Tiles"]}));
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]}));
assert_eq!(r["added"], json!(["Ink 2"]), "{first} {r}");
assert!(doc(&s).swatch("Ink 2").is_some_and(|w| !w.global && !w.spot), "{first} {r}");
}
/// Move swatch `name` of `s`'s document into a new color group under the name `to`, and link the
/// art of every pattern linked to it to `to`.
fn group_as(s: &mut Session, name: &str, to: &str) {
s.edit("Group", |d, _| {
let i = d.swatches.iter().position(|w| w.name == name).unwrap();
let mut w = d.swatches.remove(i);
w.name = to.into();
d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] });
for def in &mut d.patterns {
for node in &mut def.art {
for it in &mut std::sync::Arc::make_mut(node).appearance.items {
it.paint_mut().map_links(&mut |_, link, _| {
let hit = link.as_deref() == Some(name);
if hit {
*link = Some(to.into());
}
hit
});
}
}
}
Ok(())
})
.unwrap();
}
/// The swatch paint `p` links to.
fn tint_link(p: &Paint) -> Option<String> {
match p {
Paint::Solid { swatch, .. } => swatch.clone(),
_ => None,
}
}
/// A library pattern "Tiles" added beside the document's own swatch "Tiles" does not take the name
/// "Tiles 2" that the library gives a color, neither for the pattern nor for its swatch; nor does
/// its swatch when the document holds the pattern as "Tiles 2" (pasted there) without a swatch.
#[test]
fn a_pattern_swatch_named_after_its_numbered_pattern_skips_the_librarys_names() {
for pasted in [false, true] {
let mut s = session();
let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone();
run(&mut s, "select.set", json!({"ids": [dot]}));
run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8}));
run(&mut s, "object.pattern.done", json!({}));
run(&mut s, "swatch.new", json!({"name": "Tiles 2", "color": "#00ff00", "global": true}));
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone();
let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone();
run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]}));
run(&mut s, "select.set", json!({"ids": [r]}));
run(&mut s, "edit.copy", json!({}));
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
run(&mut s, "swatch.new", json!({"name": "Tiles", "color": "#ff0000"}));
if pasted {
run(&mut s, "edit.paste", json!({}));
assert!(doc(&s).pattern("Tiles 2").is_some(), "the paste numbers the pattern");
let names: Vec<String> = doc(&s)
.swatches_iter()
.filter(|w| matches!(&w.paint, Paint::Pattern { pattern, .. } if pattern == "Tiles 2"))
.map(|w| w.name.clone())
.collect();
run(&mut s, "swatch.delete", json!({"names": names}));
}
let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]}));
let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]}));
assert_eq!(r["added"], json!(["Tiles 2"]), "{pasted}: {first} {r}");
assert!(is_global(&s, "Tiles 2", "#00ff00"), "{pasted}: {first} {r}");
}
}
/// A library tint added without its global color to a document that has no swatch of the color's
/// name brings the color along under its own name.
#[test]
+156 -12
View File
@@ -10,6 +10,25 @@ use vectorcraft_tools::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind
use crate::{EngineError, Prefs, Result, Session};
/// What a hover's lend decision holds for ([`Session::hover_tool_at`]).
#[derive(Clone, Copy, PartialEq)]
pub(crate) struct HoverKey {
/// The active document's uid and revision, which moves with the selection.
doc: Option<(u64, u64)>,
tool: &'static str,
mods: Mods,
/// The selection tool and the part selection tool chosen last.
last_tools: (Option<&'static str>, Option<&'static str>),
ctrl_click_selects_behind: bool,
object_selection_by_path_only: bool,
type_selection_by_path_only: bool,
selection_tolerance: f64,
anchor_size: u32,
use_preview_bounds: bool,
type_glyph_bounds: bool,
show_handles_multiple_anchors: bool,
}
/// The tool whose radius is General › Corner Radius.
const ROUNDED_RECTANGLE: &str = "roundedRectangle";
@@ -183,6 +202,9 @@ impl Session {
if self.tool.id() == id {
return Ok(());
}
// A double-click or triple-click after the switch is the new tool's, also when the switch
// comes back to the tool a Cmd press was lent from.
self.press_lent = None;
// Sampling type keeps its highlighted characters as the target, and a whole story that
// Select All selected. Capture before the Type tool deactivates (which commits typing and
// clears its editing state).
@@ -208,6 +230,9 @@ impl Session {
}
if vectorcraft_tools::catalog::is_selection_tool(id) {
self.last_selection_tool = Some(self.tool.id());
if id != "selection" {
self.last_part_selection_tool = Some(self.tool.id());
}
self.select_whole_instance(id);
}
Ok(())
@@ -251,8 +276,10 @@ impl Session {
/// selection tool from other tools (Alt on the lent Direct Selection gesture stays copy/subtract).
/// Cmd alone lends Direct Selection the Selection tool, whose bounding box transforms the
/// object (#3901; <https://community.adobe.com/t5/illustrator-discussions/handles-disappar-on-shape-with-direct-selection-tool/m-p/14848662>).
/// Group Selection lends the Selection tool, and the Selection tool lends Direct Selection or
/// Group Selection, whichever was chosen last (Direct Selection until one is).
/// Perspective Selection keeps Cmd+Alt drags to copy objects on their perspective plane.
/// None for the other selection tools and the view tools.
/// None for the view tools.
fn lent_tool(&self, id: &str, mods: &Mods) -> Option<&'static str> {
use vectorcraft_tools::catalog::{edits_anchors, is_selection_tool};
if matches!(id, "hand" | "zoom" | "rotateView") {
@@ -261,6 +288,12 @@ impl Session {
if id == "directSelection" && mods.cmd {
return Some(if mods.alt { "groupSelection" } else { "selection" });
}
if id == "groupSelection" && mods.cmd {
return Some("selection");
}
if id == "selection" && mods.cmd {
return Some(self.last_part_selection_tool.unwrap_or("directSelection"));
}
if id == "perspectiveSelection" && mods.cmd && mods.alt {
return None;
}
@@ -280,15 +313,118 @@ impl Session {
self.lent_tool(self.tool.id(), mods)
}
/// A press with Cmd held (Ctrl elsewhere) and any other tool than a selection tool: the
/// selection tool [`Self::lent_tool`] takes the gesture, pressing without Cmd (a plain click,
/// not Select Behind). The tool lent to stays as it was, unaware, until the release. → the event
/// for the tool, and the warnings of a preview that keeping the typing applied.
fn lend_selection_tool(&mut self, ev: &PointerEvent) -> Result<(PointerEvent, Vec<String>)> {
if ev.kind != PointerKind::Down || !ev.mods.cmd || self.lender.is_some() {
/// The tool the status bar and the help bar name with `mods` held: the selection tool Cmd
/// lends ([`Self::lent_tool_id`]) while the button is up, Space does not lend a view tool and
/// the active tool is not computing an edit, else the active tool. Over a selected object where
/// a Cmd press selects behind, as the cursor last found it, it names the active tool.
pub fn shown_tool_id(&self, mods: &Mods) -> &'static str {
match self.hovered_lent(mods) {
Some(id) if !mods.space && !self.tool_editing() && !self.pointer_held => id,
_ => self.tool.id(),
}
}
/// The tool whose marks the canvas shows with `mods` held: the selection tool a Cmd press at
/// the pointer would borrow, as [`Self::hover_tool_at`] or [`Self::cursor`] last found it
/// (before either has, the one [`Self::lent_tool_id`] names), else the active tool. The canvas
/// asks this while the view moves, when it does not hit-test the art under the pointer.
pub fn hover_tool_id(&self, mods: &Mods) -> &'static str {
match self.hovered_lent(mods) {
Some(id) if mods.cmd && !mods.space && self.lender.is_none() && !self.tool_editing() && !self.pointer_held => id,
_ => self.tool.id(),
}
}
/// The selection tool a Cmd press with `mods` would borrow at the pointer: the one
/// [`Self::hover_tool_at`] or [`Self::cursor`] last found, while the document, the selection,
/// the active tool and the keys are as they were then (none where the press selects behind),
/// else the one [`Self::lent_tool_id`] names.
fn hovered_lent(&self, mods: &Mods) -> Option<&'static str> {
match self.hover_lent {
Some((key, lent)) if key == self.hover_key(mods) => lent,
_ => self.lent_tool_id(mods),
}
}
/// What a hover's lend decision holds for: the active document's state (its uid and revision,
/// which moves with the selection), the active tool, the keys, the selection tools chosen last
/// and the preferences a press's hit test reads.
fn hover_key(&self, mods: &Mods) -> HoverKey {
let p = &self.prefs;
HoverKey {
doc: self.active().map(|d| (d.uid, d.revision)),
tool: self.tool.id(),
mods: *mods,
last_tools: (self.last_selection_tool, self.last_part_selection_tool),
ctrl_click_selects_behind: p.ctrl_click_selects_behind,
object_selection_by_path_only: p.object_selection_by_path_only,
type_selection_by_path_only: p.type_selection_by_path_only,
selection_tolerance: p.selection_tolerance,
anchor_size: p.anchor_size,
use_preview_bounds: p.use_preview_bounds,
type_glyph_bounds: p.type_glyph_bounds,
show_handles_multiple_anchors: p.show_handles_multiple_anchors,
}
}
/// The tool whose marks and widgets the canvas draws this frame with `mods` held and the
/// pointer at `p` (None off the canvas): the selection tool a Cmd press there would borrow
/// ([`Self::lent_tool_at`]; off the canvas, the one [`Self::lent_tool_id`] names), else the
/// active tool. [`Self::hover_tool_id`] then answers the same until the pointer or the keys move.
pub fn hover_tool_at(&mut self, p: Option<Point>, mods: &Mods, view: ViewInfo) -> &'static str {
let lends = mods.cmd && !mods.space && self.lender.is_none() && !self.tool_editing() && !self.pointer_held;
let lent = match p {
_ if !lends => None,
Some(p) => self.lent_tool_at(p, mods, view),
None => self.lent_tool_id(mods),
};
let key = self.hover_key(mods);
self.hover_lent = lends.then_some((key, lent));
lent.unwrap_or(self.tool.id())
}
/// The selection tool a press at `p` with `mods` borrows ([`Self::lent_tool`]): none when
/// the Selection tool keeps a Cmd press on a selected object to select the object behind it
/// (Selection & Anchor Display › Command Click to Select Objects Behind).
fn lent_tool_at(&mut self, p: Point, mods: &Mods, view: ViewInfo) -> Option<&'static str> {
let id = self.lent_tool(self.tool.id(), mods)?;
let behind = self.tool.id() == "selection" && self.with_tool_cx(view, |_, cx| vectorcraft_tools::select::selects_behind_at(cx, p));
(!behind).then_some(id)
}
/// Is the press `ev` lent a selection tool ([`Self::lend_selection_tool`])? The frontend asks
/// before the press, to tell a gesture of the tool in hand from one of a lent tool.
pub fn press_lends_tool(&mut self, ev: &PointerEvent, view: ViewInfo) -> bool {
ev.kind == PointerKind::Down && ev.mods.cmd && self.lender.is_none() && self.lent_tool_at(ev.pos, &ev.mods, view).is_some()
}
/// A press with Cmd held (Ctrl elsewhere): the selection tool [`Self::lent_tool_at`] names
/// takes the gesture, pressing without Cmd (a plain click, not Select Behind). The tool lent to
/// stays as it was, unaware, until the release. With a selection tool active, the double-click
/// or triple-click that follows Cmd-clicks goes to the tool the clicks went to, with Cmd kept
/// (Cmd+Shift releases a guide), and that tool is given back after it. → the event for the tool,
/// and the warnings of a preview that keeping the typing applied.
fn lend_selection_tool(&mut self, ev: &PointerEvent, view: ViewInfo) -> Result<(PointerEvent, Vec<String>)> {
let follow_up =
matches!(ev.kind, PointerKind::DoubleClick | PointerKind::TripleClick) && vectorcraft_tools::catalog::is_selection_tool(self.tool.id());
if ev.kind == PointerKind::Down {
self.press_lent = None;
}
if (ev.kind != PointerKind::Down && !follow_up) || !ev.mods.cmd || self.lender.is_some() {
return Ok((*ev, vec![]));
}
let Some(id) = self.lent_tool(self.tool.id(), &ev.mods) else { return Ok((*ev, vec![])) };
// A follow-up goes where the press before it went, whatever that press selected, while the
// document and the active tool are the ones that press found.
let at = (self.active().map(|d| d.uid), self.tool.id());
let id = if follow_up {
self.press_lent.filter(|(doc, tool, _)| (*doc, *tool) == at).map(|(.., id)| id)
} else {
self.lent_tool_at(ev.pos, &ev.mods, view)
};
let Some(id) = id else { return Ok((*ev, vec![])) };
if !follow_up {
self.press_lent = Some((at.0, at.1, id));
}
// Typing in progress is kept as its own step first: the lent tool's drag previews from the
// document its interaction started from, which would drop the typing (#1881). When it
// can't be kept, the press is not lent.
@@ -316,7 +452,8 @@ impl Session {
}
self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone()));
self.lender = Some(std::mem::replace(&mut self.tool, lent));
Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled))
let cmd = follow_up && ev.mods.cmd;
Ok((PointerEvent { mods: Mods { cmd, ..ev.mods }, ..*ev }, settled))
}
/// The lent selection tool's gesture is over: the tool it was lent to is back as it was (the
@@ -341,6 +478,9 @@ impl Session {
self.back_to_bucket = outer_bucket;
self.keep_tool_settings();
self.tool = lender;
// Back with the Selection or Group Selection tool, a symbol part the lent Direct
// Selection picked gives way to its instance, as choosing the tool does.
self.select_whole_instance(self.tool.id());
if let Some(points) = mesh_points {
self.tool.set_option("meshPoints", &points);
}
@@ -771,7 +911,7 @@ impl Session {
}
self.leave_draw_inside(ev, view)?;
self.tell_tool_history_moved();
let (ev, settled) = self.lend_selection_tool(ev)?;
let (ev, settled) = self.lend_selection_tool(ev, view)?;
let ev = &ev;
let lent = self.lender.is_some();
let mut acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev));
@@ -795,7 +935,7 @@ impl Session {
PointerKind::Up => self.press_point = None,
_ => {}
}
if ev.kind == PointerKind::Up {
if ev.kind == PointerKind::Up || (lent && matches!(ev.kind, PointerKind::DoubleClick | PointerKind::TripleClick)) {
self.give_back_tool(view)?;
}
r
@@ -1305,7 +1445,11 @@ impl Session {
/// press would borrow ([`Self::lend_selection_tool`]).
pub fn cursor(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Cursor {
// While an edit is computed, a Cmd press is held for the active tool, which shows it is busy.
let lent = if mods.cmd && self.lender.is_none() && !self.tool_editing() { self.lent_tool(self.tool.id(), &mods) } else { None };
// Cmd pressed once a drag is under way lends nothing, so the tool keeps its pointer.
let lends = mods.cmd && self.lender.is_none() && !self.tool_editing() && !self.pointer_held;
let lent = if lends { self.lent_tool_at(p, &mods, view) } else { None };
let key = self.hover_key(&mods);
self.hover_lent = lends.then_some((key, lent));
match lent {
Some(id) => {
let lent = self.make_tool(id);
+6 -1
View File
@@ -93,7 +93,7 @@ fn every_command_without_a_document() {
}
/// Regression: huge column counts used to panic with `capacity overflow`; in every layout and
/// order (#681), with huge and negative spacing too.
/// order (#681), with huge and negative spacing too, and with `indices` and `at`.
#[test]
fn artboard_rearrange_huge_columns() {
for fx in Fixture::ALL {
@@ -106,6 +106,11 @@ fn artboard_rearrange_huge_columns() {
}
}
}
// Listed artboards, out of range, and the grid's top-left at the far ends of the plane.
for (indices, at) in [(json!([0]), json!([1e308, -1e308])), (json!([0, u64::MAX]), json!([0, 0])), (json!([]), json!([-1e308, 1e308]))] {
let p = json!({ "indices": indices, "at": at, "columns": u64::MAX, "spacing": 1e308 });
assert_eq!(probe(fx, "artboard.rearrange", &p), None);
}
}
}
+26 -6
View File
@@ -711,9 +711,10 @@ proptest! {
}
/// Manifests with hostile `commands` (junk of every type, bad and repeated ids, labels with
/// control and bidirectional override characters, a `menu` naming another menu, junk
/// parameters) parse to an error or to commands whose menu labels show no hidden character and
/// that sit under Plug-ins alone; installing one and running each of its commands ends as an
/// control and bidirectional override characters, a `menu` of any shape naming any menu, junk
/// parameters) at API level 1 or 2 parse to an error or to commands whose menu labels show no
/// hidden character and that sit under Plug-ins, or at level 2 in one of the menus a manifest
/// may name, with the plug-in's name; installing one and running each of its commands ends as an
/// error or an edit, never a panic, and the document then renders and exports.
#[test]
fn hostile_manifest_commands_never_crash(
@@ -727,7 +728,17 @@ proptest! {
1 => "[a-z\u{0007}\n]{1,8}".prop_map(Value::from),
1 => arb_junk(),
],
prop_oneof![Just(Value::Null), Just(json!("File")), arb_junk()],
prop_oneof![
Just(Value::Null),
Just(json!("File")),
Just(json!({"path": ["Select"], "after": "Inverse"})),
Just(json!({"path": ["Object", "Path"]})),
Just(json!({"path": ["File"]})),
Just(json!({"path": ["Select"], "after": "\u{202E}Inverse"})),
arb_junk().prop_map(|j| json!({"path": j})),
arb_junk().prop_map(|j| json!({"path": ["Select"], "after": j})),
arb_junk(),
],
prop_oneof![Just(Value::Null), Just(json!({"by": {"type": "number", "min": 0, "max": 10, "default": 2}})), arb_junk()],
)
.prop_map(|(id, label, menu, params)| {
@@ -746,8 +757,9 @@ proptest! {
),
junk in prop::option::weighted(0.1, arb_junk()),
given in prop_oneof![Just(json!({})), Just(json!({"by": 3})), arb_junk()],
api in 1u32..=2,
) {
let mut m = json!({"id": "fuzz.commands", "name": "Fuzz \u{202E}Commands", "kind": kind});
let mut m = json!({"id": "fuzz.commands", "name": "Fuzz \u{202E}Commands", "kind": kind, "api": api});
if matches!(kind, "exporter" | "importer") {
m["extensions"] = json!(["fz"]);
}
@@ -760,6 +772,12 @@ proptest! {
let shown = c.shown_label();
prop_assert!(!shown.chars().any(|ch| ch.is_control() || matches!(ch, '\u{202E}' | '\u{2066}' | '\u{200F}')), "{}", shown);
prop_assert!(shown.chars().count() <= vectorcraft_plugins::permissions::MAX_SHOWN_NAME);
let placed = c.menu_label(&man.name);
prop_assert!(!placed.chars().any(|ch| ch.is_control() || matches!(ch, '\u{202E}' | '\u{2066}' | '\u{200F}')), "{}", placed);
if let Some(place) = &c.place {
prop_assert!(api >= 2 && vectorcraft_plugins::manifest::MENU_PLACES.contains(&place.path), "{:?}", place);
prop_assert!(placed.ends_with(')') && placed.len() > shown.len(), "a placed item names its plug-in: {}", placed);
}
}
}
let mut s = rich_session();
@@ -778,7 +796,9 @@ proptest! {
let ran = r.map_err(|msg| TestCaseError::fail(format!("panicked running {text}: {msg}")))?;
prop_assert!(ran.is_empty() || parsed.is_ok(), "a manifest that doesn't parse installed: {}", text);
for (id, menu) in &ran {
prop_assert!(menu.len() == 3 && menu[1] == "Plug-ins" && matches!(menu[0], "Object" | "Effect"), "{id}: {menu:?}");
let submenu = menu.len() == 3 && menu[1] == "Plug-ins" && matches!(menu[0], "Object" | "Effect");
let place = api >= 2 && vectorcraft_plugins::manifest::MENU_PLACES.contains(&menu.as_slice());
prop_assert!(submenu || place, "{id}: {menu:?}");
}
renders(&s, "after hostile commands")?;
vectorcraft_plugins::registry::remove("fuzz.commands");
+3 -1
View File
@@ -607,7 +607,9 @@ impl<'a> Scene<'a> {
// (a plate's colors come from the separator, which has applied it already); a
// spot ink with a white color still overprints, as it is written as that ink.
Some(p @ Paint::Solid { .. }) if blob.is_none_or(|b| b.gray_source().is_some()) => {
let discarded = !self.plate && self.doc.discards_white_overprint(p);
let discarded = !self.plate
&& vectorcraft_doc::overprint::is_white(p)
&& vectorcraft_doc::overprint::DiscardWhite::of(self.doc).discards(p);
let on = self.overprint_on(n.colorize_overprints() && !discarded);
self.colorized_image(im, blob, p, on);
self.overprint_off(on);
+2 -2
View File
@@ -789,7 +789,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"window.learn",
"Learn",
"",
"{show?: bool} show (true), hide (false) or toggle (omitted or null) the Learn panel, as Window › Learn and the app bar's Explore tutorials button do; any other value is an error and changes nothing; returns whether the panel shows",
"{show?: bool} show (true), hide (false) or toggle (omitted or null) the Learn panel, as Window › Learn does; any other value is an error and changes nothing; returns whether the panel shows",
),
(
"learn.list",
@@ -1597,7 +1597,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, 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}",
"{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, opacity?: bool, 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; opacity checks (true) or unchecks (false) Show Opacity, as the panel menu does: a row under the wheel or the box with a slider and a percent field that set the opacity of what the panel edits (the fill item, as paint.setFill {opacity} sets it, the stroke item, as paint.setStroke {opacity} sets it, the selected gradient stop, or the selected freeform point, the first stop or point when none is selected; gray with nothing selected, for an object selected in a symbol instance, and when the fill or stroke item it would set is on type characters or missing); 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, opacity, vision, documentColors}",
),
(
"ui.savePdfDialog",
+8 -2
View File
@@ -6,13 +6,15 @@
//! their path ([`slide`]), touching edges merged ([`shared_edge`]), paths divided into dashes
//! ([`divide_dashes`]), two circles joined by a smooth bridge ([`smooth_bridge`]) or many circles
//! joined to their neighbors ([`bridge_many`]), the common tangents of two convex outlines
//! ([`common_tangents`]), the Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch
//! two or three shapes ([`tangent_circles`]).
//! ([`common_tangents`]), the Parametric Shape Tool's shapes ([`shapes`]), the circles that touch
//! two or three shapes ([`tangent_circles`]) and the largest circle inside a shape
//! ([`inscribed_circle`]).
mod bridge;
mod crossings;
mod dashes;
mod extend;
mod inscribed;
pub mod shapes;
mod shared_edge;
mod slide;
@@ -33,6 +35,10 @@ pub use bridge::{
pub use crossings::{MAX_CROSSED_BY_SEGMENTS, MAX_CROSSING_SEGMENTS, Place, Work, crossings, crossings_on, crossings_on_within, insert_at};
pub use dashes::{DashSpec, Piece, divide_dashes};
pub use extend::{ExtendMode, extend_length_to, extend_open};
pub use inscribed::{
INSCRIBED_PRECISION, Inscribed, InscribedError, MAX_INSCRIBED_CELLS, MAX_INSCRIBED_EDGES, MAX_INSCRIBED_WORK, inscribed_circle,
inscribed_circle_within,
};
pub use shared_edge::{
COINCIDENCE, EndSide, Follow, MAX_COINCIDENCE, MergePlan, MergePreview, Stretch, apply_merge, ends_at, merge_preview, stretches_at,
};
@@ -0,0 +1,373 @@
//! Add Inscribed Circle: the largest circle inside a filled outline, the center of which is the
//! outline's [pole of inaccessibility](https://en.wikipedia.org/wiki/Pole_of_inaccessibility).
//!
//! The outline is first resolved under its fill rule into simple contours (outer contours and
//! holes, as [`crate::try_normalize`] resolves them, narrow ones kept), so overlapping and self-crossing subpaths count as the area they fill
//! and only real edges bound the circle. The contours are flattened, and square cells covering
//! their box are searched best first: a cell's center lies some distance inside the outline, and no
//! point of the cell lies more than half the cell's diagonal farther in, so a cell that cannot beat
//! the best center found by more than the precision is not split. The radius is then measured from
//! the center to the curves themselves.
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use kurbo::{ParamCurveNearest, Point, Rect, Shape};
use vectorcraft_geom::hit::fill_contains;
use vectorcraft_geom::{FillRule, PathData, PathEl};
use crate::boolean::{Tidy, fill_bezpath, normalize_bez};
#[cfg(test)]
mod tests;
#[cfg(test)]
thread_local! {
/// The distances from a point to an edge that the last [`search`] on this thread measured.
static MEASURED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// How close to the largest circle's radius the search gets, in points, for outlines whose box is
/// at least 10 pt across; a smaller box gets a thousandth of its narrower side.
pub const INSCRIBED_PRECISION: f64 = 0.01;
/// Most straight edges the flattened outline may have.
pub const MAX_INSCRIBED_EDGES: usize = 1 << 18;
/// Most distances from a point to an edge that one search measures, or that the searches of one
/// [`inscribed_circle_within`] budget measure together.
pub const MAX_INSCRIBED_WORK: usize = 1 << 27;
/// Most cells the box is first cut into.
const MAX_FIRST_CELLS: f64 = 4096.0;
/// Most cells the search keeps waiting to be split.
pub const MAX_INSCRIBED_CELLS: usize = 1 << 20;
/// How many times an outline the flattening does not resolve is flattened 16 times finer.
const FINER_FLATTENINGS: usize = 4;
/// The largest circle inside an outline: its center and radius.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Inscribed {
pub center: Point,
pub radius: f64,
}
/// Why [`inscribed_circle`] found no circle.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InscribedError {
/// The outline fills no area.
NoArea,
/// The outline could not be resolved, has more than [`MAX_INSCRIBED_EDGES`] anchors in its
/// subpaths of two or more or more than as many edges once flattened, or the
/// search would measure more than its limit or keep more than [`MAX_INSCRIBED_CELLS`] cells
/// waiting, or the outline is so thin for its length that it flattens to no area.
TooComplex,
}
/// The largest circle inside the area that `path` fills under `rule`, within twice the precision
/// of the largest radius: the search's precision and the flattening, at half of it. The precision
/// is [`INSCRIBED_PRECISION`], or a thousandth of the narrower side of the filled area's box when
/// that is less than 10 pt. A curve whose control polygon is longer than 4096² times the
/// flattening tolerance (83,886 pt at 0.005 pt) is flattened more coarsely
/// ([`vectorcraft_geom::flatten`]), and the circle can be smaller by as much; so can a curved hole
/// narrower than the flattening tolerance. The bounds hold for the fill as the path operations
/// resolve it: holes and gaps narrower than 1e-6 pt close up, and edges can move by as much. Open
/// subpaths are closed as the other path operations close them, handles included. The searches
/// for one outline measure at most [`MAX_INSCRIBED_WORK`] distances in all, the final distances
/// to the curves included.
pub fn inscribed_circle(path: &PathData, rule: FillRule) -> Result<Inscribed, InscribedError> {
inscribed_circle_within(path, rule, &mut MAX_INSCRIBED_WORK.clone())
}
/// [`inscribed_circle`], measuring at most `work` distances from a point to an edge (and never
/// more than [`MAX_INSCRIBED_WORK`]) and taking the ones it measured off `work`, so several
/// searches can share one budget.
pub fn inscribed_circle_within(path: &PathData, rule: FillRule, work: &mut usize) -> Result<Inscribed, InscribedError> {
// A path with more anchors than the edge limit, in the subpaths that are filled, is refused
// before it is resolved.
let mut filled_anchors = path.subpaths.iter().map(|sp| sp.anchors.len()).filter(|&n| n >= 2);
if filled_anchors.try_fold(0usize, |total, n| total.checked_add(n).filter(|&t| t <= MAX_INSCRIBED_EDGES)).is_none() {
return Err(InscribedError::TooComplex);
}
let filled = fill_bezpath(path);
let b = filled.bounding_box();
if !(b.width() > 0.0 && b.height() > 0.0 && b.is_finite()) {
return Err(InscribedError::NoArea);
}
let precision = precision_for(b);
// Every contour of the fill's boundary counts, however narrow, down to the sweep's tolerance
// (1e-6 pt; [`crate::boolean::eps_for`]): a hairline hole is still outside the fill. Curves the
// sweep split are rebuilt from the input's own.
let contours = normalize_bez(&filled, rule).map_err(|_| InscribedError::TooComplex)?;
// The resolved boundary can have far more pieces than the input; past the edge limit it is
// refused before it is copied.
if contours.contours().map(|c| c.path.segments().count()).sum::<usize>() > MAX_INSCRIBED_EDGES {
return Err(InscribedError::TooComplex);
}
let tidy = Tidy::keeping(precision, [&filled]);
let mut curves = kurbo::BezPath::new();
for c in contours.contours() {
curves.extend(tidy.repair(&c.path));
}
let b = curves.bounding_box();
if !(b.width() > 0.0 && b.height() > 0.0 && b.is_finite()) {
return Err(InscribedError::NoArea);
}
// The fill rule can leave a much narrower area than the outline's box.
let precision = precision.min(precision_for(b));
// The attempts for this outline share one allowance, taken off `work` as it is spent.
let start = (*work).min(MAX_INSCRIBED_WORK);
let mut allowance = start;
let found = measure(&curves, b, precision, &mut allowance);
*work = work.saturating_sub(start - allowance);
found
}
/// The largest circle in the resolved `curves`, whose box is `b`, searched to `precision`,
/// measuring at most `allowance` distances and taking them off it.
fn measure(curves: &kurbo::BezPath, b: Rect, precision: f64, allowance: &mut usize) -> Result<Inscribed, InscribedError> {
// Flattening can close up or move an area thinner than its tolerance, so that the flattened
// outline holds nothing or its best center lies outside the curves: the outline is then
// flattened 16 times finer, up to 4 times (down to 1/65,536 of the tolerance). The resolved
// contours have an area, so an outline that is still not measured is past what the
// flattening can resolve (very long curves are flattened more coarsely).
let mut tolerance = precision / 2.0;
// The last edges searched: a finer tolerance can flatten to the same ones (very long curves),
// which would give the same center again.
let mut searched = None;
for attempt in 0..=FINER_FLATTENINGS {
let edges = edges(curves, tolerance)?;
let held = area(&edges);
let last = attempt == FINER_FLATTENINGS;
let fresh = searched.as_ref() != Some(&edges);
if fresh && (held > tolerance * tolerance || (last && held.partial_cmp(&0.0) == Some(Ordering::Greater))) {
match search(&edges, b, precision, allowance) {
Ok(center) => {
// The circle touches the nearest curve, whatever the flattening moved; those
// distances come out of the allowance too.
let pieces = curves.segments().count();
if *allowance < pieces {
return Err(InscribedError::TooComplex);
}
*allowance -= pieces;
let radius = curves.segments().map(|s| s.nearest(center, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt();
if radius.is_finite() && radius > 0.0 && fill_contains(curves, FillRule::NonZero, center) {
return Ok(Inscribed { center, radius });
}
}
Err(InscribedError::NoArea) => {}
Err(e) => return Err(e),
}
searched = Some(edges);
}
tolerance /= 16.0;
}
Err(InscribedError::TooComplex)
}
/// The search's precision for an area whose box is `b`.
fn precision_for(b: Rect) -> f64 {
INSCRIBED_PRECISION.min(b.width().min(b.height()) / 1000.0)
}
/// The straight edges of `curves` flattened to within `tolerance`, each subpath closed.
fn edges(curves: &kurbo::BezPath, tolerance: f64) -> Result<Vec<(Point, Point)>, InscribedError> {
let mut out = vec![];
let (mut start, mut last) = (None, None);
let close = |out: &mut Vec<(Point, Point)>, start: Option<Point>, last: Option<Point>| {
if let (Some(a), Some(b)) = (last, start)
&& a != b
{
out.push((a, b));
}
};
// Once past the limit, no further curve is flattened.
let over = std::cell::Cell::new(false);
vectorcraft_geom::flatten(curves.iter().take_while(|_| !over.get()), tolerance, |el| {
if over.get() {
return;
}
match el {
PathEl::MoveTo(p) => {
close(&mut out, start, last);
(start, last) = (Some(p), Some(p));
}
PathEl::LineTo(p) => {
if let Some(a) = last {
out.push((a, p));
}
last = Some(p);
}
PathEl::ClosePath => {
close(&mut out, start, last);
last = start;
}
_ => {}
}
over.set(out.len() > MAX_INSCRIBED_EDGES);
});
close(&mut out, start, last);
if over.get() || out.len() > MAX_INSCRIBED_EDGES {
return Err(InscribedError::TooComplex);
}
Ok(out)
}
/// The area the closed `edges` hold: their outer contours and holes turn opposite ways. Each
/// contour's points are taken from its first one, so a small area far from the origin is not
/// rounded away.
fn area(edges: &[(Point, Point)]) -> f64 {
let (mut total, mut contour) = (0.0, 0.0);
let (mut o, mut last) = (Point::ZERO, None);
for &(a, b) in edges {
// An edge that does not start where the last one ended starts the next contour.
if last != Some(a) {
total += contour;
(contour, o) = (0.0, a);
}
contour += (a - o).cross(b - o);
last = Some(b);
}
((total + contour) / 2.0).abs()
}
/// How far `p` lies inside the closed `edges` (nonzero winding): the distance to the nearest edge,
/// negative outside.
fn inside(edges: &[(Point, Point)], p: Point) -> f64 {
let mut winding = 0;
let mut nearest = f64::INFINITY;
for &(a, b) in edges {
if (a.y <= p.y) != (b.y <= p.y) {
let side = (b - a).cross(p - a);
if b.y > a.y && side > 0.0 {
winding += 1;
} else if b.y <= a.y && side < 0.0 {
winding -= 1;
}
}
nearest = nearest.min(distance_sq_to_segment(p, a, b));
}
let d = nearest.sqrt();
if winding != 0 { d } else { -d }
}
fn distance_sq_to_segment(p: Point, a: Point, b: Point) -> f64 {
let ab = b - a;
let len2 = ab.hypot2();
let t = if len2 > 0.0 { ((p - a).dot(ab) / len2).clamp(0.0, 1.0) } else { 0.0 };
(p - (a + ab * t)).hypot2()
}
/// A square cell of the search: its center, half its side, how far its center lies inside the
/// outline, and the most any of its points can.
#[derive(Clone, Copy)]
struct Cell {
center: Point,
half: f64,
inside: f64,
best: f64,
}
impl Cell {
fn new(edges: &[(Point, Point)], center: Point, half: f64) -> Self {
let inside = inside(edges, center);
Self { center, half, inside, best: inside + half * std::f64::consts::SQRT_2 }
}
}
impl PartialEq for Cell {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for Cell {}
impl PartialOrd for Cell {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Cell {
fn cmp(&self, other: &Self) -> Ordering {
self.best.total_cmp(&other.best)
}
}
/// The point of the closed `edges`, inside box `b`, farthest from every edge, within `precision`,
/// measuring at most `budget` distances from a point to an edge, and never more than
/// [`MAX_INSCRIBED_WORK`], and taking the ones it measured off `budget`.
fn search(edges: &[(Point, Point)], b: Rect, precision: f64, budget: &mut usize) -> Result<Point, InscribedError> {
let mut work = 0usize;
let found = search_measuring(edges, b, (precision, (*budget).min(MAX_INSCRIBED_WORK), MAX_INSCRIBED_CELLS), &mut work);
*budget = budget.saturating_sub(work);
found
}
/// [`search`] with `(precision, limit, max_cells)`, measuring at most `limit` distances (counted
/// in `work`) and keeping at most `max_cells` cells waiting.
fn search_measuring(edges: &[(Point, Point)], b: Rect, limits: (f64, usize, usize), work: &mut usize) -> Result<Point, InscribedError> {
let (precision, limit, max_cells) = limits;
// Square cells as wide as the box's narrower side, or wider when that would make more than
// `first` along the box or in all: at most MAX_FIRST_CELLS, and at most a quarter of the work
// limit, so the first cells take at most about three quarters of it.
let first = MAX_FIRST_CELLS.min((limit / edges.len().max(1) / 4) as f64).max(1.0);
let size = b.width().min(b.height()).max((b.area() / first).sqrt()).max(b.width().max(b.height()) / first);
let (cols, rows) = ((b.width() / size).ceil() as usize, (b.height() / size).ceil() as usize);
// Each cell is measured only when the limit still has room for it.
let measure = |work: &mut usize, center: Point, half: f64| {
let Some(after) = work.checked_add(edges.len()).filter(|&after| after <= limit) else {
return Err(InscribedError::TooComplex);
};
*work = after;
#[cfg(test)]
MEASURED.with(|m| m.set(*work));
Ok(Cell::new(edges, center, half))
};
// No circle in the box is wider than its narrower side.
let ceiling = b.width().min(b.height()) / 2.0;
// Until a center inside the outline is found, every cell that may hold one is split; after
// that, only cells that may beat the best center by more than the precision.
let open = |cell: &Cell, best: &Cell| cell.best > 0.0 && (best.inside <= 0.0 || cell.best - best.inside > precision);
let done = |best: &Cell| best.inside > 0.0 && best.inside >= ceiling - precision;
let mut best = measure(work, b.center(), 0.0)?;
let mut cells = BinaryHeap::new();
let add = |cells: &mut BinaryHeap<Cell>, best: &mut Cell, cell: Cell| {
if cell.inside > best.inside {
*best = cell;
}
// A best center at the ceiling ends the search, full queue or not.
if !done(best) && open(&cell, best) {
if cells.len() >= max_cells {
return Err(InscribedError::TooComplex);
}
cells.push(cell);
}
Ok(())
};
for row in 0..rows {
for col in 0..cols {
if done(&best) {
return Ok(best.center);
}
let at = Point::new(b.x0 + (col as f64 + 0.5) * size, b.y0 + (row as f64 + 0.5) * size);
let cell = measure(work, at, size / 2.0)?;
add(&mut cells, &mut best, cell)?;
}
}
while let Some(cell) = cells.pop() {
if done(&best) || !open(&cell, &best) {
break;
}
let h = cell.half / 2.0;
for (dx, dy) in [(-h, -h), (h, -h), (-h, h), (h, h)] {
if done(&best) {
return Ok(best.center);
}
let child = measure(work, cell.center + (dx, dy), h)?;
add(&mut cells, &mut best, child)?;
}
}
if best.inside <= 0.0 {
return Err(InscribedError::NoArea);
}
Ok(best.center)
}
@@ -0,0 +1,304 @@
use kurbo::{Point, Rect};
use vectorcraft_geom::hit::fill_contains;
use vectorcraft_geom::{Anchor, FillRule, PathData, SubPath, shapes};
use super::*;
fn polygon(pts: &[(f64, f64)]) -> PathData {
PathData::new(vec![SubPath::new(pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true)])
}
fn circle(x: f64, y: f64, r: f64) -> SubPath {
shapes::ellipse(Rect::new(x - r, y - r, x + r, y + r)).subpaths.remove(0)
}
/// Points around the circle `c`, a little inside its edge.
fn rim(c: Inscribed) -> impl Iterator<Item = Point> {
(0..360).map(move |i| {
let a = (i as f64).to_radians();
c.center + kurbo::Vec2::new(a.cos(), a.sin()) * (c.radius - 1e-6)
})
}
/// The circle lies in the filled area and is within twice the precision of `largest`, which may
/// be `slack` too small: a circle of four curves bulges up to 0.03% past a true circle.
fn holds_within(path: &PathData, rule: FillRule, c: Inscribed, largest: f64, slack: f64) {
let bp = path.to_bezpath();
assert!(rim(c).all(|p| fill_contains(&bp, rule, p)), "{c:?} reaches outside the fill");
assert!(c.radius <= largest + slack + 1e-6 && c.radius >= largest - 2.0 * INSCRIBED_PRECISION, "{c:?}, largest {largest}");
}
fn holds(path: &PathData, rule: FillRule, c: Inscribed, largest: f64) {
holds_within(path, rule, c, largest, 0.0);
}
#[test]
fn a_square_holds_the_circle_at_its_center() {
let sq = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
let c = inscribed_circle(&sq, FillRule::NonZero).unwrap();
holds(&sq, FillRule::NonZero, c, 50.0);
assert!((c.center - Point::new(50.0, 50.0)).hypot() < 2.0 * INSCRIBED_PRECISION, "{c:?}");
}
#[test]
fn a_concave_shape_holds_the_circle_in_its_corner() {
// An L whose arms are 30 wide: the box's center (50, 50) is outside it. The largest circle
// touches the two outer edges and the inner corner (30, 30): c = √2 (30 − c).
let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)]);
let c = inscribed_circle(&l, FillRule::NonZero).unwrap();
let largest = 30.0 * std::f64::consts::SQRT_2 / (1.0 + std::f64::consts::SQRT_2);
holds(&l, FillRule::NonZero, c, largest);
}
#[test]
fn a_ring_holds_the_circle_beside_its_hole_under_even_odd() {
let ring = PathData::new(vec![circle(0.0, 0.0, 100.0), circle(0.0, 0.0, 40.0)]);
let c = inscribed_circle(&ring, FillRule::EvenOdd).unwrap();
holds_within(&ring, FillRule::EvenOdd, c, 30.0, 0.0003 * 140.0);
assert!((c.center.to_vec2().hypot() - 70.0).abs() < 0.1, "{c:?}");
// Both subpaths turn the same way, so under nonzero the inner one fills in and is no hole.
let c = inscribed_circle(&ring, FillRule::NonZero).unwrap();
holds_within(&ring, FillRule::NonZero, c, 100.0, 0.0003 * 100.0);
}
#[test]
fn overlapping_subpaths_count_as_the_area_they_fill() {
// Two squares overlapping by half: under nonzero they fill one 150 × 100 rectangle, and the
// edges inside it do not bound the circle.
let a = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
let b = polygon(&[(50.0, 0.0), (150.0, 0.0), (150.0, 100.0), (50.0, 100.0)]);
let both = PathData::new(a.subpaths.into_iter().chain(b.subpaths).collect());
let c = inscribed_circle(&both, FillRule::NonZero).unwrap();
holds(&both, FillRule::NonZero, c, 50.0);
}
#[test]
fn a_small_shape_is_measured_to_its_own_scale() {
// The L of the concave test, a thousandth of its size.
let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)].map(|(x, y)| (x / 1000.0, y / 1000.0)));
let c = inscribed_circle(&l, FillRule::NonZero).unwrap();
let largest = 0.03 * std::f64::consts::SQRT_2 / (1.0 + std::f64::consts::SQRT_2);
assert!(c.radius <= largest + 1e-9 && c.radius > largest * 0.99, "{c:?}, largest {largest}");
}
#[test]
fn a_shape_narrower_than_the_default_precision_gets_a_circle() {
// 0.005 pt square: resolved at 0.01 pt it would be dropped as a sliver.
let sq = polygon(&[(0.0, 0.0), (0.005, 0.0), (0.005, 0.005), (0.0, 0.005)]);
let c = inscribed_circle(&sq, FillRule::NonZero).unwrap();
assert!(c.radius <= 0.0025 + 1e-12 && c.radius > 0.0025 * 0.99, "{c:?}");
}
#[test]
fn a_tiny_shape_far_from_the_origin_gets_a_circle() {
let sq = polygon(&[(10_000.0, 10_000.0), (10_000.000_1, 10_000.0), (10_000.000_1, 10_000.000_1), (10_000.0, 10_000.000_1)]);
let c = inscribed_circle(&sq, FillRule::NonZero).unwrap();
assert!(c.radius > 0.00005 * 0.99 && c.radius <= 0.00005 + 1e-9, "{c:?}");
// With a second tiny square far from the first, each square's area is measured from its own
// corner.
let near = polygon(&[(0.0, 0.0), (0.0001, 0.0), (0.0001, 0.0001), (0.0, 0.0001)]);
let far = polygon(&[(1e6, 1e6), (1e6 + 0.0001, 1e6), (1e6 + 0.0001, 1e6 + 0.0001), (1e6, 1e6 + 0.0001)]);
let both = PathData::new(near.subpaths.into_iter().chain(far.subpaths).collect());
let a = area(&edges(&both.to_bezpath(), 0.005).unwrap());
assert!((a - 2e-8).abs() < 1e-10, "{a}");
}
#[test]
fn a_hairline_hole_bounds_the_circle() {
// A 100 pt square with a hole 0.001 pt wide down its middle: the circle stays on one side.
let sq = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
let slit = polygon(&[(49.9995, 10.0), (50.0005, 10.0), (50.0005, 90.0), (49.9995, 90.0)]);
let both = PathData::new(sq.subpaths.into_iter().chain(slit.subpaths).collect());
let c = inscribed_circle(&both, FillRule::EvenOdd).unwrap();
assert!((c.center.x - 50.0).abs() >= c.radius - 2.0 * INSCRIBED_PRECISION, "{c:?}");
assert!(c.radius < 30.0, "{c:?}");
}
#[test]
fn a_long_thin_shape_is_refused_without_measuring_past_the_work_limit() {
// A strip 5,000 long, 1 high at one end and 2 at the other, whose top edge has 5,000 pieces:
// cut into cells as wide as it is high, the first cells alone would measure 2,500 times every
// edge.
let n = 5000;
let top: Vec<(f64, f64)> = (0..=n).map(|i| (i as f64, 0.0)).collect();
let pts: Vec<(f64, f64)> = top.into_iter().chain([(n as f64, 1.0), (0.0, 2.0)]).collect();
let e = edges(&polygon(&pts).to_bezpath(), 0.005).unwrap();
let limit = 100 * e.len();
assert_eq!(search(&e, Rect::new(0.0, 0.0, n as f64, 2.0), 0.01, &mut limit.clone()), Err(InscribedError::TooComplex));
let measured = MEASURED.with(std::cell::Cell::get);
assert!(measured <= limit, "{measured} measured, limit {limit}");
}
#[test]
fn a_long_rectangle_stops_once_no_wider_circle_fits() {
// Every point of the center line is 50 from the long sides: the box's center is already the
// largest circle's, and the search stops at the first cells.
let r = polygon(&[(0.0, 0.0), (100_000.0, 0.0), (100_000.0, 100.0), (0.0, 100.0)]);
let c = inscribed_circle(&r, FillRule::NonZero).unwrap();
holds(&r, FillRule::NonZero, c, 50.0);
let measured = MEASURED.with(std::cell::Cell::get);
assert!(measured <= (MAX_FIRST_CELLS as usize + 1) * 4, "{measured} measured");
}
#[test]
fn a_fill_far_smaller_than_the_precision_still_gets_a_circle() {
// Two 0.001 pt squares at opposite corners of a 100 pt box, which sets the precision to
// 0.01 pt.
let a = polygon(&[(0.0, 0.0), (0.001, 0.0), (0.001, 0.001), (0.0, 0.001)]);
let b = polygon(&[(99.999, 99.999), (100.0, 99.999), (100.0, 100.0), (99.999, 100.0)]);
let both = PathData::new(a.subpaths.into_iter().chain(b.subpaths).collect());
let c = inscribed_circle(&both, FillRule::NonZero).unwrap();
assert!(c.radius > 0.0 && c.radius <= 0.0005 + 1e-9, "{c:?}");
assert!(fill_contains(&both.to_bezpath(), FillRule::NonZero, c.center), "{c:?}");
}
#[test]
fn a_lens_thinner_than_the_flattening_tolerance_gets_a_circle() {
// A straight side and a curve bowed 0.001 pt from it, 141 pt long: flattened to 0.005 pt the
// curve would lie on the straight side.
let lens = |side: f64| {
let n = kurbo::Vec2::new(1.0, -1.0) / 2f64.sqrt() * (0.001 / 0.75);
let (a, b) = (Point::ZERO, Point::new(side, side));
PathData::new(vec![SubPath::new(
vec![
Anchor::with_handles(a, Point::new(side / 3.0, side / 3.0) + n, a),
Anchor::with_handles(b, b, Point::new(side * 2.0 / 3.0, side * 2.0 / 3.0) + n),
],
true,
)])
};
let l = lens(100.0);
let c = inscribed_circle(&l, FillRule::NonZero).unwrap();
assert!(c.radius > 0.0 && c.radius <= 0.0005 + 1e-9, "{c:?}");
assert!(fill_contains(&l.to_bezpath(), FillRule::NonZero, c.center), "{c:?}");
// A curve that long is flattened too coarsely to show the bow at all: too complex, not empty.
assert_eq!(inscribed_circle(&lens(1e6), FillRule::NonZero), Err(InscribedError::TooComplex));
}
#[test]
fn a_bowed_strip_thinner_than_the_flattening_tolerance_is_not_reported_empty() {
// Two curves 0.001 pt apart, both bowed 0.003 pt the same way: flattened to 0.005 pt they
// become a straight strip that lies outside the bowed one.
let strip = |side: f64| {
let unit = kurbo::Vec2::new(1.0, -1.0) / 2f64.sqrt();
let (bow, gap) = (unit * (0.003 / 0.75), unit * 0.001);
let (a, b) = (Point::ZERO, Point::new(side, side));
let third = (b - a) / 3.0;
let (a1, b1) = (a + gap, b + gap);
PathData::new(vec![SubPath::new(
vec![
Anchor::with_handles(a, a, a + third + bow),
Anchor::with_handles(b, b - third + bow, b),
Anchor::with_handles(b1, b1, b1 - third + bow),
Anchor::with_handles(a1, a1 + third + bow, a1),
],
true,
)])
};
let inside = |s: &PathData, c: Inscribed| {
assert!(c.radius > 0.0 && c.radius <= 0.0005 + 1e-9, "{c:?}");
// Measured against the curves flattened to 1e-8 pt by kurbo itself, which does not
// coarsen long curves: kurbo's winding can miss a curve a point lies this close to.
let mut polyline = kurbo::BezPath::new();
kurbo::flatten(s.to_bezpath(), 1e-8, |el| polyline.push(el));
let fine = edges(&polyline, 1e-8).unwrap();
assert!(rim(c).all(|p| super::inside(&fine, p) > 1e-8), "{c:?} reaches outside");
};
// 28 and 141 pt long: a circle inside it, or too complex to measure; never "no area".
for side in [20.0, 100.0] {
let s = strip(side);
match inscribed_circle(&s, FillRule::NonZero) {
Ok(c) => inside(&s, c),
e => assert_eq!(e, Err(InscribedError::TooComplex), "{side}"),
}
}
}
#[test]
fn a_thin_turned_rectangle_gets_the_circle_at_its_center() {
// 100 pt long and 0.009998 pt wide, turned 45°: no wider than twice the flattening tolerance.
let (u, v) = (kurbo::Vec2::new(1.0, 1.0) / 2f64.sqrt(), kurbo::Vec2::new(1.0, -1.0) / 2f64.sqrt());
let (along, across) = (u * 100.0, v * 0.009998);
let corners = [Point::ZERO, Point::ZERO + along, Point::ZERO + along + across, Point::ZERO + across];
let r = polygon(&corners.map(|p| (p.x, p.y)));
let c = inscribed_circle(&r, FillRule::NonZero).unwrap();
holds(&r, FillRule::NonZero, c, 0.004999);
assert!(c.radius > 0.004999 * 0.99, "{c:?}");
// 1,000 pt long and 0.0001 pt wide: also measured at the center.
let (along, across) = (u * 1000.0, v * 0.0001);
let corners = [Point::ZERO, Point::ZERO + along, Point::ZERO + along + across, Point::ZERO + across];
let r = polygon(&corners.map(|p| (p.x, p.y)));
let c = inscribed_circle(&r, FillRule::NonZero).unwrap();
assert!(c.radius > 0.00005 * 0.99 && c.radius <= 0.00005 + 1e-9, "{c:?}");
}
#[test]
fn a_search_past_its_cell_limit_is_too_complex() {
let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)]);
let e = edges(&l.to_bezpath(), 0.005).unwrap();
let b = Rect::new(0.0, 0.0, 100.0, 100.0);
assert!(search_measuring(&e, b, (0.01, MAX_INSCRIBED_WORK, MAX_INSCRIBED_CELLS), &mut 0).is_ok());
assert_eq!(search_measuring(&e, b, (0.01, MAX_INSCRIBED_WORK, 10), &mut 0), Err(InscribedError::TooComplex));
}
#[test]
fn an_outline_with_too_many_edges_is_too_complex() {
let zigzag: Vec<(f64, f64)> = (0..=MAX_INSCRIBED_EDGES).map(|i| (i as f64, (i % 2) as f64)).chain([(0.0, -10.0)]).collect();
let bp = polygon(&zigzag).to_bezpath();
assert_eq!(edges(&bp, 0.005), Err(InscribedError::TooComplex));
// Too many anchors are refused before the outline is resolved, even on a line that would
// otherwise fill no area.
let line: Vec<(f64, f64)> = (0..=MAX_INSCRIBED_EDGES).map(|i| (i as f64, 0.0)).collect();
assert_eq!(inscribed_circle(&polygon(&line), FillRule::NonZero), Err(InscribedError::TooComplex));
assert_eq!(inscribed_circle(&polygon(&line[..1000]), FillRule::NonZero), Err(InscribedError::NoArea));
assert_eq!(edges(&polygon(&zigzag[..1000]).to_bezpath(), 0.005).map(|e| e.len()), Ok(1000));
}
#[test]
fn a_search_past_its_work_limit_is_too_complex() {
let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)]);
let e = edges(&l.to_bezpath(), 0.005).unwrap();
let b = Rect::new(0.0, 0.0, 100.0, 100.0);
assert!(search(&e, b, 0.01, &mut MAX_INSCRIBED_WORK.clone()).is_ok());
assert_eq!(search(&e, b, 0.01, &mut (20 * e.len())), Err(InscribedError::TooComplex));
}
#[test]
fn searches_that_share_a_budget_stop_when_it_runs_out() {
let l = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)]);
let mut work = MAX_INSCRIBED_WORK;
assert!(inscribed_circle_within(&l, FillRule::NonZero, &mut work).is_ok());
let one = MAX_INSCRIBED_WORK - work;
assert!(one > 0);
// Enough for one search and half of another: the first fits, the second runs out.
let mut work = one + one / 2;
assert!(inscribed_circle_within(&l, FillRule::NonZero, &mut work).is_ok());
assert!(work < one, "{work} left of {one}");
assert_eq!(inscribed_circle_within(&l, FillRule::NonZero, &mut work), Err(InscribedError::TooComplex));
// One distance short of a whole search: refused without measuring past the budget.
let mut work = one - 1;
assert_eq!(inscribed_circle_within(&l, FillRule::NonZero, &mut work), Err(InscribedError::TooComplex));
let measured = MEASURED.with(std::cell::Cell::get);
assert!(measured < one, "{measured} measured, budget {}", one - 1);
}
#[test]
fn an_area_the_fill_rule_leaves_small_is_measured_to_its_own_scale() {
// Two identical 100 pt squares cancel under even-odd, leaving the small L of the test above:
// the outline's box is 100 pt across, the filled area's 0.1 pt.
let sq = polygon(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]);
let l = polygon(
&[(0.0, 0.0), (100.0, 0.0), (100.0, 30.0), (30.0, 30.0), (30.0, 100.0), (0.0, 100.0)].map(|(x, y)| (x / 1000.0 + 50.0, y / 1000.0 + 50.0)),
);
let all = PathData::new(sq.subpaths.iter().cloned().chain(sq.subpaths.iter().cloned()).chain(l.subpaths).collect());
let c = inscribed_circle(&all, FillRule::EvenOdd).unwrap();
let largest = 0.03 * std::f64::consts::SQRT_2 / (1.0 + std::f64::consts::SQRT_2);
assert!(c.radius <= largest + 1e-9 && c.radius > largest * 0.99, "{c:?}, largest {largest}");
}
#[test]
fn a_shape_with_no_area_has_no_circle() {
let flat = polygon(&[(0.0, 0.0), (100.0, 0.0), (50.0, 0.0)]);
assert_eq!(inscribed_circle(&flat, FillRule::NonZero), Err(InscribedError::NoArea));
assert_eq!(inscribed_circle(&PathData::default(), FillRule::NonZero), Err(InscribedError::NoArea));
}
+3
View File
@@ -114,6 +114,9 @@ pub(crate) struct Exporter<'a> {
/// Overprinting characters' fills and strokes are drawn with Darken, as a separation's plate
/// draws its overprinting fills and strokes ([`vectorcraft_doc::overprint::darken_overprints`]).
pub darken_overprints: bool,
/// Document Setup → Discard White Overprint as it applies to the document's paints, read from
/// the document on first use ([`Self::paper_white`]).
discard_white: Option<vectorcraft_doc::overprint::DiscardWhite>,
/// An overprinting fill or stroke was drawn so.
pub overprinted: bool,
/// Characters with neither fill nor stroke, or whose fill is drawn as art (outlines filled
+1
View File
@@ -64,6 +64,7 @@ impl<'a> Exporter<'a> {
mask_art_left_out: false,
overprint: false,
darken_overprints: false,
discard_white: None,
overprinted: false,
invisible: false,
inline_depth: 0,
+29 -12
View File
@@ -523,12 +523,11 @@ impl Exporter<'_> {
}
/// Draw image `im` of node `n` colorized with `p` ([`Self::colorized_image`]), overprinting
/// when its color does ([`Node::colorize_overprints`]). A white color that is not a spot ink
/// ([`Document::spot_ink`]) and overprints (Discard White Overprint off) puts no ink down, so
/// it paints nothing.
/// when its color does ([`Node::colorize_overprints`]). A paper white color ([`Self::paper_white`])
/// that overprints (Discard White Overprint off) puts no ink down, so it paints nothing.
fn colorized(&mut self, s: &mut Surface, n: &Node, im: &vectorcraft_doc::ImageObject, p: &Paint) {
let overprint = n.colorize_overprints() && self.overprint;
if overprint && !self.doc.setup.discard_white_overprint && !self.doc.spot_ink(p) && vectorcraft_doc::overprint::is_white(p) {
if overprint && !self.doc.setup.discard_white_overprint && self.paper_white(p) {
return;
}
match self.colorized_image(im, p, !n.extras().pixelated, overprint) {
@@ -634,11 +633,10 @@ impl Exporter<'_> {
}
/// Draw a fill or stroke of `paint` with `draw`: as a form marked to overprint when it
/// `overprints`, paints and overprints are kept (but not a white one with Discard White
/// Overprint, [`Document::discards_white_overprint`]).
/// `overprints`, paints and overprints are kept (but not a paper white one with Discard White
/// Overprint, [`Self::discards_white`]).
pub(super) fn overprinting(&mut self, s: &mut Surface, overprints: bool, paint: &Paint, draw: impl FnOnce(&mut Self, &mut Surface)) {
let white = || self.doc.discards_white_overprint(paint);
if overprints && self.overprint && !paint.is_none() && !white() {
if overprints && self.overprint && !paint.is_none() && !self.discards_white(paint) {
self.overprinted = true;
crate::forms::form(s, Mark::Overprint, |s| draw(self, s));
} else {
@@ -647,11 +645,10 @@ impl Exporter<'_> {
}
/// [`Self::overprinting`] for a character fill or stroke, which has no blend mode of its own:
/// with [`Self::darken_overprints`] an overprinting one is drawn with Darken (not a white one
/// with Discard White Overprint).
/// with [`Self::darken_overprints`] an overprinting one is drawn with Darken (not a paper
/// white one with Discard White Overprint).
pub(super) fn char_overprinting(&mut self, s: &mut Surface, overprints: bool, paint: &Paint, draw: impl FnOnce(&mut Self, &mut Surface)) {
let white = self.doc.discards_white_overprint(paint);
if overprints && self.darken_overprints && !paint.is_none() && !white {
if overprints && self.darken_overprints && !paint.is_none() && !self.discards_white(paint) {
s.push_blend_mode(krilla::blend::BlendMode::Darken);
self.overprinting(s, overprints, paint, draw);
s.pop();
@@ -660,6 +657,26 @@ impl Exporter<'_> {
}
}
/// Whether paint `p` knocks out where it overprints under Document Setup → Discard White
/// Overprint ([`vectorcraft_doc::overprint::DiscardWhite::discards`]).
fn discards_white(&mut self, p: &Paint) -> bool {
self.doc.setup.discard_white_overprint && self.paper_white(p)
}
/// Whether paint `p` is paper white ([`vectorcraft_doc::overprint::DiscardWhite::paper_white`]):
/// white, and not a tint above 0% of one of the document's spot inks. The spot ink names are
/// read only for a white linked to a swatch.
fn paper_white(&mut self, p: &Paint) -> bool {
if !vectorcraft_doc::overprint::is_white(p) {
return false;
}
if !matches!(p, Paint::Solid { swatch: Some(_), .. }) {
return true;
}
let doc = self.doc;
self.discard_white.get_or_insert_with(|| vectorcraft_doc::overprint::DiscardWhite::of(doc)).paper_white(p)
}
/// Is `p` a paint PDF has no paint for when it paints a fill (`fill`) or a stroke, which
/// [`Self::area`] draws as art: a pattern swatch or a gradient drawn as pixels
/// ([`vectorcraft_color::GradientPaint::draws_as_pixels`]), but not a Perceptual one of spot
+2 -2
View File
@@ -238,7 +238,7 @@ impl<'a> Separator<'a> {
/// Overprinting fills and strokes of `a`'s subtree with a Normal blending mode, and
/// overprinting character fills and strokes, that put none of ink `plate` down leave its plate
/// as it is: they are drawn as nothing on it (white ones that `discard_white` knocks out
/// as it is: they are drawn as nothing on it (paper white ones that `discard_white` knocks out
/// aside, [`DiscardWhite::discards`]). A writer without blending modes (PostScript) then keeps the ink below them,
/// where it would draw their Darken as a knockout. One that puts any ink down is drawn, and on
/// a PostScript plate its ink replaces the ink below, as a nonzero component of an overprinting
@@ -296,7 +296,7 @@ impl<'a> Separator<'a> {
/// ink the plate below shows through instead of being knocked out.
pub fn plate(&self, plate: &str) -> Document {
let mut d = self.doc.clone();
let discard_white = DiscardWhite::of(self.doc);
let discard_white = DiscardWhite::printing(&d, |n| !self.converts(n));
let mut colorized = BTreeSet::new();
let nodes = d.layers.iter_mut().chain(d.symbols.iter_mut().map(|s| &mut s.art)).chain(d.patterns.iter_mut().flat_map(|p| p.art.iter_mut()));
for n in nodes {
+10
View File
@@ -399,6 +399,16 @@ fn a_white_spot_ink_image_overprints_with_discard_white_overprint() {
assert_eq!(p.layers[0].children().unwrap()[0].visible, name == "White Ink", "{name}");
}
}
// Printed as process inks, the white ink is paper white: the image knocks out on every plate.
let converted = serde_json::json!({"output": {"mode": "separations", "inks": [{"name": "White Ink", "convertToProcess": true}]}});
let settings: PrintSettings = serde_json::from_value(converted).unwrap();
for postscript in [true, false] {
let job = plan(&d, &PrintOptions { settings: settings.clone(), postscript, ..Default::default() }).unwrap();
assert!(!job.plates.is_empty());
for p in &job.plates {
assert!(p.layers[0].children().unwrap()[0].visible, "a converted white ink knocks out");
}
}
}
/// An overprinting colorized image whose pixels don't take its color (a color preview of its
+22
View File
@@ -352,6 +352,28 @@ fn white_overprint_is_discarded_as_the_document_setup_says() {
assert_eq!(overprints(&d, json!({})).1, 3);
}
#[test]
fn a_white_spot_ink_keeps_overprinting_under_discard_white_overprint() {
let white = Color::cmyk(0.0, 0.0, 0.0, 0.0);
let mut d = overprinting(white);
d.swatches.push(vectorcraft_color::Swatch { name: "Opaque White".into(), paint: Paint::solid(white), global: true, spot: true });
let paint = |d: &mut Document, p: &Paint| {
for n in std::sync::Arc::make_mut(&mut d.layers[0]).children_mut().into_iter().flatten() {
let n = std::sync::Arc::make_mut(n);
if let Some(f) = n.appearance.fill_mut().filter(|f| f.overprint) {
f.paint = p.clone();
}
if let NodeKind::Text(t) = &mut n.kind {
t.runs.iter_mut().for_each(|r| r.style.fill = p.clone());
}
}
};
paint(&mut d, &Paint::solid(white));
assert_eq!(overprints(&d, json!({})).1, 1, "paper white fills and characters knock out");
paint(&mut d, &Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 1.0 });
assert_eq!(overprints(&d, json!({})).1, 3, "a white spot ink overprints, characters too");
}
#[test]
fn pdf_a_overprint_mode_is_0() {
let r = export(&overprinting(RED), json!({"standard": "pdfA2b", "compression": {"compressText": false}}));
+42 -1
View File
@@ -4,7 +4,7 @@
use std::sync::Arc;
use serde_json::json;
use vectorcraft_color::{Color, Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Paint, Swatch};
use vectorcraft_color::{BlendMode, Color, Freeform, FreeformPoint, Gradient, GradientKind, GradientPaint, GradientStop, Paint, Swatch};
use vectorcraft_doc::{Appearance, Artboard, Document, LayerColor, Node, NodeKind};
use vectorcraft_geom::{Rect, shapes};
use vectorcraft_testkit::raster::render_region;
@@ -903,6 +903,47 @@ fn overprinting_near_blacks_linked_to_a_missing_swatch_keep_the_cyan_on_postscri
assert_eq!(drawn(true, 3), (3, 1, 1), "PostScript Black plate: every black, not the faint fill");
}
#[test]
fn a_white_spot_ink_keeps_overprinting_on_plates_and_in_simulated_composites() {
// With Discard White Overprint on (the default), a paper white square over cyan knocks the
// cyan out; one in a white spot ink overprints: it puts no cyan down, so the cyan plate draws
// nothing for it, and Simulate composites it with Darken.
let white = Color::cmyk(0.0, 0.0, 0.0, 0.0);
let square = |paint: Paint| {
let mut n =
Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(10.0, 15.0, 30.0, 35.0)), Appearance::basic(paint, Paint::None, 0.0));
if let Some(f) = n.appearance.fill_mut() {
f.overprint = true;
}
let mut d = over_cyan(vec![n]);
d.swatches.push(Swatch { name: "Opaque White".into(), paint: Paint::solid(white), global: true, spot: true });
d
};
let (paper, spot) = (square(Paint::solid(white)), square(Paint::Solid { color: white, swatch: Some("Opaque White".into()), tint: 1.0 }));
assert!(paper.setup.discard_white_overprint);
let cyan_fills = |d: &Document, output: serde_json::Value| {
let opts = PrintOptions { settings: settings(json!({"output": output})), ..Default::default() };
let p = plan(d, &opts).unwrap();
let mut count = 0;
p.plates[0].walk(|n| count += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none())));
count
};
let seps = json!({"mode": "separations"});
assert_eq!((cyan_fills(&paper, seps.clone()), cyan_fills(&spot, seps)), (2, 1), "paper white knocks out; the spot white leaves the cyan");
// The white ink printed as process inks is paper white.
let converted = json!({"mode": "separations", "inks": [{"name": "Opaque White", "convertToProcess": true}]});
assert_eq!(cyan_fills(&spot, converted), 2, "a converted spot white knocks out");
assert_eq!(cyan_fills(&spot, json!({"mode": "separations", "spotsToProcess": true})), 2, "so does one with every spot converted");
let blends = |d: &Document| {
let opts = PrintOptions { settings: settings(json!({"advanced": {"overprints": "simulate"}})), ..Default::default() };
let p = plan(d, &opts).unwrap();
let mut out = vec![];
p.doc.walk(|n| out.extend(n.appearance.fill().filter(|f| f.paint.color() == Some(white)).map(|f| f.blend)));
out
};
assert_eq!((blends(&paper), blends(&spot)), (vec![BlendMode::Normal], vec![BlendMode::Darken]));
}
#[test]
fn an_overprinting_fill_keeps_its_faint_ink_on_pdf_plates() {
// 0.4% cyan beside 100% K, set to overprint: a PDF plate draws it with Darken, a PostScript
+1 -1
View File
@@ -52,7 +52,7 @@ pub mod wat;
pub use dialog::ParamUi;
pub use host::{LogLevel, LogLine, Report};
pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec};
pub use manifest::{Budget, Command, InputKind, Kind, Manifest, MenuPlace, Param, ParamSpec};
pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms};
#[doc(hidden)]
pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE};
+185 -8
View File
@@ -34,6 +34,74 @@ pub const MAX_ALLOWED_COMMANDS: usize = 256;
/// Longest command id a manifest's `commandAllowlist` names, in bytes.
pub const MAX_ALLOWED_ID: usize = 128;
/// The menus a command's `menu` may name, each as its path of English menu labels. File, Window,
/// Help and the application menu are not among them, and neither are the submenus that list
/// files, fonts, panels or other plug-ins.
pub const MENU_PLACES: &[&[&str]] = &[
&["Edit"],
&["Edit", "Edit Colors"],
&["Object"],
&["Object", "Transform"],
&["Object", "Arrange"],
&["Object", "Path"],
&["Object", "Compound Path"],
&["Object", "Clipping Mask"],
&["Type"],
&["Select"],
&["Select", "Same"],
&["Select", "Object"],
&["Effect"],
&["View"],
];
/// Where a command's `menu` places it: in the menu at `path` (one of [`MENU_PLACES`]), after the
/// built-in item labeled `after` (1 to 64 printable characters), or at the end of that menu when
/// `after` is left out or names no built-in item there.
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct MenuPlace {
pub path: &'static [&'static str],
#[serde(skip_serializing_if = "Option::is_none")]
pub after: Option<String>,
}
impl MenuPlace {
/// Reads a command's `menu` value: `{"path": [label, …], "after"?: label}`.
fn read(v: &Value) -> std::result::Result<MenuPlace, String> {
let wrong_path = || {
let k = "menu.path";
let places: Vec<String> =
MENU_PLACES.iter().map(|p| format!("[{}]", p.iter().map(|l| format!("{l:?}")).collect::<Vec<_>>().join(", "))).collect();
format!("`{k}` must be one of {}", places.join(", "))
};
let Some(o) = v.as_object() else {
let key = "menu";
return Err(format!("`{key}` must be an object"));
};
if let Some(k) = o.keys().find(|k| !matches!(k.as_str(), "path" | "after")) {
let k = crate::permissions::display_text(k, crate::permissions::MAX_SHOWN_FIELD);
return Err(format!("unknown key `{k}`; the keys here are {}", "path, after"));
}
let path: Vec<&str> = match o.get("path").and_then(Value::as_array) {
Some(path) => path.iter().map(Value::as_str).collect::<Option<_>>().ok_or_else(wrong_path)?,
None => return Err(wrong_path()),
};
let path = *MENU_PLACES.iter().find(|p| **p == path.as_slice()).ok_or_else(wrong_path)?;
let key = "menu.after";
let after = match o.get("after") {
None => None,
Some(Value::String(s)) => {
let trimmed = s.trim();
if trimmed.is_empty() || s.chars().count() > 64 || s.chars().any(char::is_control) {
return Err(format!("`{key}` must be 1-64 printable characters"));
}
Some(trimmed.to_string())
}
Some(_) => return Err(format!("`{key}` must be a string")),
};
Ok(MenuPlace { path, after })
}
}
/// What a plug-in is.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -223,9 +291,9 @@ pub struct Param {
}
/// A menu command a plug-in adds (`commands`): the host lists it under Object › Plug-ins › the
/// plug-in's name (Effect › Plug-ins for a live effect's), runs it as the command
/// `plugin.<plug-in id>.<id>`, and calls the plug-in's `vc_run` with `_context.command` set to
/// `id` and the parameters it declares.
/// plug-in's name (Effect › Plug-ins for a live effect's), or in the menu its `menu` names, runs it
/// as the command `plugin.<plug-in id>.<id>`, and calls the plug-in's `vc_run` with
/// `_context.command` set to `id` and the parameters it declares.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Command {
/// `[a-z][a-z0-9_]*`, at most [`MAX_COMMAND_ID`] characters, unique within the manifest.
@@ -236,6 +304,13 @@ pub struct Command {
/// Parameters in declaration (dialog) order, declared as the manifest's own are.
#[serde(default, deserialize_with = "ordered_params", serialize_with = "params_as_object")]
pub params: Vec<(String, Param)>,
/// The menu it is listed in instead of the plug-in's submenu (`menu`, read at
/// [`crate::permissions::MENU_API`] and later).
#[serde(rename = "menu", skip_deserializing, skip_serializing_if = "Option::is_none")]
pub place: Option<MenuPlace>,
/// Each `menu` value the manifest gives, until [`Manifest::parse`] reads them.
#[serde(skip)]
pub(crate) declared_menu: Vec<Value>,
}
impl Command {
@@ -244,6 +319,18 @@ impl Command {
pub fn shown_label(&self) -> String {
crate::permissions::display_text(self.label.trim(), crate::permissions::MAX_SHOWN_NAME)
}
/// The label its menu item shows for plug-in `plugin_name`: [`Command::shown_label`], and for a
/// command placed in another menu, followed by the plug-in's name in parentheses.
pub fn menu_label(&self, plugin_name: &str) -> String {
match self.place {
None => self.shown_label(),
Some(_) => {
let name = crate::permissions::display_text(plugin_name.trim(), crate::permissions::MAX_SHOWN_NAME);
format!("{} ({name})", self.shown_label())
}
}
}
}
impl From<ParamSpec> for Param {
@@ -364,8 +451,9 @@ impl Manifest {
if serde_json::from_str::<Value>(text).is_ok_and(|v| v.get("paintOutput").is_some_and(|p| *p != Value::Bool(true))) {
return Err(Error::Manifest("`paintOutput` may only be true".into()));
}
let man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(format!("manifest: {e}")))?;
let mut man: Manifest = serde_json::from_str(text).map_err(|e| Error::Manifest(format!("manifest: {e}")))?;
man.validate()?;
man.read_places()?;
Ok(man)
}
@@ -401,6 +489,31 @@ impl Manifest {
self.commands.iter().find(|c| c.id == id)
}
/// Reads each command's `menu` into its [`Command::place`] at
/// [`crate::permissions::MENU_API`] and later, and drops it below that level, where the key is
/// ignored. A `menu` that names a menu outside [`MENU_PLACES`], has the wrong shape or is given
/// twice is refused, and the error names the command.
fn read_places(&mut self) -> Result<()> {
let reads = self.api >= permissions::MENU_API;
for (i, c) in self.commands.iter_mut().enumerate() {
let menus = std::mem::take(&mut c.declared_menu);
if !reads {
continue;
}
let name = command_name(i, &c.id);
let place = match menus.as_slice() {
[] => continue,
[menu] => MenuPlace::read(menu),
_ => {
let key = "menu";
Err(format!("duplicate field `{key}`"))
}
};
c.place = Some(place.map_err(|e| Error::Manifest(format!("command {name}: {e}")))?);
}
Ok(())
}
/// Checks what the module declared: its id, name and text lengths, its extensions, a budget its
/// kind may have (only a filter may be heavy), and each parameter and its dialog layout.
fn validate(&self) -> Result<()> {
@@ -809,7 +922,7 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu
Err(A::Error::custom(self.wrong()))
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> std::result::Result<Command, A::Error> {
let (mut id, mut label, mut params) = (None::<String>, None::<String>, None::<Params>);
let (mut id, mut label, mut params, mut menu) = (None::<String>, None::<String>, None::<Params>, Vec::<Value>::new());
let named = |id: &Option<String>, e: &dyn std::fmt::Display| {
A::Error::custom(format!("command {}: {e}", command_name(self.0, id.as_deref().unwrap_or_default())))
};
@@ -828,6 +941,11 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu
params = Some(map.next_value().map_err(|e| named(&id, &e))?);
false
}
// A repeated `menu` is refused only where the key is read ([`Manifest::parse`]).
"menu" => {
menu.push(map.next_value().map_err(|e| named(&id, &e))?);
false
}
"id" | "label" | "params" => true,
_ => {
map.next_value::<IgnoredAny>()?;
@@ -844,7 +962,7 @@ fn ordered_commands<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Resu
let Some(label) = label else {
return Err(named(&Some(id), &"missing field `label`"));
};
Ok(Command { id, label, params: params.map(|p| p.0).unwrap_or_default() })
Ok(Command { id, label, params: params.map(|p| p.0).unwrap_or_default(), place: None, declared_menu: menu })
}
}
@@ -1220,7 +1338,7 @@ mod tests {
}
/// A filter or a live effect lists menu commands with their own parameters; a `menu` key is
/// ignored. A malformed entry, a bad or repeated id, a label that isn't printable and too many
/// ignored at API level 1. A malformed entry, a bad or repeated id, a label that isn't printable and too many
/// commands are refused, and the error names the command.
#[test]
fn commands_are_checked_and_errors_name_them() {
@@ -1242,7 +1360,7 @@ mod tests {
assert!(serde_json::to_value(Manifest::parse(br#"{"id":"a","name":"x","kind":"filter"}"#).unwrap()).unwrap().get("commands").is_none());
let effect = Manifest::parse(br#"{"id":"a","name":"x","kind":"effect","commands":[{"id":"c","label":"C"}]}"#).unwrap();
assert_eq!(effect.commands.len(), 1);
let label = |l: &str| Command { id: "c".into(), label: l.into(), params: Vec::new() }.shown_label();
let label = |l: &str| Command { id: "c".into(), label: l.into(), params: Vec::new(), place: None, declared_menu: Vec::new() }.shown_label();
assert_eq!(label("Flip\u{202E}txt.exe"), "Flip\\u{202E}txt.exe");
let many: Vec<String> = (0..=MAX_COMMANDS).map(|i| format!(r#"{{"id":"c{i}","label":"C"}}"#)).collect();
@@ -1298,6 +1416,65 @@ mod tests {
assert!(hidden.unwrap_err().to_string().contains("command `x\\u{202E}`"), "an id in an error is escaped");
}
/// At API level 2 a command's `menu` places it in one of [`MENU_PLACES`], after a named item or
/// at the end; a menu outside them (File, Help, Window, Edit › Preferences) or a `menu` of the
/// wrong shape is refused and the error names the command. At level 1 the key is ignored.
#[test]
fn a_command_menu_names_an_allowed_place() {
let with = |api: u32, menu: &str| {
format!(
r#"{{"id":"org.example.low","name":"Low Area","api":{api},"kind":"filter","commands":[{{"id":"low","label":"Low Area Closed Paths","menu":{menu}}}]}}"#
)
};
let m = Manifest::parse(with(2, r#"{"path":["Select"],"after":" Inverse "}"#).as_bytes()).unwrap();
let c = &m.commands[0];
assert_eq!(c.place, Some(MenuPlace { path: &["Select"], after: Some("Inverse".into()) }));
assert_eq!(c.menu_label(&m.name), "Low Area Closed Paths (Low Area)", "a placed item names its plug-in");
assert_eq!(serde_json::to_value(&m).unwrap()["commands"][0]["menu"], json!({"path": ["Select"], "after": "Inverse"}));
let end = Manifest::parse(with(2, r#"{"path":["Select","Same"]}"#).as_bytes()).unwrap();
assert_eq!(end.commands[0].place, Some(MenuPlace { path: &["Select", "Same"], after: None }));
// API level 1 ignores the key, as hosts before it did: the command stays in the plug-in's submenu.
for menu in [r#"{"path":["Select"]}"#, r#""File""#, r#"{"path":["File"]}"#, r#"{"path":["Select"]},"menu":{"path":["Edit"]}"#] {
let old = Manifest::parse(with(1, menu).as_bytes()).unwrap();
assert_eq!(old.commands[0].place, None, "{menu}");
assert_eq!(old.commands[0].menu_label(&old.name), "Low Area Closed Paths");
}
let long = format!(r#"{{"path":["Select"],"after":"{}"}}"#, "x".repeat(65));
let padded = format!(r#"{{"path":["Select"],"after":" {} "}}"#, "x".repeat(64));
for (menu, says) in [
(r#"{"path":["File"]}"#, "`menu.path` must be one of"),
(r#"{"path":["Help"]}"#, "`menu.path` must be one of"),
(r#"{"path":["Window"]}"#, "`menu.path` must be one of"),
(r#"{"path":["VectorCraft"]}"#, "`menu.path` must be one of"),
(r#"{"path":["Edit","Preferences"]}"#, "`menu.path` must be one of"),
(r#"{"path":["Object","Plug-ins"]}"#, "`menu.path` must be one of"),
(r#"{"path":["select"]}"#, "`menu.path` must be one of"),
(r#"{"path":[]}"#, "`menu.path` must be one of"),
(r#"{"path":"Select"}"#, "`menu.path` must be one of"),
(r#"{"path":["Select",1]}"#, "`menu.path` must be one of"),
(r#"{"after":"Inverse"}"#, "`menu.path` must be one of"),
(r#""Select""#, "`menu` must be an object"),
(r#"["Select"]"#, "`menu` must be an object"),
(r#"{"path":["Select"],"before":"Inverse"}"#, "unknown key `before`"),
(r#"{"path":["Select"],"after":3}"#, "`menu.after` must be a string"),
(r#"{"path":["Select"],"after":null}"#, "`menu.after` must be a string"),
(r#"{"path":["Select"],"after":" "}"#, "`menu.after` must be 1-64 printable characters"),
(r#"{"path":["Select"],"after":"In\u0007verse"}"#, "`menu.after` must be 1-64 printable characters"),
(r#"{"path":["Select"],"after":"\nInverse\n"}"#, "`menu.after` must be 1-64 printable characters"),
(long.as_str(), "`menu.after` must be 1-64 printable characters"),
(padded.as_str(), "`menu.after` must be 1-64 printable characters"),
(r#"{"path":["Select"]},"menu":{"path":["Edit"]}"#, "duplicate field `menu`"),
] {
let e = Manifest::parse(with(2, menu).as_bytes()).unwrap_err().to_string();
assert!(e.contains("command `low`") && e.contains(says), "{menu}: {e}");
}
let twice =
r#"{"id":"a","name":"x","api":2,"kind":"filter","commands":[{"id":"x","label":"A","menu":{"path":["Edit"]},"menu":{"path":["Edit"]}}]}"#;
assert!(Manifest::parse(twice.as_bytes()).unwrap_err().to_string().contains("duplicate field `menu`"));
}
#[test]
fn strings_and_number_lists_resolve_like_the_other_types() {
let m = Manifest::parse(
+4
View File
@@ -25,6 +25,10 @@ pub const PROGRESS_API: u32 = 2;
/// The API level that adds a filter's `inputs` ([`crate::InputKind`]).
pub const INPUTS_API: u32 = 2;
/// The API level that reads a command's `menu` ([`crate::manifest::MenuPlace`]); below it the key
/// is ignored.
pub const MENU_API: u32 = 2;
/// Most permissions a manifest may list.
pub const MAX_PERMISSIONS: usize = 16;
+36 -2
View File
@@ -4,7 +4,7 @@ use wasmi::{
Config, CustomFuelCosts, EnforcedLimits, Engine, ExternType, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall,
Val, ValType, WasmParams, WasmResults,
};
use wasmparser::{Validator, WasmFeatures};
use wasmparser::{CompositeInnerType, Parser, Payload, Validator, WasmFeatures};
use crate::host::{self, Bridge, Deadline, Host, Report, Run};
use crate::manifest::{MANIFEST_SECTION, MAX_MANIFEST_BYTES, Manifest};
@@ -42,12 +42,46 @@ const WASM_FEATURES: WasmFeatures = WasmFeatures::MUTABLE_GLOBAL
.union(WasmFeatures::EXTENDED_CONST)
.union(WasmFeatures::FLOATS);
/// The most parameters or results a function type may have: the limit `EnforcedLimits::strict()`
/// sets in wasmi 2.0.0.
const MAX_FUNC_TYPE_VALUES: usize = 32;
/// Validates `bytes` with only [`WASM_FEATURES`] on, before wasmi reads the module. A module that
/// uses any other proposal is refused with the validator's error, which names the proposal.
/// uses any other proposal is refused with the validator's error, which names the proposal. A
/// function type with more than [`MAX_FUNC_TYPE_VALUES`] parameters or results is refused before
/// any function body is validated.
fn check_features(bytes: &[u8]) -> Result<()> {
check_func_types(bytes)?;
Validator::new_with_features(WASM_FEATURES).validate_all(bytes).map(|_| ()).map_err(|e| Error::Module(e.to_string()))
}
/// Refuses a function type in the type section with more than [`MAX_FUNC_TYPE_VALUES`] parameters
/// or results, with wasmi's message. Reading stops at the code section. A section that doesn't
/// parse is left to the validator, which reports it.
fn check_func_types(bytes: &[u8]) -> Result<()> {
for payload in Parser::new(0).parse_all(bytes) {
let types = match payload {
Ok(Payload::TypeSection(types)) => types,
Ok(Payload::CodeSectionStart { .. }) | Err(_) => return Ok(()),
Ok(_) => continue,
};
for group in types {
let Ok(group) = group else { return Ok(()) };
for ty in group.types() {
if let CompositeInnerType::Func(f) = &ty.composite_type.inner {
if f.params().len() > MAX_FUNC_TYPE_VALUES {
return Err(Error::Module(format!("a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} parameters")));
}
if f.results().len() > MAX_FUNC_TYPE_VALUES {
return Err(Error::Module(format!("a function type exceeds the limit of {MAX_FUNC_TYPE_VALUES} results")));
}
}
}
}
}
Ok(())
}
/// Sets each WebAssembly proposal that wasmi's `Config` has a setter for in this build on or off,
/// to match [`WASM_FEATURES`].
fn set_features(config: &mut Config) -> &mut Config {
Loaded 100 of 283 files, more files were not shown because too many files have changed in this diff. Show more