Merge main into feat/plugin-api-document-info

This commit is contained in:
dotCooCoo
2026-11-24 22:49:15 -08:00
465 changed files with 27095 additions and 2709 deletions
+32
View File
@@ -154,9 +154,11 @@ 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 | |
| `assets/icons/dc-cycle-sizes.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (two stacked triangles, a panel's Cycle Display Sizes control) | MIT OR Apache-2.0 | |
| `assets/icons/dc-dash-align.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-dash-exact.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-dimension.svg` | Osama Amin | Original work, drawn for VectorCraft: a dimension line with arrowheads between two extension lines | MIT OR Apache-2.0 | |
@@ -193,14 +195,27 @@ 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 | |
| `assets/icons/dc-help.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a question mark in a circle) | MIT OR Apache-2.0 | |
| `assets/icons/dc-join-bevel.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-join-miter.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `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 | |
@@ -228,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 | |
@@ -246,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 | |
@@ -260,15 +278,29 @@ 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 | |
| `assets/icons/dc-stroke-outside.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-stroke.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-swap.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-swatch-global.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a square with a filled corner, a global process color) | MIT OR Apache-2.0 | |
| `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
+121 -100
View File
@@ -1134,7 +1134,7 @@ dependencies = [
[[package]]
name = "craft"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
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=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
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=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
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=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"rustix 1.1.6",
]
@@ -1204,11 +1204,12 @@ dependencies = [
[[package]]
name = "craft-automation"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"base64 0.22.1",
"base64 0.23.1",
"craft-behavior",
"craft-control",
"craft-host",
"craft-keymap",
"craft-platform",
"craft-theme",
@@ -1228,7 +1229,7 @@ dependencies = [
[[package]]
name = "craft-behavior"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"accesskit",
"bitflags 2.13.2",
@@ -1246,7 +1247,7 @@ dependencies = [
[[package]]
name = "craft-browse"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-docpath",
@@ -1264,7 +1265,7 @@ dependencies = [
[[package]]
name = "craft-cdr"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"crc32fast",
"flate2",
@@ -1273,7 +1274,7 @@ dependencies = [
[[package]]
name = "craft-cloud-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"egui",
]
@@ -1281,7 +1282,7 @@ dependencies = [
[[package]]
name = "craft-cms"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"md-5",
"rayon",
@@ -1290,12 +1291,12 @@ dependencies = [
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
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=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-cms",
@@ -1315,7 +1316,7 @@ dependencies = [
[[package]]
name = "craft-control"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"getrandom 0.3.4",
"serde",
@@ -1325,7 +1326,7 @@ dependencies = [
[[package]]
name = "craft-dds"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"rayon",
]
@@ -1333,7 +1334,7 @@ dependencies = [
[[package]]
name = "craft-dialogs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"block2 0.6.2",
"craft-atomic",
@@ -1358,7 +1359,7 @@ dependencies = [
[[package]]
name = "craft-docpath"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"serde",
]
@@ -1366,7 +1367,7 @@ dependencies = [
[[package]]
name = "craft-draw"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1385,7 +1386,7 @@ dependencies = [
[[package]]
name = "craft-dxf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-codepage",
"encoding_rs",
@@ -1397,12 +1398,12 @@ dependencies = [
[[package]]
name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
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=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"fontique",
"harfrust 0.13.3",
@@ -1417,7 +1418,7 @@ dependencies = [
[[package]]
name = "craft-font-manager"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-font-catalog",
@@ -1430,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=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"cap-primitives",
"craft-atomic",
@@ -1452,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=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
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=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"gif",
]
@@ -1470,7 +1472,7 @@ dependencies = [
[[package]]
name = "craft-gzip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"flate2",
]
@@ -1478,7 +1480,7 @@ dependencies = [
[[package]]
name = "craft-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"bitflags 2.13.2",
"craft-i18n",
@@ -1491,7 +1493,7 @@ dependencies = [
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"chrono",
"fixed_decimal",
@@ -1519,7 +1521,7 @@ dependencies = [
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-dds",
"craft-jpeg",
@@ -1546,7 +1548,7 @@ dependencies = [
[[package]]
name = "craft-imaging"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-color-ui",
@@ -1564,7 +1566,7 @@ dependencies = [
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"thiserror 2.0.21",
]
@@ -1572,7 +1574,7 @@ dependencies = [
[[package]]
name = "craft-jxl"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"brotli-decompressor 5.0.3",
"jixel",
@@ -1583,7 +1585,7 @@ dependencies = [
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-host",
"craft-i18n",
@@ -1598,7 +1600,7 @@ dependencies = [
[[package]]
name = "craft-layers"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-i18n",
@@ -1612,7 +1614,7 @@ dependencies = [
[[package]]
name = "craft-menu"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-host",
@@ -1630,7 +1632,7 @@ dependencies = [
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"brotli-decompressor 6.3.2",
"chrono",
@@ -1642,7 +1644,7 @@ dependencies = [
[[package]]
name = "craft-metafile"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"encoding_rs",
"image",
@@ -1653,7 +1655,7 @@ dependencies = [
[[package]]
name = "craft-mime"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"chrono",
"craft-codepage",
@@ -1663,7 +1665,7 @@ dependencies = [
[[package]]
name = "craft-pages"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -1673,12 +1675,13 @@ dependencies = [
"egui",
"kurbo 0.13.1",
"serde",
"serde_json",
]
[[package]]
name = "craft-pdf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"hayro-interpret",
"hayro-syntax",
@@ -1690,7 +1693,7 @@ dependencies = [
[[package]]
name = "craft-platform"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"async-channel",
"async-io",
@@ -1699,6 +1702,7 @@ dependencies = [
"craft-atomic",
"craft-docpath",
"craft-host",
"craft-i18n",
"craft-theme",
"futures-lite",
"js-sys",
@@ -1720,7 +1724,7 @@ dependencies = [
[[package]]
name = "craft-plotter"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"kurbo 0.13.1",
"thiserror 2.0.21",
@@ -1729,10 +1733,11 @@ dependencies = [
[[package]]
name = "craft-print"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-host",
"craft-theme",
"craft-ui",
"craft-winprint-gdi",
"egui",
@@ -1752,7 +1757,7 @@ dependencies = [
[[package]]
name = "craft-proof"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"log",
"miniz_oxide 0.9.1",
@@ -1763,7 +1768,7 @@ dependencies = [
[[package]]
name = "craft-ps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-eps",
"flate2",
@@ -1777,7 +1782,7 @@ dependencies = [
[[package]]
name = "craft-psd"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"encoding_rs",
"flate2",
@@ -1788,19 +1793,22 @@ dependencies = [
[[package]]
name = "craft-quit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"dispatch2",
"egui",
"objc2 0.6.5",
"objc2-app-kit 0.3.2",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "craft-review"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"base64 0.23.1",
"craft-behavior",
"craft-host",
"craft-i18n",
@@ -1817,7 +1825,7 @@ dependencies = [
[[package]]
name = "craft-settings"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-atomic",
"craft-host",
@@ -1834,7 +1842,7 @@ dependencies = [
[[package]]
name = "craft-stream-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"fax",
"hayro-ccitt",
@@ -1845,7 +1853,7 @@ dependencies = [
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-image-codecs",
"craft-xml",
@@ -1866,7 +1874,7 @@ dependencies = [
[[package]]
name = "craft-table"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -1878,7 +1886,7 @@ dependencies = [
[[package]]
name = "craft-text"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-font-manager",
@@ -1903,7 +1911,7 @@ dependencies = [
[[package]]
name = "craft-theme"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"bitflags 2.13.2",
"craft-tracked",
@@ -1918,7 +1926,7 @@ dependencies = [
[[package]]
name = "craft-theme-store"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-atomic",
"craft-behavior",
@@ -1933,7 +1941,7 @@ dependencies = [
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1943,7 +1951,7 @@ dependencies = [
[[package]]
name = "craft-time"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"serde",
"thiserror 2.0.21",
@@ -1952,7 +1960,7 @@ dependencies = [
[[package]]
name = "craft-timeline"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-keymap",
@@ -1967,12 +1975,12 @@ dependencies = [
[[package]]
name = "craft-tracked"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
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=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-cloud-ui",
"craft-ui-canvas",
@@ -1986,7 +1994,7 @@ dependencies = [
[[package]]
name = "craft-ui-canvas"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-i18n",
@@ -2002,7 +2010,7 @@ dependencies = [
[[package]]
name = "craft-ui-contract"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"accesskit",
"craft-behavior",
@@ -2033,13 +2041,14 @@ dependencies = [
"smallvec",
"toml",
"typeid",
"wasm-bindgen-futures",
"web-time",
]
[[package]]
name = "craft-ui-macros"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -2050,7 +2059,7 @@ dependencies = [
[[package]]
name = "craft-ui-panels"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2068,7 +2077,7 @@ dependencies = [
[[package]]
name = "craft-ui-patterns"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2089,7 +2098,7 @@ dependencies = [
[[package]]
name = "craft-ui-shell"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-host",
@@ -2110,16 +2119,18 @@ dependencies = [
[[package]]
name = "craft-ui-widgets"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-behavior",
"craft-host",
"craft-i18n",
"craft-keymap",
"craft-svg",
"craft-theme",
"craft-ui-contract",
"craft-ui-macros",
"egui",
"log",
"serde",
"smallvec",
]
@@ -2127,7 +2138,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"chrono",
"craft-host",
@@ -2156,7 +2167,7 @@ dependencies = [
[[package]]
name = "craft-vectorcraft-format"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"flate2",
"serde",
@@ -2167,7 +2178,7 @@ dependencies = [
[[package]]
name = "craft-wayland"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"raw-window-handle",
"wayland-backend",
@@ -2177,7 +2188,7 @@ dependencies = [
[[package]]
name = "craft-web-api"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"js-sys",
"serde_json",
@@ -2188,7 +2199,7 @@ dependencies = [
[[package]]
name = "craft-win32"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"winsafe",
]
@@ -2196,7 +2207,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"craft-appkit",
"craft-atomic",
@@ -2228,7 +2239,7 @@ dependencies = [
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"quick-xml 0.41.0",
"serde",
@@ -2390,7 +2401,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
"windows-sys 0.59.0",
"windows-sys 0.61.2",
]
[[package]]
@@ -2516,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",
@@ -2525,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",
@@ -2560,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",
@@ -2579,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",
@@ -2598,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",
@@ -2623,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",
@@ -2637,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",
@@ -2650,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",
@@ -2676,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",
]
@@ -2757,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",
@@ -2783,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"
@@ -3073,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]]
@@ -3496,7 +3507,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a"
[[package]]
name = "hayro-cmap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"brotli",
"hayro-postscript",
@@ -3505,7 +3516,7 @@ dependencies = [
[[package]]
name = "hayro-interpret"
version = "0.7.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"bitflags 2.13.2",
"hayro-cmap",
@@ -3523,7 +3534,7 @@ dependencies = [
[[package]]
name = "hayro-jbig2"
version = "0.3.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"fearless_simd",
"hayro-ccitt",
@@ -3541,12 +3552,12 @@ dependencies = [
[[package]]
name = "hayro-postscript"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
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=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"flate2",
"hayro-ccitt",
@@ -4106,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]]
@@ -4477,7 +4488,7 @@ dependencies = [
[[package]]
name = "krilla"
version = "0.8.2"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"base64 0.22.1",
"bumpalo",
@@ -4634,7 +4645,7 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "git+https://github.com/storytold/craft-libs?rev=bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0#bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0"
source = "git+https://github.com/storytold/craft-libs?rev=4bed21baaa41d2b47bef90879c04df521f6f6043#4bed21baaa41d2b47bef90879c04df521f6f6043"
dependencies = [
"arrayvec",
"kurbo 0.13.1",
@@ -9707,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]]
@@ -9762,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"
@@ -10270,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 = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0", default-features = false, features = ["interpret", "write"] }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
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 = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
craft-gzip = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
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 = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
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 = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
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 = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0", features = ["tree"] }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
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 = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
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 = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
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 = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
craft-gif = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
craft-tiff = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
craft-ps = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0", default-features = false, features = ["read", "write"] }
craft-psd = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
craft-stream-codecs = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
craft-jxl = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
craft-codepage = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
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 = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
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 = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
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 = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
krilla = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
linesweeper = { git = "https://github.com/storytold/craft-libs", rev = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0" }
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 = "bf62d509fb26e92ab5c45a9fd613d8aab9ffafd0", 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 }
-2
View File
@@ -614,8 +614,6 @@ fn main() -> std::process::ExitCode {
};
embed::install(ctx, spec, &vectorcraft_ui_egui::ui_fonts()).map_err(|e| e.to_string())?;
egui_extras::install_image_loaders(ctx);
craft::ui::primitives::register_app_icons(&vectorcraft_ui_egui::icons::APP_ICONS);
craft::ui::primitives::register_app_icons(&vectorcraft_ui_egui::cursors::CURSOR_ICONS);
let folders = settings.lock().get().ui.last_folders.clone();
let wake = {
let ctx = ctx.clone();
+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="butt" stroke-linejoin="miter"><path d="M5 9H19L12 2Z M5 15H19L12 22Z" fill="currentColor" stroke="none"/></svg>

After

Width:  |  Height:  |  Size: 264 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"><circle cx="12" cy="12" r="9"/><path d="M9.5 9.5a2.5 2.5 0 1 1 3.5 2.3c-.6.3-1 .9-1 1.6v.6M12 17h.01"/></svg>

After

Width:  |  Height:  |  Size: 293 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="butt" stroke-linejoin="miter"><rect x="4.75" y="4.75" width="14.5" height="14.5"/><path d="M20 10V20H10Z" fill="currentColor" stroke="none"/></svg>

After

Width:  |  Height:  |  Size: 300 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"><rect x="4.75" y="4.75" width="14.5" height="14.5"/></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="butt" stroke-linejoin="miter"><circle cx="12" cy="12" r="8.25"/><circle cx="12" cy="12" r="3.25" fill="currentColor" stroke="none"/></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"><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

+12
View File
@@ -13,6 +13,18 @@ pub struct Effect {
pub visible: bool,
}
impl Effect {
/// Whether this effect gives an image's fill or stroke a shape to paint: it is a visible
/// Convert to Shape or Outline Object.
pub fn gives_image_shape(&self) -> bool {
self.visible
&& matches!(
self.id.as_str(),
"convertToShape.rectangle" | "convertToShape.roundedRectangle" | "convertToShape.ellipse" | "path.outlineObject"
)
}
}
fn yes() -> bool {
true
}
+190 -31
View File
@@ -389,6 +389,12 @@ pub enum DimensionSource {
#[serde(default, rename = "freeB", skip_serializing_if = "Option::is_none")]
free_b: Option<FreePoint>,
},
/// A whole path, measured between its outermost points ([`extent`]): the leftmost and the
/// rightmost while the dimension is horizontal or aligned, the topmost and the bottommost while
/// it is vertical. Versions without this source do not open the file.
Extent {
node: NodeId,
},
}
impl DimensionSource {
@@ -396,7 +402,7 @@ impl DimensionSource {
match self {
Self::Segment { edge } | Self::Arc { edge } => vec![edge.node],
Self::Angle { first, second } => vec![first.node, second.node],
Self::Circle { node } => vec![*node],
Self::Circle { node } | Self::Extent { node } => vec![*node],
Self::Points { a, b, vertex, free_a, free_b } => [a, b, vertex]
.into_iter()
.filter_map(|p| p.as_ref().map(|r| r.node))
@@ -407,7 +413,7 @@ impl DimensionSource {
/// Anchor indexes cannot safely follow a topology replacement. Ordinary moves and handle
/// edits keep their topology and remain linked.
pub fn topology_changed(&self, before: &Document, after: &Document) -> bool {
if matches!(self, Self::Circle { .. }) {
if matches!(self, Self::Circle { .. } | Self::Extent { .. }) {
return false;
}
self.nodes().iter().any(|id| {
@@ -418,9 +424,19 @@ impl DimensionSource {
old.is_some() && old != counts(after)
})
}
/// Whether a path it measures differs between `before` and `after`, or is in only one of them.
/// A node without a path, or missing from both, counts as changed.
pub fn art_changed(&self, before: &Document, after: &Document) -> bool {
self.nodes().into_iter().any(|id| match (before.node(id), after.node(id)) {
(Some(old), Some(new)) => old.path_data().is_none() || (!std::ptr::eq(old, new) && old.path_data() != new.path_data()),
_ => true,
})
}
/// The map that took the measured art from `before` to `after`, when every path it measures
/// went through one [`art_transform`] that reflects it (a negative determinant). None when a
/// measured path is unchanged, or when two of them went through different maps.
/// measured path is unchanged, or when two of them went through different maps. None for a
/// dimension of a whole path whose path's box through its outermost points stays where it
/// was, as after its direction is reversed.
pub fn reflection(&self, before: &Document, after: &Document) -> Option<Affine> {
let mut first: Option<Affine> = None;
for id in self.nodes() {
@@ -429,6 +445,9 @@ impl DimensionSource {
return None;
}
let xf = fitted(before, after, id, |xf| xf.determinant() < 0.0)?;
if matches!(self, Self::Extent { .. }) && same_extents(before, after, id) {
return None;
}
match first {
None => first = Some(xf),
Some(f) => {
@@ -759,19 +778,22 @@ impl Dimension {
/// outside them as it was, on the same side: the gap is measured from the outermost point
/// on the line's side, so the line stays clear of art that turns. A line that lay between
/// the two points keeps its distance from the first point.
pub fn keep_gap(&mut self, old: &Dimension) {
/// With `docs`, the documents `old` and this dimension were read from, the gap of a dimension of
/// a whole path is measured from the whole path ([`Self::span`]), also when only parts of the
/// path other than its measured points moved, and also when the dimension is aligned (each
/// along its own normal).
pub fn keep_gap(&mut self, old: &Dimension, docs: Option<(&Document, &Document)>) {
let whole = docs.is_some() && matches!(self.source, Some(DimensionSource::Extent { .. }));
if self.mode != DimensionMode::Linear
|| self.orientation == Orientation::Aligned
|| (self.orientation == Orientation::Aligned && !whole)
|| old.orientation != self.orientation
|| (self.a, self.b) == (old.a, old.b)
|| ((self.a, self.b) == (old.a, old.b) && !whole)
{
return;
}
let n = self.normal();
let across = |p: Point| p.to_vec2().dot(n);
let line = across(old.a) + old.offset;
let (low, high) = (across(old.a).min(across(old.b)), across(old.a).max(across(old.b)));
let (new_low, new_high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b)));
let line = old.a.to_vec2().dot(old.normal()) + old.offset;
let (low, high) = old.span(docs.map(|(before, _)| before));
let (new_low, new_high) = self.span(docs.map(|(_, after)| after));
let at = if line >= high {
new_high + (line - high)
} else if line <= low {
@@ -779,7 +801,7 @@ impl Dimension {
} else {
return;
};
let offset = at - across(self.a);
let offset = at - self.a.to_vec2().dot(self.normal());
if offset.is_finite() && offset.abs() <= 1e6 {
self.offset = offset;
}
@@ -787,8 +809,9 @@ impl Dimension {
/// A linear dimension whose art was reflected, its points now moved from `old`'s: its line goes
/// to the side of the points that `image` (where the reflection put `old`'s line) is on, as far
/// past the outermost point on that side as `old`'s line was. A line that lay between the two
/// points is left as it is.
pub fn mirror_line(&mut self, old: &Dimension, image: Point) {
/// points is left as it is. With `docs`, as in [`Self::keep_gap`], a dimension of a whole path
/// measures from the whole path.
pub fn mirror_line(&mut self, old: &Dimension, image: Point, docs: Option<(&Document, &Document)>) {
if self.mode != DimensionMode::Linear || old.mode != DimensionMode::Linear {
return;
}
@@ -796,7 +819,7 @@ impl Dimension {
let n = old.normal();
let across = |p: Point| p.to_vec2().dot(n);
let line = across(old.a) + old.offset;
let (low, high) = (across(old.a).min(across(old.b)), across(old.a).max(across(old.b)));
let (low, high) = old.span(docs.map(|(before, _)| before));
if line >= high {
line - high
} else if line <= low {
@@ -807,13 +830,25 @@ impl Dimension {
};
let n = self.normal();
let across = |p: Point| p.to_vec2().dot(n);
let (low, high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b)));
let (low, high) = self.span(docs.map(|(_, after)| after));
let at = if 2.0 * across(image) >= low + high { high + gap } else { low - gap };
let offset = at - across(self.a);
if offset.is_finite() && offset.abs() <= 1e6 {
self.offset = offset;
}
}
/// Where a linear dimension's art lies along its normal, lowest and highest: its two points,
/// or, for a dimension of a whole path read from `doc`, the whole path ([`reach`]), so that
/// the whole path is on one side of a line outside the span.
fn span(&self, doc: Option<&Document>) -> (f64, f64) {
let n = self.normal();
let (a, b) = (self.a.to_vec2().dot(n), self.b.to_vec2().dot(n));
let (low, high) = (a.min(b), a.max(b));
match (doc, &self.source) {
(Some(doc), Some(DimensionSource::Extent { node })) => reach(doc, *node, n).map_or((low, high), |(l, h)| (low.min(l), high.max(h))),
_ => (low, high),
}
}
/// Whether a linear dimension's line lies strictly between its two points along the normal.
fn line_between_points(&self) -> bool {
let n = self.normal();
@@ -824,30 +859,67 @@ impl Dimension {
/// Makes a linear dimension measure in `orientation`, with its line on the side of the points
/// it was on. The line goes through the middle of the old line when that point lies outside
/// the two points along the new normal; otherwise it lies as far past the outermost point on
/// that side as the old line lay from its points.
pub fn set_orientation(&mut self, orientation: Orientation) {
/// that side as the old line lay from its points. A dimension of a whole path
/// ([`DimensionSource::Extent`]) first reads from `doc` the outermost points it measures in the
/// new orientation, and its line keeps its distance from the whole path ([`Self::span`]), on
/// the side the middle of the old line is on. A line that lay across the path goes as far past
/// the path as it lay from its first point. For such a dimension it is an error when the path
/// no longer exists, or when the line would lie more than 1,000,000 pt from its first point,
/// and the dimension is then left as it was.
pub fn set_orientation(&mut self, orientation: Orientation, doc: &Document) -> Result<(), String> {
if self.mode != DimensionMode::Linear || self.orientation == orientation {
self.orientation = orientation;
return;
return Ok(());
}
let (handle, gap) = (self.handle(), self.offset.abs());
self.orientation = orientation;
let n = self.normal();
let across = |p: Point| p.to_vec2().dot(n);
let (low, high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b)));
let h = across(handle);
let at = if h >= high || h <= low {
let mut next = self.clone();
let (handle, mut gap) = (next.handle(), next.offset.abs());
if let Some(DimensionSource::Extent { .. }) = &next.source {
// Measured from the whole path, relative to the first point, which the line is
// `offset` from. A line on the path's edge, to within the rounding of the
// projections, is outside it.
let n = next.normal();
let base = next.a.to_vec2().dot(n);
let (low, high) = next.span(Some(doc));
let eps = 8.0 * f64::EPSILON * ((next.a.x * n.x).abs() + (next.a.y * n.y).abs() + low.abs() + high.abs());
let (low, high, line) = (low - base, high - base, next.offset);
gap = if line >= high - eps {
(line - high).max(0.0)
} else if line <= low + eps {
(low - line).max(0.0)
} else {
gap
};
}
next.orientation = orientation;
if let Some(DimensionSource::Extent { node }) = &next.source {
(next.a, next.b) = extent(doc, *node, orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?;
}
// Along the new normal, relative to the new first point, so that the result is the offset.
let n = next.normal();
let base = next.a.to_vec2().dot(n);
let (low, high) = next.span(Some(doc));
let (low, high, h) = (low - base, high - base, handle.to_vec2().dot(n) - base);
let whole = matches!(next.source, Some(DimensionSource::Extent { .. }));
let at = if whole && h >= high {
high + gap
} else if whole && h <= low {
low - gap
} else if h >= high || h <= low {
h
} else if 2.0 * h >= low + high {
high + gap
} else {
low - gap
};
let offset = at - across(self.a);
if offset.is_finite() && offset.abs() <= 1e6 {
self.offset = offset;
if at.is_finite() && at.abs() <= 1e6 {
next.offset = at;
} else if whole {
// The old offset would put the line across the path.
return Err("Invalid dimension offset".into());
}
self.length = self.measured();
next.length = next.measured();
*self = next;
Ok(())
}
fn bisector(&self) -> Vec2 {
let start = (self.a - self.vertex).atan2();
@@ -889,7 +961,7 @@ impl Dimension {
self.offset = offset;
}
if self.line_between_points() && !old.line_between_points() {
self.keep_gap(&old);
self.keep_gap(&old, None);
}
} else if self.mode == DimensionMode::Linear && xf.determinant() < 0.0 && (self.b - self.a).hypot() > 1e-9 {
// A reflection turns the left normal of a → b to the other side, so an aligned
@@ -948,6 +1020,12 @@ impl Dimension {
let (center, radius) = arc(doc, edge).ok_or("Choose a circle or a perfect arc")?;
self.set_radial(center, radius);
}
Some(DimensionSource::Extent { node }) => {
let (a, b) = extent(doc, *node, self.orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?;
self.a = a;
self.b = b;
self.length = self.measured();
}
None => {}
}
self.validate()
@@ -1048,6 +1126,87 @@ pub fn arc(doc: &Document, edge: &SegmentRef) -> Option<(Point, f64)> {
Some((center, radius))
}
/// The outermost points of a path's outline, read from its segments (an anchor that starts no
/// segment is not part of it): the leftmost and the rightmost, then the topmost and the
/// bottommost. Of points level with each other, the first point is the topmost or leftmost of
/// them and the second the bottommost or rightmost, so a straight vertical line has two points
/// across its width too. None for a node without a path or without segments.
pub fn extents(doc: &Document, id: NodeId) -> Option<[(Point, Point); 2]> {
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveExtrema};
let path = doc.node(id)?.path_data()?;
let before = |p: Point, q: Point, vertical: bool| {
let key = |p: Point| if vertical { (p.y, p.x) } else { (p.x, p.y) };
let (a, b) = (key(p), key(q));
a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1)).is_lt()
};
let mut ends: Option<[(Point, Point); 2]> = None;
let mut take = |p: Point| {
let ends = ends.get_or_insert([(p, p); 2]);
for (axis, (low, high)) in ends.iter_mut().enumerate() {
if before(p, *low, axis == 1) {
*low = p;
}
if before(*high, p, axis == 1) {
*high = p;
}
}
};
for sp in &path.subpaths {
for i in 0..sp.segment_count() {
let seg = sp.segment(i);
take(seg.p0);
take(seg.p3);
for t in seg.extrema() {
take(seg.eval(t));
}
}
}
ends
}
/// Whether the box through a path's outermost points ([`extents`]) is where it was in `before`,
/// each side to within rounding against the larger coordinate on its axis.
fn same_extents(before: &Document, after: &Document, id: NodeId) -> bool {
let sides = |doc: &Document| extents(doc, id).map(|[(left, right), (top, bottom)]| [left.x, right.x, top.y, bottom.y]);
let (Some(old), Some(new)) = (sides(before), sides(after)) else { return false };
[0, 2].into_iter().all(|i| {
let scale = old[i].abs().max(old[i + 1].abs()).max(1.0);
(i..i + 2).all(|j| (old[j] - new[j]).abs() <= 1e-12 * scale)
})
}
/// [`extents`] along one axis: the leftmost and the rightmost points, or with `vertical` the
/// topmost and the bottommost.
pub fn extent(doc: &Document, id: NodeId, vertical: bool) -> Option<(Point, Point)> {
extents(doc, id).map(|ends| ends[usize::from(vertical)])
}
/// How far a path's outline reaches along the unit direction `u`: the lowest and the highest
/// `p · u` over the points of its segments. None for a node without a path or without segments.
pub fn reach(doc: &Document, id: NodeId, u: Vec2) -> Option<(f64, f64)> {
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveExtrema};
let path = doc.node(id)?.path_data()?;
// Turns `u` onto the x axis, so the turned curve's extrema include those along `u`.
let turn = Affine::new([u.x, -u.y, u.y, u.x, 0.0, 0.0]);
let mut span: Option<(f64, f64)> = None;
let mut take = |p: Point| {
let v = p.to_vec2().dot(u);
let (low, high) = span.get_or_insert((v, v));
(*low, *high) = (low.min(v), high.max(v));
};
for sp in &path.subpaths {
for i in 0..sp.segment_count() {
let seg = sp.segment(i);
take(seg.p0);
take(seg.p3);
for t in (turn * seg).extrema() {
take(seg.eval(t));
}
}
}
span
}
/// The two straight segments that meet at a corner anchor, if both are straight.
pub fn corner(doc: &Document, node: NodeId, subpath: usize, anchor: usize) -> Option<(SegmentRef, SegmentRef)> {
let sp = doc.node(node)?.path_data()?.subpaths.get(subpath)?;
+44 -7
View File
@@ -343,18 +343,27 @@ impl Document {
/// tree order where `id` appears.
pub fn index_path(&self, id: NodeId) -> Option<Vec<usize>> {
crate::id_index::note_path_lookup();
// No cache yet: build it, and answer from it (an id it doesn't have is not in the tree; one
// that appears more than once is walked to, as below).
let Some(cached) = self.index.get() else {
let fresh = self.index.rebuild(&self.layers);
return match fresh.get(&id) {
Some(Some(p)) => Some(p),
_ if fresh.contains_key(&id) => self.walk_index_path(id),
_ => None,
};
};
// The cached path, while the node there still has the id ([`id_index`]).
let cached = self.index.get();
match cached.as_ref().and_then(|m| m.get(&id)) {
match cached.get(&id) {
Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == id) => return Some(p),
Some(None) => return self.walk_index_path(id),
_ => {}
}
// A stale path (the tree changed), an id the cache doesn't have (deleted or added since),
// or no cache yet: walk, and rebuild now and then.
// A stale path (the tree changed) or an id the cache doesn't have (deleted or added
// since): walk, and rebuild now and then.
let found = self.walk_index_path(id);
let stale = cached.as_ref().is_some_and(|m| m.contains_key(&id));
if cached.is_none() || ((stale || found.is_some()) && self.index.missed()) {
let stale = cached.contains_key(&id);
if (stale || found.is_some()) && self.index.missed() {
self.index.rebuild(&self.layers);
}
found
@@ -618,10 +627,38 @@ impl Document {
/// children of each parent. Each id is listed once and none lies inside another listed node, as
/// in a list of top-level objects. For an id that is not in the tree, is listed twice or lies
/// inside another listed node, it fails with `NoNode` and leaves the document as it was.
///
/// The lookup cache ([`id_index`]) is kept, with the listed nodes taken out of it, while it has
/// each listed node where it is, until the nodes removed since it was built are half its
/// entries; otherwise it is cleared.
pub fn remove_many(&mut self, ids: &[NodeId]) -> Result<Vec<Arc<Node>>, DocError> {
let places = self.places(ids)?;
// Each listed node's place in the cache's table, while the cache has it where it is.
let gone = self.index.get().and_then(|cache| {
let listed = places.iter().flat_map(|(up, kids)| kids.iter().map(move |&(i, k)| (up, i, k)));
listed
.map(|(up, i, k)| {
let id = ids.get(k)?;
let path = cache.get(id)??;
(path.split_last() == Some((&i, up.as_slice()))).then(|| cache.table_place(id)).flatten()
})
.collect::<Option<Vec<_>>>()
});
let removed = self.take(places, ids.len())?;
self.index.clear();
// The removed nodes, as the cache counts them (ruler guides included), up to `limit`.
let count = |limit: usize| {
let mut n = 0usize;
let mut each = |_: &Node| {
n += 1;
if n >= limit { std::ops::ControlFlow::Break(()) } else { std::ops::ControlFlow::Continue(()) }
};
let _ = removed.iter().try_for_each(|r| r.try_walk(&mut each));
n
};
match gone {
Some(gone) if !self.index.removed(count) => self.index.take_out(&gone),
_ => self.index.clear(),
}
Ok(removed)
}
+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())
}
+104 -21
View File
@@ -4,10 +4,15 @@
//! The tree is edited in many places through public fields, so the cache can't be kept in step
//! with it. It is checked instead: a cached path is used only while the node at that path still
//! has the id (a check as deep as the tree). A path that no longer checks out rebuilds the cache,
//! and an id the cache doesn't have (deleted, or added since) is looked up by walking, as before.
//! and an id the cache doesn't have (added since, or removed) is looked up by walking, as before.
//! An id that appears more than once (a damaged file) is never cached, so lookups keep returning
//! its first place in tree order.
//!
//! [`crate::Document::remove_many`] keeps the cache and notes the nodes it removes, so the cache
//! places each node after a removed sibling one lower and finds no path for a removed node or one
//! inside it. Once the removed nodes are half the cache's entries, the cache is let go. The first
//! lookup with no cache builds it and answers from it.
//!
//! The one case a cached lookup can answer differently from a walk: a second node with an
//! existing id put in the tree *after* the cache was built, earlier in tree order than the first.
//! The lookup then returns the original node (also one with that id) instead of the new one. The
@@ -48,10 +53,25 @@ fn multiplier() -> u64 {
/// A map keyed by node id with [`IdHasher`].
pub type IdMap<V> = HashMap<NodeId, V, BuildHasherDefault<IdHasher>>;
/// Where each node is: its parent's entry (`u32::MAX` for a top-level layer) and its index among
/// its siblings. One flat table, so building it allocates nothing per node.
#[derive(Default)]
/// The children removed from each parent since the table was built: the parent's entry (`u32::MAX`
/// for the top-level layers) and the removed children's indices in the table, sorted.
type Gaps = HashMap<u32, Vec<u32>>;
/// The cache as a document reads it: the table, and the nodes removed from the tree since it was
/// built. A node's index among its siblings is its index in the table less the removed siblings
/// before it.
#[derive(Clone)]
pub(crate) struct Paths {
table: Arc<Table>,
gaps: Arc<Gaps>,
}
/// Where each node was when the cache was built: its parent's entry (`u32::MAX` for a top-level
/// layer) and its index among its siblings. One flat table, so building it allocates nothing per
/// node.
#[derive(Default)]
struct Table {
/// Each id's entry in `at`; `None` for an id that appears more than once.
ids: IdMap<Option<u32>>,
at: Vec<(u32, u32)>,
@@ -59,15 +79,15 @@ pub(crate) struct Paths {
impl Paths {
/// The index path of `id`: `Some(None)` when the id appears more than once, `None` when it
/// isn't in the table.
/// isn't in the table or it, or a node it is in, was removed.
pub(crate) fn get(&self, id: &NodeId) -> Option<Option<Vec<usize>>> {
let e = (*self.ids.get(id)?)?;
let e = (*self.table.ids.get(id)?)?;
let mut path = Vec::new();
let mut cur = e;
// Each step goes to a parent entry, made before its children: at most `at.len()` steps.
for _ in 0..=self.at.len() {
let Some(&(parent, i)) = self.at.get(cur as usize) else { return Some(None) };
path.push(i as usize);
for _ in 0..=self.table.at.len() {
let Some(&(parent, i)) = self.table.at.get(cur as usize) else { return Some(None) };
path.push(self.shifted(parent, i)? as usize);
if parent == u32::MAX {
path.reverse();
return Some(Some(path));
@@ -76,21 +96,37 @@ impl Paths {
}
Some(None)
}
/// Where the table has `id` as it was built: its parent's entry and its index among its
/// siblings then; `None` when the id isn't in the table or appears more than once.
pub(crate) fn table_place(&self, id: &NodeId) -> Option<(u32, u32)> {
let e = (*self.table.ids.get(id)?)?;
self.table.at.get(e as usize).copied()
}
pub(crate) fn contains_key(&self, id: &NodeId) -> bool {
self.ids.contains_key(id)
self.table.ids.contains_key(id)
}
pub(crate) fn len(&self) -> usize {
self.ids.len()
self.table.ids.len()
}
/// The entry of `id` in the table: `Some(None)` when the id appears more than once, `None`
/// when it isn't in the table.
pub(crate) fn entry(&self, id: &NodeId) -> Option<Option<u32>> {
self.ids.get(id).copied()
self.table.ids.get(id).copied()
}
/// Entry `e`'s parent entry (`u32::MAX` for a top-level layer) and its index among its
/// siblings.
/// siblings; `None` when the node at `e` was removed.
pub(crate) fn place(&self, e: u32) -> Option<(u32, u32)> {
self.at.get(e as usize).copied()
let (parent, i) = self.table.at.get(e as usize).copied()?;
Some((parent, self.shifted(parent, i)?))
}
/// The index among its siblings of the child of `parent` at index `i` in the table: `i` less
/// the removed children before it, or `None` when that child was removed.
fn shifted(&self, parent: u32, i: u32) -> Option<u32> {
let Some(gone) = self.gaps.get(&parent) else { return Some(i) };
match gone.binary_search(&i) {
Ok(_) => None,
Err(k) => Some(i - k as u32),
}
}
}
@@ -134,9 +170,10 @@ pub(crate) fn note_path_lookup() {
PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1));
}
/// The cache, shared by clones of a document (each checks every path it uses against its own tree).
/// The cache, shared by clones of a document (each checks every path it uses against its own tree),
/// the lookups that missed it, and the nodes removed from the tree since it was built.
#[derive(Default)]
pub struct IdIndex(RwLock<Option<Arc<Paths>>>, std::sync::atomic::AtomicU32);
pub struct IdIndex(RwLock<Option<Arc<Paths>>>, std::sync::atomic::AtomicU32, std::sync::atomic::AtomicUsize);
impl IdIndex {
/// The current cache, if one was built.
@@ -150,6 +187,18 @@ impl IdIndex {
*g = None;
}
self.1.store(0, std::sync::atomic::Ordering::Relaxed);
self.2.store(0, std::sync::atomic::Ordering::Relaxed);
}
/// Note the nodes removed from the tree while the cache is kept (their entries go stale); true
/// when the stale entries are half the cache or more, and it's time to let it go. `count(limit)`
/// counts the removed nodes, and may stop once it reaches `limit`, the number that makes half.
/// With no cache, `count` isn't called.
pub(crate) fn removed(&self, count: impl FnOnce(usize) -> usize) -> bool {
let Some(paths) = self.get() else { return false };
let half = paths.len().div_ceil(2);
let n = count(half.saturating_sub(self.2.load(std::sync::atomic::Ordering::Relaxed)));
self.2.fetch_add(n, std::sync::atomic::Ordering::Relaxed).saturating_add(n) >= half
}
/// Whether a cache was built (and not cleared since).
@@ -157,9 +206,42 @@ impl IdIndex {
self.0.read().is_ok_and(|g| g.is_some())
}
/// Note the nodes that [`crate::Document::remove_many`] took out of the tree, each as its place
/// in the table ([`Paths::table_place`]): the cache then places their later siblings one lower
/// for each, and has no path for them or the nodes in them. With no cache, it does nothing.
pub(crate) fn take_out(&self, gone: &[(u32, u32)]) {
let Ok(mut g) = self.0.write() else { return };
let Some(paths) = g.as_mut() else { return };
// Clones of the document keep the cache as it was.
let gaps = Arc::make_mut(&mut Arc::make_mut(paths).gaps);
let mut gone = gone.to_vec();
gone.sort_unstable();
// One merge of sorted lists per parent, so a removal of many children costs one pass.
for run in gone.chunk_by(|a, b| a.0 == b.0) {
let Some(&(parent, _)) = run.first() else { continue };
let list = gaps.entry(parent).or_default();
let old = std::mem::take(list);
list.reserve(old.len() + run.len());
let (mut a, mut b) = (old.into_iter().peekable(), run.iter().map(|&(_, i)| i).peekable());
loop {
let next = match (a.peek(), b.peek()) {
(Some(x), Some(y)) if x <= y => a.next(),
(Some(_), Some(_)) | (None, Some(_)) => b.next(),
(Some(_), None) => a.next(),
(None, None) => break,
};
if let Some(i) = next
&& list.last() != Some(&i)
{
list.push(i);
}
}
}
}
/// Rebuild the cache from `layers` (one walk) and return it.
pub(crate) fn rebuild(&self, layers: &[Arc<Node>]) -> Arc<Paths> {
fn walk(nodes: &[Arc<Node>], parent: u32, out: &mut Paths) {
fn walk(nodes: &[Arc<Node>], parent: u32, out: &mut Table) {
for (i, n) in nodes.iter().enumerate() {
let e = out.at.len() as u32;
out.at.push((parent, i as u32));
@@ -170,13 +252,14 @@ impl IdIndex {
}
}
note_tree_walk();
let mut out = Paths::default();
walk(layers, u32::MAX, &mut out);
let out = Arc::new(out);
let mut table = Table::default();
walk(layers, u32::MAX, &mut table);
let out = Arc::new(Paths { table: Arc::new(table), gaps: Arc::default() });
if let Ok(mut g) = self.0.write() {
*g = Some(out.clone());
}
self.1.store(0, std::sync::atomic::Ordering::Relaxed);
self.2.store(0, std::sync::atomic::Ordering::Relaxed);
out
}
@@ -189,7 +272,7 @@ impl IdIndex {
impl Clone for IdIndex {
fn clone(&self) -> Self {
IdIndex(RwLock::new(self.get()), Default::default())
IdIndex(RwLock::new(self.get()), Default::default(), self.2.load(std::sync::atomic::Ordering::Relaxed).into())
}
}
+13
View File
@@ -238,6 +238,19 @@ impl Node {
Some(bp)
}
/// The two lines from corner to corner of this image's frame, which cross a linked image in
/// Outline mode without Document Setup → Show Images in Outline Mode. `None` for anything that
/// is not an image.
pub fn image_cross(&self) -> Option<BezPath> {
let q = self.image_corners()?;
let mut bp = BezPath::new();
bp.move_to(q[0]);
bp.line_to(q[2]);
bp.move_to(q[1]);
bp.line_to(q[3]);
Some(bp)
}
/// The map from this image's pixel space to the page: projective for a distorted image, its
/// transform otherwise. `None` for anything that is not an image.
pub fn image_map(&self) -> Option<Homography> {
+27
View File
@@ -1340,6 +1340,33 @@ mod tests {
assert!(piece.knockout_outline().is_none());
}
/// Each piece of a mesh-warped colorized image keeps its color and whether it overprints.
#[test]
fn mesh_warp_image_pieces_keep_an_overprinting_color() {
let im = crate::ImageObject {
key: "pic".into(),
width: 4,
height: 4,
xf: Affine::scale(10.0),
link: None,
placement: Default::default(),
pixels: None,
};
let mut n = Node::new(NodeId(3), NodeKind::Image(Box::new(im.clone())));
n.extras_mut().colorize = Some(Box::new(Paint::solid(Color::BLACK)));
n.extras_mut().colorize_overprint = true;
for masked in [false, true] {
let g = mesh_warp_image(&n, &im, &|p| p, 2, false, masked);
let mut pieces = vec![];
g.walk(&mut |c| {
if matches!(c.kind, NodeKind::Image(_)) {
pieces.push(c.colorize_overprints());
}
});
assert_eq!(pieces, [true; 8], "masked {masked}");
}
}
/// More cells than the objects live art may make cut no pieces (the count overflowed).
#[test]
fn mesh_warp_image_past_the_budget_makes_an_empty_group() {
+5 -2
View File
@@ -231,13 +231,15 @@ pub(crate) fn mesh_warp_image_with(
g.knockout = crate::Knockout::On;
if let Some(e) = g.extras_if_any() {
e.colorize = None;
e.colorize_overprint = false;
e.image_quad = None;
}
if mesh_warp_cost(k) > MAX_GENERATED {
return g;
}
// A grayscale image's fill color colorizes each piece; the group of pieces takes none.
let colorize = n.extras().colorize.clone();
// A grayscale image's fill color colorizes each piece, overprinting as the image's does; the
// group of pieces takes none.
let (colorize, colorize_overprint) = (n.extras().colorize.clone(), n.extras().colorize_overprint);
// Each piece shows what the image shows: its color mask's masked pixels.
let color_mask = n.extras().color_mask.clone();
let (pw, ph) = (im.width as f64, im.height as f64);
@@ -271,6 +273,7 @@ pub(crate) fn mesh_warp_image_with(
let mut image = Node::new(n.id, NodeKind::Image(Box::new(ImageObject { xf, ..im.clone() })));
image.extras_mut().pixelated = pixelated;
image.extras_mut().colorize = colorize.clone();
image.extras_mut().colorize_overprint = colorize_overprint;
image.extras_mut().color_mask = color_mask.clone();
if masked {
// Preserve Shape Using Transparency: the triangle is the piece's alpha (a
+5
View File
@@ -63,6 +63,10 @@ pub struct NodeExtras {
/// colorizes it. Each pixel is drawn in this color, as opaque as the pixel is dark, so white
/// pixels are transparent. `None`: the image shows its own pixels.
pub colorize: Option<Box<vectorcraft_color::Paint>>,
/// Attributes panel › Overprint Fill on a colorized image: its color prints over the inks
/// below instead of knocking them out. It counts only while [`Self::colorize`] is set
/// ([`crate::Node::colorize_overprints`]).
pub colorize_overprint: bool,
/// Pathfinder panel › Make Compound Shape: this group is a compound shape
/// ([`Node::is_compound_shape`], [`crate::compound_shape`]).
pub compound_shape: bool,
@@ -115,6 +119,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras {
live_paint_gaps: None,
objects_on_path: None,
colorize: None,
colorize_overprint: false,
compound_shape: false,
shape_mode: crate::ShapeMode::Add,
symbol_overrides: Vec::new(),
+5
View File
@@ -51,6 +51,7 @@ impl Serialize for Node {
e.live_paint_gaps.is_none(),
e.objects_on_path.is_none(),
e.colorize.is_none(),
is_default(&e.colorize_overprint),
is_default(&e.compound_shape),
is_default(&e.shape_mode),
e.symbol_overrides.is_empty(),
@@ -99,6 +100,7 @@ impl Serialize for Node {
field!("live_paint_gaps", &e.live_paint_gaps);
field!("objects_on_path", &e.objects_on_path);
field!("colorize", &e.colorize);
field!("colorize_overprint", &e.colorize_overprint);
field!("compound_shape", &e.compound_shape);
field!("shape_mode", &e.shape_mode);
field!("symbol_overrides", &e.symbol_overrides);
@@ -244,6 +246,8 @@ pub(super) struct NodeWire {
#[serde(default)]
colorize: Option<Box<vectorcraft_color::Paint>>,
#[serde(default)]
colorize_overprint: bool,
#[serde(default)]
compound_shape: bool,
#[serde(default)]
shape_mode: crate::ShapeMode,
@@ -477,6 +481,7 @@ impl From<NodeWire> for Node {
live_paint_gaps: w.live_paint_gaps,
objects_on_path: w.objects_on_path,
colorize: w.colorize,
colorize_overprint: w.colorize_overprint,
compound_shape: w.compound_shape,
shape_mode: w.shape_mode,
symbol_overrides: w.symbol_overrides,
+403 -11
View File
@@ -2,11 +2,12 @@
//! over the inks below instead of knocking them out ([`crate::FillLayer::overprint`]).
//! Edit → Edit Colors → Overprint Black sets it on black fills and strokes ([`OverprintBlack`]).
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use vectorcraft_color::{BlendMode, Color, GradientKind, Paint};
use crate::{Document, Node, NodeId, NodeKind};
use crate::{Document, ImageBlob, Node, NodeId, NodeKind};
/// `Document.unknown` key of files from before per-fill/stroke overprint: the ids of objects
/// marked Overprint Black ([`Document::migrate_overprint_black`]).
@@ -65,7 +66,8 @@ impl OverprintBlack {
}
}
/// Set (or clear) the overprint of `n`'s own black fills and strokes and its characters'.
/// Set (or clear) the overprint of `n`'s own black fills and strokes, its characters' and,
/// for a colorized image, its color's.
/// `spots`: the document's spot swatch names ([`Document::spot_names`]). Returns whether
/// anything changed.
pub fn apply(&self, n: &mut Node, spots: &[String]) -> bool {
@@ -90,9 +92,18 @@ impl OverprintBlack {
}
}
}
if self.colorize_black(n, spots) {
set(&mut n.extras_mut().colorize_overprint);
}
changed
}
/// Whether `n` is an image colorized with a black color that [`Self::fill`] covers: the color
/// of a gray or 1-bit image is its fill ([`crate::NodeExtras::colorize`]).
fn colorize_black(&self, n: &Node, spots: &[String]) -> bool {
self.fill && matches!(n.kind, NodeKind::Image(_)) && n.extras().colorize.as_deref().is_some_and(|p| self.black(p, spots))
}
/// [`Self::apply`] to every node of `a`'s subtree, copying only the nodes on the way to those
/// that change. Returns whether anything changed.
pub fn apply_deep(&self, a: &mut Arc<Node>, spots: &[String]) -> bool {
@@ -136,38 +147,138 @@ impl OverprintBlack {
(self.fill && r.style.overprint_fill != on && self.black(&r.style.fill, spots))
|| (self.stroke && r.style.overprint_stroke != on && self.black(&r.style.stroke, spots))
};
n.appearance.items.iter().any(item) || matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(run))
n.appearance.items.iter().any(item)
|| matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(run))
|| (n.extras().colorize_overprint != on && self.colorize_black(n, spots))
}
}
impl Node {
/// Whether any fill or stroke of this subtree overprints (characters' aside).
pub fn has_overprint(&self) -> bool {
self.appearance.items.iter().any(|i| i.overprint()) || self.children().is_some_and(|c| c.iter().any(|c| c.has_overprint()))
self.appearance.items.iter().any(|i| i.overprint())
|| self.colorize_overprints()
|| self.children().is_some_and(|c| c.iter().any(|c| c.has_overprint()))
}
/// Whether this is an image colorized with a color ([`crate::NodeExtras::colorize`]) that
/// overprints ([`crate::NodeExtras::colorize_overprint`]).
pub fn colorize_overprints(&self) -> bool {
let e = self.extras();
matches!(self.kind, NodeKind::Image(_)) && e.colorize_overprint && e.colorize.as_deref().is_some_and(|p| !p.is_none())
}
}
/// Whether fill or stroke row `i` of an image draws: it is visible, has a paint and an opacity
/// above 0 (a stroke a width too) and a visible Convert to Shape or Outline Object, which gives a
/// row on an image a shape of its own ([`crate::Effect::gives_image_shape`]).
pub fn image_row_draws(i: &crate::AppearanceItem) -> bool {
let width = match i {
crate::AppearanceItem::Stroke(s) => s.width > 0.0,
crate::AppearanceItem::Fill(_) => true,
};
i.visible() && i.opacity() > 0.0 && !i.paint().is_none() && width && i.effects().iter().any(crate::Effect::gives_image_shape)
}
/// Whether paint `paint` of blend mode `blend` darkens when `overprint` asks it to: with the
/// Normal blend, and not a white that `discard_white` knocks out ([`DiscardWhite::discards`]).
fn darkens(overprint: bool, blend: BlendMode, paint: &Paint, discard_white: &DiscardWhite) -> bool {
overprint && blend == BlendMode::Normal && !discard_white.discards(paint)
}
/// The effects that only move or reshape what an object draws, keeping its own colors, besides
/// those whose ids start with `warp.`, `convertToShape.` or `addon.path.` ([`reshapes_only`]).
const RESHAPING_EFFECTS: [&str; 12] = [
"distort.freeDistort",
"distort.puckerBloat",
"distort.roughen",
"distort.transform",
"distort.tweak",
"distort.twist",
"distort.zigZag",
"path.offsetPath",
"path.outlineObject",
"path.outlineStroke",
"stylize.roundCorners",
"stylize.scribble",
];
/// Whether effect `id` only moves or reshapes what an object draws ([`RESHAPING_EFFECTS`]).
/// Any other effect (a shadow, a glow, a raster effect, a color adjustment, a plug-in effect)
/// paints colors of its own.
pub fn reshapes_only(id: &str) -> bool {
["warp.", "convertToShape.", "addon.path."].iter().any(|p| id.starts_with(p)) || RESHAPING_EFFECTS.contains(&id)
}
/// Whether `n` is an image with no pixels of its own and a colorize paint.
pub fn is_colorized_image(n: &Node) -> bool {
matches!(n.kind, NodeKind::Image(ref im) if im.pixels.is_none()) && n.extras().colorize.is_some()
}
/// The key of the pixels colorized image `n` shows in `images`: its color mask's when the mask
/// was made for it and is there ([`Document::shown_image`]), else its own. `None` for any other
/// node.
pub fn colorized_shown_key(n: &Node, images: &BTreeMap<String, ImageBlob>) -> Option<String> {
match &n.kind {
NodeKind::Image(im) if is_colorized_image(n) => {
let mask = Document::color_mask_of(n).filter(|m| m.made_for(im) && images.contains_key(&m.key));
Some(mask.map_or(&im.key, |m| &m.key).clone())
}
_ => None,
}
}
/// Whether colorized image `n` shows pixels in `images` that don't take its colorize paint
/// ([`ImageBlob::takes_colorize`]), so it is drawn and separated as those pixels and not as its
/// color.
pub fn refuses_colorize(n: &Node, images: &BTreeMap<String, ImageBlob>) -> bool {
colorized_shown_key(n, images).and_then(|key| images.get(&key)).is_some_and(|b| !b.takes_colorize())
}
/// Whether colorized image `n` is drawn overprinting as a whole: its color overprints
/// ([`Node::colorize_overprints`]) with the Normal blend and is not a white `discard_white` knocks out,
/// the pixels it shows in `images` take its color ([`refuses_colorize`]), each of its own visible
/// effects only reshapes it ([`reshapes_only`]), and each row that draws ([`image_row_draws`])
/// overprints that way too. A colorized image's color is not a fill row, so the whole node
/// overprints or none of it does.
pub fn image_overprints_whole(n: &Node, discard_white: &DiscardWhite, images: &BTreeMap<String, ImageBlob>) -> bool {
let row = |i: &crate::AppearanceItem| match i {
crate::AppearanceItem::Fill(l) => darkens(l.overprint, l.blend, &l.paint, discard_white),
crate::AppearanceItem::Stroke(l) => darkens(l.overprint, l.blend, &l.paint, discard_white),
};
let paints_past = n.appearance.effects.iter().any(|e| e.visible && !reshapes_only(&e.id));
n.colorize_overprints()
&& n.extras().colorize.as_deref().is_some_and(|p| darkens(true, n.blend, p, discard_white))
&& !paints_past
&& n.appearance.items.iter().filter(|i| image_row_draws(i)).all(row)
&& !refuses_colorize(n, images)
}
/// Draw the overprinting fills and strokes of `a`'s subtree with Darken (those with a blend
/// mode of their own keep it), copying only the nodes on the way to them: on screen and on a
/// printed plate this approximates their inks printing over the inks below. Darken keeps the
/// stronger ink of each plate (and each additive channel), so a colour overprinting itself stays
/// that colour, where Multiply would darken it. With `discard_white`
/// (Document Setup → Discard White Overprint) white fills and strokes knock out instead.
pub fn darken_overprints(a: &mut Arc<Node>, discard_white: bool) {
/// that colour, where Multiply would darken it. White fills and strokes that `discard_white`
/// (Document Setup → Discard White Overprint) knocks out do so instead. A colorized image
/// darkens as a whole ([`image_overprints_whole`], with the document's `images`).
pub fn darken_overprints(a: &mut Arc<Node>, discard_white: &DiscardWhite, images: &BTreeMap<String, ImageBlob>) {
if !a.has_overprint() {
return;
}
let n = Arc::make_mut(a);
let darkens = |overprint: bool, blend: BlendMode, paint: &Paint| overprint && blend == BlendMode::Normal && !(discard_white && is_white(paint));
let whole = image_overprints_whole(n, discard_white, images);
for it in &mut n.appearance.items {
match it {
crate::AppearanceItem::Fill(l) if darkens(l.overprint, l.blend, &l.paint) => l.blend = BlendMode::Darken,
crate::AppearanceItem::Stroke(l) if darkens(l.overprint, l.blend, &l.paint) => l.blend = BlendMode::Darken,
crate::AppearanceItem::Fill(l) if darkens(l.overprint, l.blend, &l.paint, discard_white) => l.blend = BlendMode::Darken,
crate::AppearanceItem::Stroke(l) if darkens(l.overprint, l.blend, &l.paint, discard_white) => l.blend = BlendMode::Darken,
_ => {}
}
}
if whole {
n.blend = BlendMode::Darken;
}
for c in n.children_mut().into_iter().flatten() {
darken_overprints(c, discard_white);
darken_overprints(c, discard_white, images);
}
}
@@ -182,7 +293,59 @@ 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_names`]).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct DiscardWhite {
on: bool,
spot_inks: BTreeSet<String>,
}
impl DiscardWhite {
/// The document's setting and spot inks.
pub fn of(doc: &Document) -> Self {
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.
pub fn new(on: bool) -> Self {
Self { on, spot_inks: BTreeSet::new() }
}
/// Whether `p` loses its overprint: the setting is on and `p` is paper white
/// ([`Self::paper_white`]), not a tint above 0% of a spot ink, which prints as that ink.
pub fn discards(&self, p: &Paint) -> bool {
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()
@@ -208,6 +371,7 @@ impl Document {
/// Whether any fill or stroke of `n`'s subtree overprints, characters' too.
fn overprints_anywhere(n: &Node) -> bool {
n.appearance.items.iter().any(|i| i.overprint())
|| n.extras().colorize_overprint
|| matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke))
|| n.children().is_some_and(|c| c.iter().any(|c| overprints_anywhere(c)))
}
@@ -227,6 +391,10 @@ pub fn clear_overprints(a: &mut Arc<Node>) {
(r.style.overprint_fill, r.style.overprint_stroke) = (false, false);
}
}
// Also the flag an image keeps after its color is removed.
if n.extras().colorize_overprint {
n.extras_mut().colorize_overprint = false;
}
for c in n.children_mut().into_iter().flatten() {
clear_overprints(c);
}
@@ -331,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);
@@ -348,6 +568,178 @@ mod tests {
assert!(Arc::ptr_eq(&group, &marked), "and nothing is copied");
}
/// A gray image colorized with `color`, its color overprinting, with the fill row `fill`.
fn colorized(color: Paint, fill: Paint) -> Node {
let im = crate::ImageObject {
key: "pic".into(),
width: 1,
height: 1,
xf: vectorcraft_geom::Affine::IDENTITY,
link: None,
placement: Default::default(),
pixels: None,
};
let mut n = Node::new(NodeId(1), NodeKind::Image(Box::new(im)));
n.appearance = Appearance::basic(fill, Paint::None, 0.0).into();
n.extras_mut().colorize = Some(Box::new(color));
n.extras_mut().colorize_overprint = true;
n
}
#[test]
fn a_white_colorized_image_knocks_out_under_discard_white() {
let image = |color: Paint, discard_white: bool| {
let mut a = Arc::new(colorized(color, Paint::None));
darken_overprints(&mut a, &DiscardWhite::new(discard_white), &BTreeMap::new());
a.blend
};
let white = Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 0.0));
assert_eq!(image(white.clone(), true), BlendMode::Normal, "white knocks out, as a white fill does");
assert_eq!(image(white, false), BlendMode::Darken);
assert_eq!(image(cmyk(0.0, 0.0, 0.0, 1.0), true), BlendMode::Darken);
}
/// A tint above 0% of a spot ink whose color is white keeps overprinting with Discard White
/// Overprint, as an image's color and as a fill; a 0% tint, a process white and a swatch that
/// is not spot knock out.
#[test]
fn a_white_spot_ink_keeps_overprinting_under_discard_white() {
let mut doc = Document::new(100.0, 100.0);
let white = Color::cmyk(0.0, 0.0, 0.0, 0.0);
doc.swatches.push(crate::Swatch { name: "White Ink".into(), paint: Paint::solid(white), global: true, spot: true });
doc.swatches.push(crate::Swatch { name: "Paper".into(), paint: Paint::solid(white), global: true, spot: false });
doc.setup.discard_white_overprint = true;
let discard = DiscardWhite::of(&doc);
let linked = |name: &str, tint: f32| Paint::Solid { color: white, swatch: Some(name.into()), tint };
let blend = |color: Paint, fill: Paint| {
let mut n = colorized(color, Paint::None);
if let Some(f) = n.appearance.fill_mut() {
f.paint = fill;
f.overprint = true;
}
let mut a = Arc::new(n);
darken_overprints(&mut a, &discard, &BTreeMap::new());
(a.blend, a.appearance.fill().map(|f| f.blend))
};
let spot = linked("White Ink", 0.5);
assert_eq!(blend(spot.clone(), spot.clone()), (BlendMode::Darken, Some(BlendMode::Darken)));
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:?}");
}
assert!(!DiscardWhite::new(false).discards(&Paint::solid(white)));
}
#[test]
fn a_colorized_image_showing_pixels_that_refuse_its_color_keeps_knocking_out() {
let blend = |images: &BTreeMap<String, ImageBlob>| {
let mut a = Arc::new(colorized(cmyk(0.0, 0.0, 0.0, 1.0), Paint::None));
darken_overprints(&mut a, &DiscardWhite::new(false), images);
a.blend
};
let bytes = crate::links::missing_placeholder().unwrap();
let preview = Arc::new(bytes.clone());
let shown = ImageBlob { mime: "image/png".into(), bytes: preview.clone(), proxy: Some(preview), file_font: Default::default() };
assert!(!shown.takes_colorize());
assert_eq!(blend(&BTreeMap::from([("pic".to_string(), shown)])), BlendMode::Normal, "a full-color preview is drawn as it is");
let own = ImageBlob::new("image/png", bytes);
assert_eq!(blend(&BTreeMap::from([("pic".to_string(), own)])), BlendMode::Darken, "the image's own pixels take the color");
}
#[test]
fn a_colorized_image_darkens_unless_its_rows_draw_an_effect() {
let blend = |effect: Option<(&str, bool)>, overprint: bool| {
let mut n = colorized(cmyk(0.0, 0.0, 0.0, 1.0), cmyk(1.0, 0.0, 0.0, 0.0));
if let Some(f) = n.appearance.fill_mut() {
f.overprint = overprint;
if let Some((id, visible)) = effect {
f.effects.push(crate::Effect { id: id.into(), params: serde_json::json!({}), visible });
}
}
let mut a = Arc::new(n);
darken_overprints(&mut a, &DiscardWhite::new(false), &BTreeMap::new());
a.blend
};
let shape = "convertToShape.rectangle";
assert_eq!(blend(None, false), BlendMode::Darken, "a row with no effect paints nothing on an image");
assert_eq!(blend(Some((shape, false)), false), BlendMode::Darken, "nor one whose effect is hidden");
assert_eq!(blend(Some(("path.offsetPath", true)), false), BlendMode::Darken, "nor one whose effect gives it no shape");
assert_eq!(blend(Some((shape, true)), false), BlendMode::Normal, "a knocking-out row drawn by its effect keeps knocking out");
assert_eq!(blend(Some(("path.outlineObject", true)), false), BlendMode::Normal, "Outline Object gives a row a shape too");
assert_eq!(blend(Some((shape, true)), true), BlendMode::Darken, "with an overprinting row the whole image overprints");
}
#[test]
fn a_colorized_image_darkens_past_a_row_with_no_opacity() {
let blend = |stroke: bool, opacity: f32| {
let mut n = colorized(cmyk(0.0, 0.0, 0.0, 1.0), Paint::None);
let effect = crate::Effect { id: "convertToShape.rectangle".into(), params: serde_json::json!({}), visible: true };
if stroke {
if let Some(s) = n.appearance.stroke_mut() {
s.paint = cmyk(1.0, 0.0, 0.0, 0.0);
s.width = 1.0;
s.opacity = opacity;
s.effects.push(effect);
}
} else if let Some(f) = n.appearance.fill_mut() {
f.paint = cmyk(1.0, 0.0, 0.0, 0.0);
f.opacity = opacity;
f.effects.push(effect);
}
let mut a = Arc::new(n);
darken_overprints(&mut a, &DiscardWhite::new(false), &BTreeMap::new());
a.blend
};
assert_eq!(blend(false, 0.0), BlendMode::Darken, "a fill with no opacity paints nothing");
assert_eq!(blend(true, 0.0), BlendMode::Darken, "nor a stroke with no opacity");
assert_eq!(blend(false, 0.5), BlendMode::Normal, "a fill with some opacity still knocks out");
assert_eq!(blend(true, 0.5), BlendMode::Normal, "and so does a stroke");
}
#[test]
fn a_colorized_image_with_a_node_effect_keeps_knocking_out() {
let blend = |id: &str, visible: bool| {
let mut n = colorized(cmyk(0.0, 0.0, 0.0, 1.0), Paint::None);
n.appearance.effects.push(crate::Effect { id: id.into(), params: serde_json::json!({}), visible });
let mut a = Arc::new(n);
darken_overprints(&mut a, &DiscardWhite::new(false), &BTreeMap::new());
a.blend
};
assert_eq!(blend("stylize.dropShadow", true), BlendMode::Normal, "a drop shadow is not darkened with the image");
assert_eq!(blend("stylize.outerGlow", true), BlendMode::Normal, "nor an outer glow");
assert_eq!(blend("stylize.innerGlow", true), BlendMode::Normal, "nor an inner glow");
assert_eq!(blend("artistic.neonGlow", true), BlendMode::Normal, "nor a raster effect");
assert_eq!(blend("stylize.dropShadow", false), BlendMode::Darken, "a hidden effect draws nothing");
assert_eq!(blend("distort.roughen", true), BlendMode::Darken, "a geometry effect reshapes the image itself");
assert_eq!(blend("warp.arc", true), BlendMode::Darken, "so does a warp");
}
#[test]
fn overprint_black_takes_a_black_colorized_image() {
let off = |mut n: Node| {
n.extras_mut().colorize_overprint = false;
Arc::new(n)
};
let mut a = off(colorized(cmyk(0.0, 0.0, 0.0, 1.0), Paint::None));
assert!(!OverprintBlack { fill: false, ..Default::default() }.apply_deep(&mut a, &[]), "the color is the image's fill");
assert!(OverprintBlack::default().apply_deep(&mut a, &[]) && a.colorize_overprints());
assert!(!OverprintBlack::default().apply_deep(&mut a, &[]), "nothing left to change");
assert!(OverprintBlack { remove: true, ..Default::default() }.apply_deep(&mut a, &[]) && !a.colorize_overprints());
let mut cyan = off(colorized(cmyk(1.0, 0.0, 0.0, 0.0), Paint::None));
assert!(!OverprintBlack::default().apply_deep(&mut cyan, &[]), "a cyan image is not black");
}
#[test]
fn clearing_overprints_clears_the_flag_of_an_image_without_a_color() {
let mut n = colorized(cmyk(0.0, 0.0, 0.0, 1.0), Paint::None);
n.extras_mut().colorize = None;
let mut a = Arc::new(n);
clear_overprints(&mut a);
Arc::make_mut(&mut a).extras_mut().colorize = Some(Box::new(cmyk(0.0, 0.0, 0.0, 1.0)));
assert!(!a.colorize_overprints(), "a color given later knocks out");
}
#[test]
fn legacy_overprint_black_list_migrates() {
let mut d = Document::new(100.0, 100.0);
+15 -2
View File
@@ -12,6 +12,9 @@ pub type AnchorRef = (usize, usize);
/// (subpath index, segment index) inside a path.
pub type SegmentRef = (usize, usize);
/// The most objects [`Selection::add_all`] adds by looking for each one in the selected objects.
const FEW_TO_ADD: usize = 8;
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Selection {
/// Selected objects in selection order.
@@ -197,14 +200,24 @@ impl Selection {
/// carry its current activation, so a removal drops every slot of the id at once.
fn each(&mut self, ids: impl IntoIterator<Item = NodeId>, toggle: bool) {
use std::collections::hash_map::{Entry, HashMap};
let mut ids = ids.into_iter().peekable();
if ids.peek().is_none() {
let ids: Vec<NodeId> = ids.into_iter().collect();
if ids.is_empty() {
return;
}
self.target = None;
self.slices.clear();
self.symbol_part = None;
self.on_path_member = None;
// Up to [`FEW_TO_ADD`] objects to add are each looked for in the selected objects; more go
// through a table of the selected objects.
if !toggle && ids.len() <= FEW_TO_ADD {
for id in ids {
if !self.objects.contains(&id) {
self.objects.push(id);
}
}
return;
}
let mut live: HashMap<NodeId, usize> = self.objects.iter().map(|id| (*id, 0)).collect();
let mut added: Vec<(NodeId, usize)> = Vec::new();
let mut removed = false;
+114
View File
@@ -261,6 +261,120 @@ fn remove_many_matches_removing_one_at_a_time() {
}
}
/// A document with `n` squares on its one layer, bottom to top, and their ids.
fn squares(n: usize) -> (Document, Vec<NodeId>) {
let mut d = Document::new(612.0, 792.0);
let layer = d.layers[0].id;
let ids = (0..n)
.map(|k| {
let s = square(&mut d);
d.insert(Some(layer), k, s).unwrap()
})
.collect();
(d, ids)
}
/// The first lookup with no cache, which builds it, finds what a walk finds, an id that appears
/// more than once and one not in the tree included.
#[test]
fn a_first_lookup_with_no_cache_finds_what_a_walk_finds() {
for seed in 1..10 {
let (d, ids) = tree(seed);
for id in ids.iter().chain(&[NodeId(999_999)]) {
d.drop_lookup_cache();
assert_eq!(d.index_path(*id), d.walk_index_path(*id), "seed {seed}: {id:?}");
}
}
}
/// A lookup with no cache builds it in one walk of the tree. Removing objects from the top, the
/// bottom or the middle of a layer, or a group with the objects in it, keeps the cache: the objects
/// left are found where a walk finds them, without a walk.
#[test]
fn remove_many_keeps_the_cache_whichever_objects_it_removes() {
let (mut d, ids) = squares(100);
let layer = d.layers[0].id;
let inner: Vec<Arc<Node>> = (0..3).map(|_| Arc::new(square(&mut d))).collect();
let members: Vec<NodeId> = inner.iter().map(|n| n.id).collect();
let gid = d.alloc_id();
let group = d.insert(Some(layer), 50, Node::group(gid, inner)).unwrap();
d.drop_lookup_cache();
let walks = tree_walks();
assert!(d.node(ids[0]).is_some());
assert_eq!(tree_walks() - walks, 1, "building the cache");
let walks = tree_walks();
d.remove_many(&ids[90..]).unwrap();
d.remove_many(&ids[..10]).unwrap();
d.remove_many(&[ids[30], ids[60], ids[45]]).unwrap();
d.remove_many(&[group]).unwrap();
let left: Vec<NodeId> = ids[10..90].iter().copied().filter(|id| ![ids[30], ids[45], ids[60]].contains(id)).collect();
let found: Vec<_> = left.iter().map(|id| d.index_path(*id)).collect();
assert_eq!(tree_walks() - walks, 0, "after the removals");
let walked: Vec<_> = left.iter().map(|id| d.walk_index_path(*id)).collect();
assert_eq!(found, walked);
assert!(found.iter().all(Option::is_some));
let middle = [ids[30], ids[45], ids[60], group];
let mut gone = ids[..10].iter().chain(&ids[90..]).chain(&middle).chain(&members);
assert!(gone.all(|id| d.node(*id).is_none()));
}
/// A layer keeps its ruler guides above its art: removing the topmost object moves the guides down,
/// and the cache still finds them, and the art left, without a walk.
#[test]
fn remove_many_keeps_the_cache_in_a_layer_with_ruler_guides() {
let (mut d, ids) = squares(20);
let layer = d.layers[0].id;
let guides: Vec<NodeId> = (0..3)
.map(|k| {
let g = Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: k % 2 == 0, pos: k as f64, artboard: None });
d.insert(Some(layer), usize::MAX, g).unwrap()
})
.collect();
d.drop_lookup_cache();
d.node(ids[0]);
let walks = tree_walks();
for id in ids.iter().rev().take(5) {
d.remove_many(&[*id]).unwrap();
let rest = ids[..15].iter().chain(&guides);
assert!(rest.into_iter().all(|id| d.index_path(*id) == d.walk_index_path(*id) && d.node(*id).is_some_and(|n| n.id == *id)));
}
assert!(d.has_lookup_cache());
// Each pass above walked once per id to compare: 18 ids, 5 passes.
assert_eq!(tree_walks() - walks, 18 * 5, "only the comparison walks");
}
/// Removing the top objects one at a time keeps the cache only while the removed nodes are less
/// than half of its entries, so it doesn't keep growing stale. A removed layer counts every node in
/// it, its ruler guides included.
#[test]
fn remove_many_lets_the_cache_go_once_half_of_it_is_removed() {
let (mut d, ids) = squares(100);
d.drop_lookup_cache();
d.node(ids[0]);
// The layer and its 100 squares.
let entries = 101;
let mut removed = 0;
for id in ids.iter().rev() {
d.remove_many(&[*id]).unwrap();
removed += 1;
assert_eq!(d.has_lookup_cache(), removed * 2 < entries, "after {removed} removals");
if !d.has_lookup_cache() {
break;
}
}
assert!(removed < ids.len(), "the cache went before the last removal");
let (mut d, ids) = squares(100);
let top = d.add_layer(None);
let guides: Vec<Arc<Node>> =
(0..200).map(|k| Arc::new(Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: false, pos: k as f64, artboard: None }))).collect();
d.children_mut(Some(top)).unwrap().extend(guides);
d.drop_lookup_cache();
d.node(ids[0]);
d.remove_many(&[top]).unwrap();
assert!(!d.has_lookup_cache(), "the removed layer and its 200 guides are most of the cache");
}
#[test]
fn insert_beside_matches_inserting_one_at_a_time() {
for seed in 1..40 {
+1 -1
View File
@@ -117,7 +117,7 @@ pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings};
pub use svg_filter::SVG_FILTER;
pub use trap::TRAP;
pub use vectorcraft_three_d::PlanarFace;
pub use vectorcraft_three_d::{BevelProfile, Mesh};
pub use vectorcraft_three_d::{BevelProfile, Mesh, MeshPart};
pub use warp::{WARP_NET, WarpNet, WarpStyle, map_version, warp_point, warp_version};
mod catalog;
+3 -3
View File
@@ -495,10 +495,9 @@ fn add_to_instance(n: &mut Node, fill: &[Effect], stroke: &[Effect]) {
}
/// Does effect `e` give an image's fill or stroke a shape to paint (a visible Convert to Shape or
/// Outline Object)?
/// Outline Object, [`Effect::gives_image_shape`])?
fn gives_shape(e: &Effect) -> bool {
e.visible
&& matches!(e.id.as_str(), "convertToShape.rectangle" | "convertToShape.roundedRectangle" | "convertToShape.ellipse" | "path.outlineObject")
e.gives_image_shape()
}
/// Does `item`, a fill or stroke of an image, paint something: does it paint and carry an effect
@@ -1277,6 +1276,7 @@ fn as_art_opts(
{
let mut e = image.extras_mut();
e.colorize = n.extras().colorize.clone();
e.colorize_overprint = n.extras().colorize_overprint;
e.pixelated = n.extras().pixelated;
e.color_mask = n.extras().color_mask.clone();
e.image_quad = n.extras().image_quad.clone();
+8 -3
View File
@@ -893,8 +893,11 @@ fn surface_meshes(
}
let (mesh, on) = vectorcraft_three_d::revolve_mesh_surface(path, rule, b, options)?;
let (mut side, mut rest, mut art) = (vectorcraft_three_d::Mesh::default(), vectorcraft_three_d::Mesh::default(), vec![]);
for (t, points) in mesh.triangles.iter().zip(&on) {
let corner = |i: u32| mesh.positions.get(i as usize).copied().zip(mesh.normals.get(i as usize).copied());
for ((t, points), part) in mesh.triangles.iter().zip(&on).zip(&mesh.parts) {
let corner = |i: u32| {
let i = i as usize;
Some((*mesh.positions.get(i)?, *mesh.normals.get(i)?, *mesh.uvs.get(i)?))
};
let Some(corners) = t.iter().map(|&i| corner(i)).collect::<Option<Vec<_>>>() else { continue };
let into = match points {
Some(points) => {
@@ -904,11 +907,13 @@ fn surface_meshes(
None => &mut rest,
};
let base = into.positions.len() as u32;
for (p, n) in corners {
for (p, n, uv) in corners {
into.positions.push(p);
into.normals.push(n);
into.uvs.push(uv);
}
into.triangles.push([base, base + 1, base + 2]);
into.parts.push(*part);
}
let mut out = vec![];
if !rest.is_empty() {
+9 -4
View File
@@ -2893,10 +2893,13 @@ fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity
};
let Some(on_mesh) = on_mesh else { continue };
let (mut taken, mut left, mut art) = (Mesh::default(), Mesh::default(), vec![]);
for t in &rest.triangles {
let corner = |i: u32| rest.positions.get(i as usize).copied().zip(rest.normals.get(i as usize).copied());
for (t, part) in rest.triangles.iter().zip(&rest.parts) {
let corner = |i: u32| {
let i = i as usize;
Some((*rest.positions.get(i)?, *rest.normals.get(i)?, *rest.uvs.get(i)?))
};
let Some(corners) = t.iter().map(|&i| corner(i)).collect::<Option<Vec<_>>>() else { continue };
let points: Option<Vec<Point>> = corners.iter().map(|(m, n)| on_mesh.art_point(*m, *n)).collect();
let points: Option<Vec<Point>> = corners.iter().map(|(m, n, _)| on_mesh.art_point(*m, *n)).collect();
let into = match points {
Some(points) => {
art.extend(points);
@@ -2905,11 +2908,13 @@ fn split_graphics(id: &str, p: &Value, bounds: Rect, mesh: Mesh, (color, opacity
None => &mut left,
};
let base = into.positions.len() as u32;
for (m, n) in corners {
for (m, n, uv) in corners {
into.positions.push(m);
into.normals.push(n);
into.uvs.push(uv);
}
into.triangles.push([base, base + 1, base + 2]);
into.parts.push(*part);
}
rest = left;
if !taken.is_empty() {
+12 -3
View File
@@ -148,6 +148,14 @@ fn nine_slice_painted_effects_are_raster_effects() {
}
}
/// The effects that leave a colorized image overprinting as a whole are the geometry effects.
#[test]
fn image_overprint_reshaping_effects_are_the_geometry_effects() {
for id in crate::catalog::catalog_index().keys() {
assert_eq!(vectorcraft_doc::overprint::reshapes_only(id), is_geometry(id), "{id}");
}
}
#[test]
fn open_paths_stay_open() {
let line = PathData::single(SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(50.0, 20.0), Point::new(100.0, 0.0)], false));
@@ -701,21 +709,22 @@ fn a_nested_groups_gradient_follows_its_warped_image() {
}
/// An image under a geometry effect other than a Warp draws as the image does: colorized by
/// a grayscale image's fill color, and smoothed or not.
/// a grayscale image's fill color, overprinting as it does, and smoothed or not.
#[test]
fn an_image_under_a_geometry_effect_keeps_its_color_and_smoothing() {
let mut n = (*warp_test_image(1)).clone();
n.appearance.effects = vec![fx("distort.roughen", json!({"size": 5, "detail": 10}))];
n.extras_mut().colorize = Some(Box::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0))));
n.extras_mut().colorize_overprint = true;
n.extras_mut().pixelated = true;
let art = crate::reshape::reshape(None, &n, None).unwrap();
let mut seen = vec![];
art.walk(&mut |c| {
if matches!(c.kind, NodeKind::Image(_)) {
seen.push((c.extras().colorize.clone(), c.extras().pixelated));
seen.push((c.extras().colorize.clone(), c.colorize_overprints(), c.extras().pixelated));
}
});
assert_eq!(seen, vec![(n.extras().colorize.clone(), true)]);
assert_eq!(seen, vec![(n.extras().colorize.clone(), true, true)]);
}
/// What `effects` make of `path` within `budget`.
+8 -3
View File
@@ -846,19 +846,24 @@ 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;
pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned};
/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with.
pub use object::{reflect_axis, scale_factors, shear_tangent};
pub(crate) use paint::LIVE_PAINT_BUCKET;
pub(crate) use paint::{LIVE_PAINT_BUCKET, asks_defaults_only};
pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys};
pub use select::SIMILAR;
pub(crate) use vectorcraft_doc::range::parse_range;
/// What the fill and stroke proxies read from the selected objects, kept with the selection
/// ([`crate::doc_state::SelectionRecord`]).
pub(crate) use paint::SelectionPaints;
/// A date param in Unix seconds that defaults to the clock: `None` when absent (now, see
/// [`clock_date`]), `Some(None)` for null (no date), else `Some(Some(seconds))`.
pub(crate) fn date_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Option<i64>>> {
+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 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,26 +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(|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
@@ -154,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)
}
+1 -1
View File
@@ -169,7 +169,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Overprint Black…",
["Edit", "Edit Colors"],
None,
"{remove?: false, percentage?: 100, fill?: true, stroke?: true, includeCmyBlacks?: false, includeSpotBlacks?: false, ids?} make the black fills and/or strokes of the selection (or ids; groups: their contents; type: its characters) overprint, or stop (remove). Black: K ≥ percentage with no C, M or Y (any with includeCmyBlacks), not linked to a spot swatch (unless includeSpotBlacks); a gradient is black when every stop is → {changed: objects}",
"{remove?: false, percentage?: 100, fill?: true, stroke?: true, includeCmyBlacks?: false, includeSpotBlacks?: false, ids?} make the black fills and/or strokes of the selection (or ids; groups: their contents; type: its characters; a grayscale or 1-bit image colorized by paint.setFill: its color, as a fill) overprint, or stop (remove). Black: K ≥ percentage with no C, M or Y (any with includeCmyBlacks), not linked to a spot swatch (unless includeSpotBlacks); a gradient is black when every stop is → {changed: objects}",
has_doc,
super::overprint::overprint_black
),
+22 -6
View File
@@ -14,7 +14,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Dimension",
[],
None,
"{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits",
"{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: extent, node} (linear only: a whole path between its outermost points, leftmost and rightmost when horizontal or aligned, topmost and bottommost when vertical)|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits",
has_doc,
create
),
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Update Dimensions",
[],
None,
"{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on), offset?: pt (as in dimension.create), at?: [x,y] (after offset: puts a linear dimension's line through this point, gives an angular dimension's arc a radius of the point's distance from the vertex, at least 12 pt, or turns a radius or diameter line toward it; what the dimension measures does not change)} restyle, turn or move existing dimensions → {ids}",
"{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on; for an extent source, an error when that would put the line more than 1,000,000 pt from its first point and no offset is given), offset?: pt (as in dimension.create), at?: [x,y] (after offset: puts a linear dimension's line through this point, gives an angular dimension's arc a radius of the point's distance from the vertex, at least 12 pt, or turns a radius or diameter line toward it; what the dimension measures does not change)} restyle, turn or move existing dimensions → {ids}",
has_doc,
update
),
@@ -80,6 +80,7 @@ fn recipe(s: &Session, p: &Value) -> Result<Dimension> {
| (DimensionMode::Angular, DimensionSource::Angle { .. })
| (DimensionMode::Radius | DimensionMode::Diameter, DimensionSource::Circle { .. } | DimensionSource::Arc { .. })
| (DimensionMode::Linear | DimensionMode::Angular, DimensionSource::Points { .. })
| (DimensionMode::Linear, DimensionSource::Extent { .. })
);
if !compatible {
return Err(error("Dimension mode does not match its source"));
@@ -175,7 +176,14 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
dim.options = o.clone();
}
if let Some(orientation) = orientation(p, dim.mode)? {
dim.set_orientation(orientation);
// An offset given with the orientation replaces the one the orientation would
// give: the dimension takes the orientation, and `resolve` reads its points.
if let Err(e) = dim.set_orientation(orientation, doc) {
if p.get("offset").is_none() {
return Err(error(e));
}
dim.orientation = orientation;
}
}
dim.offset = distance(p, dim.offset)?;
dim.resolve(doc).map_err(error)?;
@@ -457,7 +465,14 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<bool> {
for (id, old) in dimensions {
let mut next = old.clone();
let moved = next.moved.take();
if next.source.as_ref().is_some_and(|s| s.topology_changed(before, doc)) || next.resolve(doc).is_err() {
// Whether the path a dimension of a whole path measures changed: when it did not, the
// dimension keeps its points without reading the path again, and is only checked.
let whole_changed = match &next.source {
Some(s @ DimensionSource::Extent { .. }) => Some(s.art_changed(before, doc)),
_ => None,
};
let unreadable = if whole_changed == Some(false) { next.validate().is_err() } else { next.resolve(doc).is_err() };
if next.source.as_ref().is_some_and(|s| s.topology_changed(before, doc)) || unreadable {
// The art it measured was deleted, or rebuilt with other anchors, or no longer fits
// (an ellipse that was a circle): it stays where it was, no longer linked, in this
// same undo step, rather than attaching to a different edge.
@@ -470,13 +485,14 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<bool> {
changed = true;
continue;
}
next.keep_gap(&old);
next.keep_gap(&old, (whole_changed == Some(true)).then_some((before, doc)));
if let Some(xf) = next.source.as_ref().and_then(|s| s.reflection(before, doc)) {
next.mirror_line(&old, xf * old.handle());
next.mirror_line(&old, xf * old.handle(), Some((before, doc)));
}
// Moved on its own (the art it measures stayed put): it keeps its new place.
if let Some(v) = moved
&& (next.a, next.b, next.vertex) == (old.a, old.b, old.vertex)
&& whole_changed != Some(true)
{
next.place(old.handle() + v);
if next.resolve(doc).is_err() {
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -17,7 +17,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Setup",
[],
None,
"{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour; #rrggbbaa and #rgba are refused), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), alignNewObjectsToPixelGrid?: bool (Align New Objects to Pixel Grid: paths and compound paths drawn from then on are pixel-aligned, as object.setPixelAligned; art already in the document, pasted, duplicated or placed keeps its own setting), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup",
"{units?: \"Points\"|\"Inches\"|\"Millimeters\"|…, bleed?: pt (all sides)|[top, bottom, left, right]|{top?, bottom?, left?, right?} (0–72 pt), outlineImages?: bool (show images in Outline mode; off: a linked image or placed document shows its box crossed from corner to corner), highlightSubstitutedGlyphs?: bool (Highlight Substituted Fonts is a preference: prefs.set highlightSubstitutedFonts; a highlightSubstitutedFonts key is ignored and the reply carries a warning),gridSize?: \"small\"|\"medium\"|\"large\", gridColors?: \"Light\"|\"Medium\"|\"Dark\"|\"Red\"|\"Orange\"|\"Green\"|\"Blue\"|\"Purple\"|[colour, colour] (transparency grid; the first is also the paper colour; #rrggbbaa and #rgba are refused), simulatePaper?: bool, flattenerPreset?: \"High Resolution\"|\"Medium Resolution\"|\"Low Resolution\"|a saved preset (flattener.presets.list), discardWhiteOverprint?: bool, language?: \"English: USA\"|\"German\"|\"French\"|… (also picks its quotes), quotes?: {double?: \"“”\", single?: \"‘’\"} (beside a language: only if they differ from the current ones), typographersQuotes?: bool (typed straight quotes become the document's quotes), superscript?: {size?: %, position?: %}, subscript?: {size?: %, position?: %}, smallCapsSize?: %, exportText?: \"editable\"|\"appearance\" (SVG text as text or as outlines), backgroundContents?: \"transparent\"|\"white\" (white: raster exports are white behind the art), alignNewObjectsToPixelGrid?: bool (Align New Objects to Pixel Grid: paths and compound paths drawn from then on are pixel-aligned, as object.setPixelAligned; art already in the document, pasted, duplicated or placed keeps its own setting), …the keys of its own reply (it can be passed back; the values it only reports are ignored)} change the document setup in one undo step; no params → the current setup",
has_doc,
setup
)]
+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,
+11 -2
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",
@@ -120,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Smooth",
[],
None,
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12; from 0.001 to 1000), fidelity?: pt (2.5; from 0.000078125 to about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom, kept within the range)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}. A radius or fidelity outside its range is refused with an error, and nothing changes",
"{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12; from 0.001 to 1000), fidelity?: pt (2.5; from 0.000078125 to about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom, kept within the range)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side, and leaving a subpath as it is when the result would not be smoother (docs/mcp.md) → {ids, before, after}. A radius or fidelity outside its range is refused with an error, and nothing changes",
has_selection,
smooth_region
),
+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 }))
}
+441 -23
View File
@@ -1,3 +1,5 @@
use std::collections::HashMap;
use vectorcraft_pathops::addons::pathtools as pt;
use vectorcraft_pathops::start_nearest;
@@ -344,6 +346,8 @@ fn drag_stretches(pts: &[Point]) -> Vec<usize> {
/// The stretches of the drag `pts` among `of` whose bounds come within `radius` of `r` on both
/// axes: every stretch within `radius` of a point in `r`, and perhaps a few more.
fn stretches_near(pts: &[Point], of: &[usize], r: Rect, radius: f64) -> Vec<usize> {
#[cfg(test)]
STRETCH_TESTS.with(|c| c.set(c.get() + of.len()));
let r = r.inflate(radius, radius);
of.iter()
.copied()
@@ -355,8 +359,115 @@ fn stretches_near(pts: &[Point], of: &[usize], r: Rect, radius: f64) -> Vec<usiz
.collect()
}
#[cfg(test)]
thread_local! {
/// Tests: how many times this thread measured a point or a box against one stretch of a drag.
static STRETCH_TESTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Most grid cells [`DragReach`] lists one stretch of the drag in. A stretch whose reach covers more
/// is measured against every point and box instead.
const MAX_STRETCH_CELLS: usize = 64;
/// Most grid cells across the drag's bounds on each axis in [`DragReach`].
const MAX_DRAG_CELLS: f64 = 1024.0;
/// The stretches of a Smooth drag listed by the cells of a grid that their reach covers, so that a
/// point or a piece of path is measured only against the stretches whose reach it is in. Each query
/// gives at least every stretch that measuring against the whole drag finds in reach, so the results
/// are the same as measuring against the whole drag.
struct DragReach<'a> {
pts: &'a [Point],
radius: f64,
/// Every stretch of the drag, in order.
all: Vec<usize>,
/// The drag's bounds grown by more than `radius`, with the cell size; `None` when the drag or
/// the reach is not a finite number, and then every query gives every stretch.
grid: Option<(Rect, f64)>,
cells: HashMap<(i64, i64), Vec<usize>>,
/// The stretches whose reach covers more than [`MAX_STRETCH_CELLS`] cells.
wide: Vec<usize>,
}
impl<'a> DragReach<'a> {
fn new(pts: &'a [Point], radius: f64) -> Self {
let all = drag_stretches(pts);
let mut reach = DragReach { pts, radius, all, grid: None, cells: HashMap::new(), wide: vec![] };
if pts.is_empty() || !radius.is_finite() || pts.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) {
return reach;
}
// Enough more than the reach to cover the rounding of each distance and box measured.
let size = pts.iter().fold(0.0_f64, |m, p| m.max(p.x.abs()).max(p.y.abs()));
let pad = radius + 1e-6 * radius.max(1.0) + 1e-9 * size;
let area = poly_bounds(pts, pad);
let cell = pad.max(area.width().max(area.height()) / MAX_DRAG_CELLS);
if !(cell.is_finite() && cell > 0.0 && area.width().is_finite() && area.height().is_finite()) {
return reach;
}
reach.grid = Some((area, cell));
for &k in &reach.all {
let Some(&a) = pts.get(k) else { continue };
let b = pts.get(k + 1).copied().unwrap_or(a);
let r = Rect::from_points(a, b).inflate(pad, pad);
let ((x0, y0), (x1, y1)) = (reach.cell_of(Point::new(r.x0, r.y0)), reach.cell_of(Point::new(r.x1, r.y1)));
if (x1 - x0 + 1).saturating_mul(y1 - y0 + 1) > MAX_STRETCH_CELLS as i64 {
reach.wide.push(k);
continue;
}
for x in x0..=x1 {
for y in y0..=y1 {
reach.cells.entry((x, y)).or_default().push(k);
}
}
}
reach
}
/// The cell `q` is in, counted from the corner of the grid.
fn cell_of(&self, q: Point) -> (i64, i64) {
let Some((area, cell)) = self.grid else { return (0, 0) };
(((q.x - area.x0) / cell).floor() as i64, ((q.y - area.y0) / cell).floor() as i64)
}
/// Whether `q` is within the reach of the drag, and `slack` more.
fn in_reach(&self, q: Point, slack: f64) -> bool {
let limit = self.radius + slack;
let Some((area, _)) = self.grid else { return dist_to_stretches(self.pts, &self.all, q) <= limit };
if !(q.x >= area.x0 && q.x <= area.x1 && q.y >= area.y0 && q.y <= area.y1) {
return false;
}
let listed = self.cells.get(&self.cell_of(q)).map_or(&[][..], Vec::as_slice);
dist_to_stretches(self.pts, listed, q).min(dist_to_stretches(self.pts, &self.wide, q)) <= limit
}
/// The stretches, in order, that may come within the reach of `r`: at least every one that
/// [`stretches_near`] gives for `r` from the whole drag.
fn near_rect(&self, r: Rect) -> Vec<usize> {
let Some((area, _)) = self.grid else { return self.all.clone() };
let (x0, x1, y0, y1) = (r.x0.max(area.x0), r.x1.min(area.x1), r.y0.max(area.y0), r.y1.min(area.y1));
if !(x0 <= x1 && y0 <= y1) {
return vec![];
}
let ((cx0, cy0), (cx1, cy1)) = (self.cell_of(Point::new(x0, y0)), self.cell_of(Point::new(x1, y1)));
if (cx1 - cx0 + 1).saturating_mul(cy1 - cy0 + 1) > self.all.len() as i64 {
return self.all.clone();
}
let mut out = self.wide.clone();
for x in cx0..=cx1 {
for y in cy0..=cy1 {
out.extend(self.cells.get(&(x, y)).into_iter().flatten());
}
}
out.sort_unstable();
out.dedup();
out
}
}
/// The distance from `q` to the nearest of the stretches `of` of the drag `pts`.
fn dist_to_stretches(pts: &[Point], of: &[usize], q: Point) -> f64 {
#[cfg(test)]
STRETCH_TESTS.with(|c| c.set(c.get() + of.len()));
of.iter()
.filter_map(|&k| {
let a = *pts.get(k)?;
@@ -391,15 +502,18 @@ fn nearest_to_stretches(s: CubicBez, pts: &[Point], of: &[usize]) -> (f64, f64)
best
}
/// How many curved segments of `pd` may come within `radius` of the drag `pts`.
fn segments_in_reach(pd: &PathData, pts: &[Point], radius: f64) -> usize {
let all = drag_stretches(pts);
/// How many curved segments of `pd` may come within the reach of the drag.
fn segments_in_reach(pd: &PathData, reach: &DragReach) -> usize {
pd.subpaths
.iter()
.map(|sp| {
(0..sp.segment_count())
.filter(|&i| {
!vectorcraft_tools::draw2::segment_is_straight(sp, i) && !stretches_near(pts, &all, control_box(sp.segment(i)), radius).is_empty()
if vectorcraft_tools::draw2::segment_is_straight(sp, i) {
return false;
}
let b = control_box(sp.segment(i));
!stretches_near(reach.pts, &reach.near_rect(b), b, reach.radius).is_empty()
})
.count()
})
@@ -439,26 +553,26 @@ fn reach_samples(c: CubicBez, (t0, t1): (f64, f64), (pts, of): (&[Point], &[usiz
reach_samples(c, (mid, t1), (pts, &near), radius, budget, out);
}
/// `sp` cut where the reach `radius` of the drag `pts` crosses its curved segments, and whether each
/// `sp` cut where the reach of the drag crosses its curved segments, and whether each
/// anchor of the result is in reach. An anchor in reach is added in the middle of each stretch of a
/// segment in reach that does not run on from one of the segment's anchors in reach, and an anchor
/// out of reach in the middle of each stretch out of reach between two stretches in reach, so that a
/// stretch in reach is smoothed even when the segment's anchors are not, and the stretches between
/// stay as they are. A segment is searched no more than half the reach apart where it comes within
/// the reach of the drag ([`reach_samples`]), measuring up to `share` pieces of each segment.
fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubPath, Vec<bool>) {
let near = |q: Point| dist_to_polyline(pts, q) <= radius;
fn mark_reached(sp: &SubPath, reach: &DragReach, share: usize) -> (SubPath, Vec<bool>) {
let (pts, radius) = (reach.pts, reach.radius);
let n = sp.anchors.len();
let marked: Vec<bool> = sp.anchors.iter().map(|a| near(a.p)).collect();
let marked: Vec<bool> = sp.anchors.iter().map(|a| reach.in_reach(a.p, 0.0)).collect();
let mut places = vec![];
let all = drag_stretches(pts);
for i in 0..sp.segment_count() {
if vectorcraft_tools::draw2::segment_is_straight(sp, i) {
continue;
}
let c = sp.segment(i);
let (mut samples, mut budget) = (vec![], share);
reach_samples(c, (0.0, 1.0), (pts, &all), radius, &mut budget, &mut samples);
let near = reach.near_rect(control_box(c.subsegment(0.0..1.0)));
reach_samples(c, (0.0, 1.0), (pts, &near), radius, &mut budget, &mut samples);
// Stretches of samples alike, in order: (in reach, first, last).
let mut runs: Vec<(bool, usize, usize)> = vec![];
for (k, s) in samples.iter().enumerate() {
@@ -496,7 +610,7 @@ fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubP
.anchors
.iter()
.enumerate()
.map(|(j, a)| if added.contains(&j) { dist_to_polyline(pts, a.p) <= radius + 1e-9 * radius.max(1.0) } else { kept.next().unwrap_or(false) })
.map(|(j, a)| if added.contains(&j) { reach.in_reach(a.p, 1e-9 * radius.max(1.0)) } else { kept.next().unwrap_or(false) })
.collect();
(out, marked)
}
@@ -504,13 +618,14 @@ fn mark_reached(sp: &SubPath, pts: &[Point], radius: f64, share: usize) -> (SubP
/// `sp` with the anchors in the drag's reach smoothed and refitted, `None` when none are in reach.
/// A closed path whose first anchor is in reach starts at the point of the refitted path nearest
/// that anchor's place (VectorCraft's own rule).
fn smooth_subpath(sp: &SubPath, pts: &[Point], radius: f64, share: usize, tol: f64, sigma: f64) -> Option<SubPath> {
fn smooth_subpath(sp: &SubPath, reach: &DragReach, share: usize, tol: f64, sigma: f64) -> Option<SubPath> {
if sp.anchors.len() < 2 {
return None;
}
let near = &|q: Point| dist_to_polyline(pts, q) <= radius;
let radius = reach.radius;
let near = &|q: Point| reach.in_reach(q, 0.0);
// A drag along a segment smooths it even when its anchors are out of reach.
let (sp, marked) = mark_reached(sp, pts, radius, share);
let (sp, marked) = mark_reached(sp, reach, share);
let sp = &sp;
if !marked.iter().any(|m| *m) {
return None;
@@ -634,14 +749,16 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
}
i += 1;
}
let mut out = anchors.to_vec();
let mut out = EditsFromEnd::new(anchors.to_vec());
for (a, b) in runs.into_iter().rev() {
let (mut lo, mut hi) = (a.saturating_sub(1), (b + 1).min(n - 1));
// How much of the segments leading out of the run is in reach. A segment that is in reach
// only at the run's anchor stays out of the piece, so the piece ends at that anchor rather
// than in a sliver of a segment, which would leave the refit no direction to end along.
let after = if hi > b { split_at_reach(CubicBez::new(out[hi].p, out[hi].h_in, out[b].h_out, out[b].p), near, radius) } else { Reach::Whole };
let before = if lo < a { split_at_reach(CubicBez::new(out[lo].p, out[lo].h_out, out[a].h_in, out[a].p), near, radius) } else { Reach::Whole };
let Some(span) = out.get(lo, hi) else { continue };
let (first, start, end, last) = (span[0], span[a - lo], span[b - lo], span[hi - lo]);
let after = if hi > b { split_at_reach(CubicBez::new(last.p, last.h_in, end.h_out, end.p), near, radius) } else { Reach::Whole };
let before = if lo < a { split_at_reach(CubicBez::new(first.p, first.h_out, start.h_in, start.p), near, radius) } else { Reach::Whole };
if matches!(after, Reach::End) {
hi = b;
}
@@ -651,7 +768,8 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
if hi == lo {
continue;
}
let mut piece = out[lo..=hi].to_vec();
let Some(piece) = out.get(lo, hi) else { continue };
let mut piece = piece.to_vec();
// The anchors outside the reach, kept with the part of their segment that is outside.
let (mut head, mut tail) = (None, None);
if let Reach::Split(far, reach) = after
@@ -674,9 +792,132 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool
if same_anchors(&new, &piece) {
continue;
}
out.splice(lo..=hi, head.into_iter().chain(new).chain(tail));
out.replace(lo, hi, head.into_iter().chain(new).chain(tail));
}
out
out.finish()
}
/// A list edited by replacing stretches of it, each one ending no later than where the one before
/// started, in time proportional to the items replaced and moved rather than to the list's length
/// for each edit.
struct EditsFromEnd<T> {
/// The start of the list.
head: Vec<T>,
/// The rest of the list, last item first.
rest: Vec<T>,
}
impl<T> EditsFromEnd<T> {
fn new(items: Vec<T>) -> Self {
EditsFromEnd { head: items, rest: vec![] }
}
/// The items `lo` to `hi` of the list, `None` when it is shorter.
fn get(&mut self, lo: usize, hi: usize) -> Option<&[T]> {
while self.head.len() <= hi {
self.head.push(self.rest.pop()?);
}
self.head.get(lo..=hi)
}
/// The list with the items `lo` to `hi` replaced by `with`, as [`Vec::splice`] gives it. Leaves
/// the list as it is when it is shorter.
fn replace(&mut self, lo: usize, hi: usize, with: impl IntoIterator<Item = T>) {
if lo > hi || self.get(lo, hi).is_none() {
return;
}
self.rest.extend(self.head.drain(hi + 1..).rev());
self.head.truncate(lo);
self.head.extend(with);
}
fn finish(mut self) -> Vec<T> {
self.head.extend(self.rest.into_iter().rev());
self.head
}
}
/// Most pieces [`roughness`] cuts one curved segment into.
const ROUGHNESS_SEGMENT_PIECES: usize = 1024;
/// Most pieces [`roughness`] cuts the curved segments of one subpath into, shared equally by them.
const ROUGHNESS_PIECES: usize = 1 << 18;
/// How rough the subpath `sp` is, measured along the lines between points on each curved segment
/// about `step` apart along its control polygon (at least 4 and at most
/// [`ROUGHNESS_SEGMENT_PIECES`] pieces a segment, fewer on a subpath of very many segments): how
/// much it turns along its length in radians, from the direction each segment leaves its first anchor
/// along to the one it arrives at its last anchor along, with each turn at an anchor counted twice;
/// and how much it bends, the sum of each turn between two pieces squared over their mean length.
/// `None` when a point or a turn is not a number.
fn roughness(sp: &SubPath, step: f64) -> Option<(f64, f64)> {
let segments = sp.segment_count();
let most = (ROUGHNESS_PIECES / segments.max(1)).clamp(4, ROUGHNESS_SEGMENT_PIECES);
// The directions along the path, each with whether it leaves an anchor, and the pieces' vectors.
let (mut dirs, mut pieces): (Vec<(kurbo::Vec2, bool)>, Vec<kurbo::Vec2>) = (vec![], vec![]);
for i in 0..segments {
let c = sp.segment(i);
if sp.segment_is_line(i) {
dirs.push((c.p3 - c.p0, true));
pieces.push(c.p3 - c.p0);
continue;
}
let leave = [c.p1 - c.p0, c.p2 - c.p0, c.p3 - c.p0].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default();
let arrive = [c.p3 - c.p2, c.p3 - c.p1, c.p3 - c.p0].into_iter().find(|d| d.hypot() > 1e-12).unwrap_or_default();
let len = polygon_len(c);
let k = if step > 0.0 && step.is_finite() && len.is_finite() { (len / step).ceil().clamp(4.0, most as f64) as usize } else { most };
dirs.push((leave, true));
let mut at = c.p0;
for j in 1..=k {
let q = if j == k { c.p3 } else { c.eval(j as f64 / k as f64) };
dirs.push((q - at, false));
pieces.push(q - at);
at = q;
}
dirs.push((arrive, false));
}
// A direction of no length is left out; the turn at an anchor is then taken at the next one.
let mut kept: Vec<(kurbo::Vec2, bool)> = Vec::with_capacity(dirs.len());
let mut at_anchor = false;
for (d, anchor) in dirs {
at_anchor |= anchor;
if d.hypot() > 1e-12 {
kept.push((d, at_anchor));
at_anchor = false;
}
}
pieces.retain(|d| d.hypot() > 1e-12);
let turn = |u: kurbo::Vec2, v: kurbo::Vec2| u.cross(v).atan2(u.dot(v)).abs();
let pairs = |n: usize| if sp.closed { n } else { n.saturating_sub(1) };
let mut turning = 0.0;
for j in 0..pairs(kept.len()) {
let (u, (v, anchor)) = (kept[j].0, kept[(j + 1) % kept.len()]);
turning += if anchor { 2.0 } else { 1.0 } * turn(u, v);
}
let mut bending = 0.0;
for j in 0..pairs(pieces.len()) {
let (u, v) = (pieces[j], pieces[(j + 1) % pieces.len()]);
bending += turn(u, v).powi(2) / (0.5 * (u.hypot() + v.hypot()));
}
(turning.is_finite() && bending.is_finite()).then_some((turning, bending))
}
/// Whether the Smooth tool keeps `new`, the subpath `old` smoothed with the reach `radius`
/// (VectorCraft's own rule). Both are measured with [`roughness`] at one spacing, an eighth of the
/// reach or 1/512 of the diagonal of `old`'s control points, whichever is smaller. `new` must turn
/// no more than a thousandth more than `old` (counting a turn of less than 1 radian as 1), and it
/// must have fewer anchors, turn less, or bend more than a ten-thousandth less. A result that would
/// leave the path rougher, or that adds anchors or changes the path without smoothing it, is not
/// kept.
fn smoother(old: &SubPath, new: &SubPath, radius: f64) -> bool {
let size = old.anchors.iter().fold(None, |r: Option<Rect>, a| {
let b = Rect::from_points(a.p, a.h_in).union_pt(a.h_out);
Some(r.map_or(b, |r| r.union(b)))
});
let step = (radius / 8.0).min(size.map_or(0.0, |r| r.width().hypot(r.height()) / 512.0));
let (Some((t0, b0)), Some((t1, b1))) = (roughness(old, step), roughness(new, step)) else { return false };
let scale = t0.max(1.0);
t1 <= t0 + 1e-3 * scale && (new.anchors.len() < old.anchors.len() || t0 - t1 >= 1e-6 * scale || b0 - b1 > 1e-4 * b0)
}
pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
@@ -696,15 +937,16 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, radius)) {
paths.push((id, path_of(&st.doc, id)?.0));
}
let reach = DragReach::new(&pts, radius);
// Each curved segment in reach gets the same share of the search, whatever order they come in.
let in_reach: usize = paths.iter().map(|(_, pd)| segments_in_reach(pd, &pts, radius)).sum();
let in_reach: usize = paths.iter().map(|(_, pd)| segments_in_reach(pd, &reach)).sum();
let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1);
for (id, pd) in paths {
let mut changed = false;
let subs: Vec<SubPath> = pd
.subpaths
.iter()
.map(|sp| match smooth_subpath(sp, &pts, radius, share, tol, sigma) {
.map(|sp| match smooth_subpath(sp, &reach, share, tol, sigma) {
Some(n) if n != *sp && n.anchors.len() >= 2 => {
changed = true;
n
@@ -712,7 +954,10 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result<Value> {
_ => sp.clone(),
})
.collect();
if changed {
// A subpath whose result would not be smoother stays as it was.
let subs: Vec<SubPath> =
subs.into_iter().zip(&pd.subpaths).map(|(n, sp)| if n == *sp || smoother(sp, &n, radius) { n } else { sp.clone() }).collect();
if changed && subs != pd.subpaths {
let np = PathData::new(subs);
before += pd.anchor_count();
after += np.anchor_count();
@@ -1082,6 +1327,153 @@ mod tests {
pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect()
}
/// A path of `n` smooth anchors 1 pt apart, along x and up and down by 3 pt, every segment
/// curved; closed, the anchors go round a circle `n` pt long instead.
fn wave(n: usize, closed: bool) -> SubPath {
let anchors = (0..n)
.map(|i| {
let f = i as f64;
if closed {
let r = n as f64 / std::f64::consts::TAU + f64::from(u8::from(i % 2 == 1)) * 3.0;
let a = f / n as f64 * std::f64::consts::TAU;
let (p, t) = (Point::new(r * a.cos(), r * a.sin()), kurbo::Vec2::new(-a.sin(), a.cos()) * 0.4);
Anchor::with_handles(p, p - t, p + t)
} else {
let p = Point::new(f, f64::from(u8::from(i % 2 == 1)) * 3.0);
Anchor::with_handles(p, p - kurbo::Vec2::new(0.4, 0.0), p + kurbo::Vec2::new(0.4, 0.0))
}
})
.collect();
SubPath::new(anchors, closed)
}
/// The same drag measured against all of its stretches for every point and box.
fn linear<'a>(pts: &'a [Point], radius: f64) -> DragReach<'a> {
DragReach { grid: None, ..DragReach::new(pts, radius) }
}
/// How many stretch measures `f` made on this thread.
fn stretch_tests(f: impl FnOnce()) -> usize {
STRETCH_TESTS.with(|c| c.set(0));
f();
STRETCH_TESTS.with(std::cell::Cell::get)
}
/// A drag of 200 points over 200 pt of a curved path of 100,000 anchors measures the anchors
/// and segments near the drag against the stretches near them, not every anchor and segment
/// against every stretch (about 40 million measures), and smooths the path as measuring
/// everything does.
#[test]
fn a_drag_over_a_long_path_measures_only_what_is_near_it() {
let sp = wave(100_000, false);
let pts: Vec<Point> = (0..200).map(|i| Point::new(50_000.0 + f64::from(i), 1.5)).collect();
let reach = DragReach::new(&pts, 12.0);
let pd = PathData::single(sp.clone());
let mut in_reach = 0;
let boxes = stretch_tests(|| in_reach = segments_in_reach(&pd, &reach));
assert!(in_reach > 0 && boxes < 100_000, "{in_reach} segments in reach, {boxes} measures");
let share = (MAX_REACH_PIECES / in_reach).max(1);
let mut got = None;
let marks = stretch_tests(|| got = Some(mark_reached(&sp, &reach, share)));
assert!(marks < 100_000, "{marks} measures");
let smoothed = smooth_subpath(&sp, &reach, share, 2.5, 4.0);
assert!(smoothed.is_some());
let all = linear(&pts, 12.0);
assert_eq!(segments_in_reach(&pd, &all), in_reach);
assert_eq!(Some(mark_reached(&sp, &all, share)), got);
assert_eq!(smooth_subpath(&sp, &all, share, 2.5, 4.0), smoothed);
}
/// Paths and drags of many shapes, a drag of one point, one far away, one with a stretch longer
/// than the grid lists by cell, one with a point that is not a number, and reaches of 0 to 50 pt:
/// the grid gives the same segments in reach, the same marks and the same smoothed path as
/// measuring against the whole drag.
#[test]
fn the_drag_grid_gives_the_results_of_measuring_the_whole_drag() {
let far = Point::new(1e7, -1e7);
let paths = [
ring(),
wave(1500, false),
wave(1500, true),
SubPath::polyline(&(0..500).map(|i| Point::new(f64::from(i) * 2.0, f64::from(i % 3) * 4.0)).collect::<Vec<_>>(), false),
SubPath::new(
vec![Anchor::with_handles(Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(3e5, 4e5)), Anchor::corner(Point::new(1e6, 0.0))],
false,
),
SubPath::new(
wave(200, true)
.anchors
.iter()
.map(|a| Anchor::with_handles(a.p + far.to_vec2(), a.h_in + far.to_vec2(), a.h_out + far.to_vec2()))
.collect(),
true,
),
];
let line = |from: (f64, f64), to: (f64, f64), n: u32| -> Vec<Point> {
(0..=n).map(|i| Point::new(from.0, from.1).lerp(Point::new(to.0, to.1), f64::from(i) / f64::from(n))).collect()
};
let mut loop_drag: Vec<Point> =
(0..400).map(|i| Point::new(100.0 + 120.0 * (f64::from(i) * 0.05).cos(), 120.0 * (f64::from(i) * 0.05).sin())).collect();
loop_drag.extend(line((0.0, 0.0), (1500.0, 2.0), 50));
let drags = [
vec![Point::new(150.0, 100.0)],
line((40.0, 90.0), (160.0, 110.0), 30),
line((-100.0, 1.0), (1600.0, 2.0), 1500),
loop_drag,
line((5e6, 5e6), (5e6 + 10.0, 5e6), 5),
vec![Point::new(0.0, 0.0), Point::new(1500.0, 3.0), Point::new(1500.0, 3.2), Point::new(10.0, 0.5)],
vec![Point::new(10.0, 1.0), Point::new(f64::NAN, 0.0), Point::new(12.0, 1.0)],
(0..1000).map(|i| Point::new(f64::from(i) * 0.01, 1.0)).collect(),
line((far.x, far.y), (far.x + 300.0, far.y + 40.0), 80),
];
for pts in &drags {
for radius in [0.0, 0.5, 12.0, 50.0] {
let (grid, all) = (DragReach::new(pts, radius), linear(pts, radius));
for (k, sp) in paths.iter().enumerate() {
let pd = PathData::single(sp.clone());
let in_reach = segments_in_reach(&pd, &all);
assert_eq!(segments_in_reach(&pd, &grid), in_reach, "path {k}, reach {radius}, drag {:?}", pts.first());
let share = (MAX_REACH_PIECES / in_reach.max(1)).max(1);
assert_eq!(mark_reached(sp, &grid, share), mark_reached(sp, &all, share), "path {k}, reach {radius}, drag {:?}", pts.first());
let sigma = radius * SMOOTH_SPREAD;
let want = smooth_subpath(sp, &all, share, 2.5, sigma);
assert_eq!(smooth_subpath(sp, &grid, share, 2.5, sigma), want, "path {k}, reach {radius}, drag {:?}", pts.first());
}
}
}
}
/// Replacing stretches of a list from its end, each one ending no later than where the one
/// before started (sometimes on that item, sometimes with nothing or with more items), gives the
/// list that [`Vec::splice`] gives.
#[test]
fn edits_from_the_end_match_splicing() {
let mut seed = 0x2545_f491_u64;
let mut next = |m: usize| {
seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407);
(seed >> 33) as usize % m.max(1)
};
for round in 0..200 {
let items: Vec<usize> = (0..next(60) + 1).collect();
let (mut want, mut got) = (items.clone(), EditsFromEnd::new(items.clone()));
let mut end = items.len() - 1;
loop {
let hi = end.saturating_sub(next(3));
let lo = hi.saturating_sub(next(6));
let with: Vec<usize> = (0..next(5)).map(|j| 1000 * (round + 1) + j).collect();
let Some(stretch) = want.get(lo..=hi).map(<[usize]>::to_vec) else { break };
assert_eq!(got.get(lo, hi).map(<[usize]>::to_vec), Some(stretch), "round {round}");
want.splice(lo..=hi, with.clone());
got.replace(lo, hi, with);
if lo == 0 {
break;
}
end = lo;
}
assert_eq!(got.finish(), want, "round {round}");
}
}
/// Anchors on one point, anchors that are not numbers or are too far out to measure, and a
/// zigzag of 100,001 anchors 1 pt high give no corner and do not fail; a square's four anchors
/// are its corners, and an open path's ends never are.
@@ -1201,4 +1593,30 @@ mod tests {
assert_eq!(smooth_corners(&jags, true, 12.0), vec![false; 16]);
assert_eq!(smooth_corners(&polyline(&[(0.0, 0.0), (6.0, 0.0), (3.0, 5.196)]), true, 12.0), vec![true; 3]);
}
/// `sp` scaled by `k` about the origin.
fn scaled(sp: &SubPath, k: f64) -> SubPath {
let at = |p: Point| Point::new(p.x * k, p.y * k);
SubPath::new(sp.anchors.iter().map(|a| Anchor { p: at(a.p), h_in: at(a.h_in), h_out: at(a.h_out), ..*a }).collect::<Vec<Anchor>>(), sp.closed)
}
/// The Smooth tool keeps a result that turns less, and not one that turns more with as many
/// anchors, one that adds an anchor and keeps the outline, or one that is the path itself, at
/// any size.
#[test]
fn the_smooth_tool_keeps_only_a_smoother_result() {
let round = ring();
let mut bumped = ring();
bumped.anchors[1].translate(kurbo::Vec2::new(0.0, -25.0));
let split = start_nearest(ring(), round.segment(0).eval(0.3), &round);
assert_eq!(split.anchors.len(), 5, "{split:?}");
for k in [1e-3, 1.0, 1e3] {
let (round, bumped, split) = (scaled(&round, k), scaled(&bumped, k), scaled(&split, k));
let reach = 12.0 * k;
assert!(smoother(&bumped, &round, reach), "at {k}x a bump smoothed away is kept");
assert!(!smoother(&round, &bumped, reach), "at {k}x a bump added is not kept");
assert!(!smoother(&round, &split, reach), "at {k}x an anchor added on the outline is not kept");
assert!(!smoother(&round, &round.clone(), reach), "at {k}x the same path is not kept");
}
}
}
+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";
+25 -7
View File
@@ -7,7 +7,9 @@
//! about the point the object turns about: in points in OBJ and USD (whose layer says how many
//! meters a unit is), in meters in glTF, as its specification asks. glTF and USD colors are linear,
//! as their specifications ask; MTL colors are the display colors. Materials are two-sided, since
//! an open solid or a turned plane is seen from both sides.
//! an open solid or a turned plane is seen from both sides. Every corner carries its normal and
//! texture coordinates (`vt`, `TEXCOORD_0`, `primvars:st`); a mesh whose lists do not match, or
//! that holds a value that is not a number, is refused before anything is written.
//!
//! The graphics mapped onto a face of a solid ([`textures`]) are a PNG picture of that face: its
//! color with the graphics drawn over it, flat and unshaded, which the face's own mesh shows through
@@ -140,6 +142,7 @@ pub(crate) fn image_maps(textures: &[Option<Texture>]) -> Vec<bool> {
/// OBJ with its MTL after it and the PNG files of `textures` last (an OBJ's opacity maps each after
/// its texture). `textures` holds the picture of each part that has one, in the order of `parts`.
pub(crate) fn mesh_files(stem: &str, format: &str, parts: &[SolidMesh], textures: &[Option<Texture>]) -> Result<Vec<(String, Vec<u8>)>, String> {
check_parts(parts)?;
let (images, image) = images(parts.len(), textures);
let maps: Vec<bool> = images.iter().map(|(_, map)| map.is_some()).collect();
let names = mesh_file_names(stem, format, &maps)?;
@@ -180,6 +183,21 @@ impl Scene<'_> {
let t = self.textures.get(k)?.as_ref()?;
Some((t.uv.as_slice(), (*self.image.get(k)?)?))
}
/// Part `k`'s texture coordinates, one for each corner, 0 to 1 across from the left and down
/// from the top: its picture's when it has one, else its mesh's own.
fn coords(&self, k: usize) -> Option<&[[f64; 2]]> {
let count = self.parts.get(k)?.mesh.positions.len();
let own = self.parts.get(k).map(|p| p.mesh.uvs.as_slice());
self.texture(k).map(|(uv, _)| uv).into_iter().chain(own).find(|uv| uv.len() == count && count > 0)
}
}
/// An error when a part's mesh cannot be written as it is: its lists do not match, or a
/// position, normal or texture coordinate is not a number
/// ([`vectorcraft_render::effects::Mesh::check`]).
fn check_parts(parts: &[SolidMesh]) -> Result<(), String> {
parts.iter().try_for_each(|p| p.mesh.check())
}
/// A material: a color, with a picture that replaces its red, green and blue.
@@ -230,7 +248,7 @@ fn obj(stem: &str, scene: &Scene) -> (String, String) {
}
// OBJ's texture coordinates run up from the picture's bottom.
for k in 0..parts.len() {
for uv in scene.texture(k).map(|(uv, _)| uv).unwrap_or_default() {
for uv in scene.coords(k).unwrap_or_default() {
let _ = writeln!(o, "vt {} {}", num(uv[0]), num(1.0 - uv[1]));
}
}
@@ -243,9 +261,9 @@ fn obj(stem: &str, scene: &Scene) -> (String, String) {
for (k, p) in parts.iter().enumerate() {
let _ = writeln!(o, "g Solid_{}", k + 1);
let _ = writeln!(o, "usemtl Material_{}", material.get(k).copied().unwrap_or(0) + 1);
let textured = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()).is_some();
let coords = scene.coords(k).is_some();
for t in &p.mesh.triangles {
if textured {
if coords {
let [a, b, c] = t.map(|i| i as usize);
let corner = |i: usize| format!("{}/{}/{}", i + base, i + uv_base, i + base);
let _ = writeln!(o, "f {} {} {}", corner(a), corner(b), corner(c));
@@ -255,7 +273,7 @@ fn obj(stem: &str, scene: &Scene) -> (String, String) {
}
}
base += p.mesh.positions.len();
uv_base += scene.texture(k).map_or(0, |(uv, _)| uv.len());
uv_base += scene.coords(k).map_or(0, <[_]>::len);
}
let mut m = String::new();
for (k, mat) in materials.iter().enumerate() {
@@ -313,7 +331,7 @@ fn gltf(stem: &str, scene: &Scene) -> String {
"material": material.get(k).copied().unwrap_or(0),
});
// glTF's texture coordinates run down from the picture's top, as the picture's own do.
if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == count) {
if let Some(uv) = scene.coords(k) {
let bytes = uv.iter().flatten().flat_map(|x| (*x as f32).to_le_bytes()).collect();
let coords = view(&mut buffer, bytes, 34962);
primitive["attributes"]["TEXCOORD_0"] = json!(accessors.len());
@@ -415,7 +433,7 @@ fn usda(stem: &str, scene: &Scene) -> String {
);
let _ = writeln!(u, " float[] primvars:displayOpacity = [{}] (\n interpolation = \"constant\"\n )", c[3]);
// USD's texture coordinates run up from the picture's bottom.
if let Some((uv, _)) = scene.texture(k).filter(|(uv, _)| uv.len() == p.mesh.positions.len()) {
if let Some(uv) = scene.coords(k) {
let st = list(uv.iter().map(|t| format!("({}, {})", num(t[0]), num(1.0 - t[1]))).collect());
let _ = writeln!(u, " texCoord2f[] primvars:st = [{st}] (\n interpolation = \"vertex\"\n )");
}
+49 -13
View File
@@ -1,12 +1,18 @@
use serde_json::Value;
use vectorcraft_render::effects::{Mesh, SolidMesh};
use vectorcraft_render::effects::{Mesh, MeshPart, SolidMesh};
use super::*;
/// A 10 × 10 square facing the viewer: two triangles, each with corners of its own.
fn square(color: [f32; 4]) -> SolidMesh {
let [a, b, c, d] = [[-5.0, -5.0, 0.0], [5.0, -5.0, 0.0], [5.0, 5.0, 0.0], [-5.0, 5.0, 0.0]];
let mesh = Mesh { positions: vec![a, b, c, a, c, d], normals: vec![[0.0, 0.0, 1.0]; 6], triangles: vec![[0, 1, 2], [3, 4, 5]] };
let mesh = Mesh {
positions: vec![a, b, c, a, c, d],
normals: vec![[0.0, 0.0, 1.0]; 6],
uvs: vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]],
triangles: vec![[0, 1, 2], [3, 4, 5]],
parts: vec![MeshPart::Front; 2],
};
SolidMesh::plain(mesh, color)
}
@@ -31,8 +37,9 @@ fn obj_numbers_corners_across_solids_and_names_its_materials() {
assert!(obj.starts_with("mtllib Box.mtl\no Box\n"));
assert_eq!(obj.lines().filter(|l| l.starts_with("v ")).count(), 18);
assert_eq!(obj.lines().filter(|l| l.starts_with("vn ")).count(), 18);
assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).count(), 18);
// The third solid's last triangle uses corners 13 to 18; red solids share Material_1.
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 16//16 17//17 18//18"));
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 16/16/16 17/17/17 18/18/18"));
assert_eq!(obj.lines().filter(|l| l.starts_with("usemtl ")).collect::<Vec<_>>(), ["usemtl Material_1", "usemtl Material_2", "usemtl Material_1"]);
let mtl = text(&files, "Box.mtl");
assert_eq!(mtl.matches("newmtl").count(), 2);
@@ -64,8 +71,12 @@ fn gltf_holds_its_buffer_and_every_accessor_fits_it() {
assert_eq!(g["materials"][1]["alphaMode"], "BLEND");
assert!(g["materials"][0].get("alphaMode").is_none());
assert_eq!(g["materials"][0]["doubleSided"], true);
// Without graphics there are no textures.
assert!(g.get("images").is_none() && g.get("textures").is_none() && prims[0]["attributes"].get("TEXCOORD_0").is_none());
// Without graphics there are no textures, but every corner has its mesh's texture coordinates.
assert!(g.get("images").is_none() && g.get("textures").is_none());
for p in prims {
let uv = &g["accessors"][p["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize];
assert_eq!((uv["type"].as_str(), uv["count"].as_u64()), (Some("VEC2"), Some(6)));
}
}
#[test]
@@ -82,7 +93,28 @@ fn usda_is_y_up_in_points_with_a_material_for_each_color() {
// sRGB 0.5 is about 0.214 linear.
assert!(u.contains("color3f inputs:diffuseColor = (0.21404"), "{u}");
assert_eq!(u.matches('{').count(), u.matches('}').count());
assert!(!u.contains("primvars:st") && !u.contains("UsdUVTexture"));
// Each mesh carries its own texture coordinates, up from the bottom, with no picture to show.
assert_eq!(u.matches("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]").count(), 2, "{u}");
assert!(!u.contains("UsdUVTexture"));
}
#[test]
fn a_mesh_whose_lists_do_not_match_or_hold_no_number_is_refused() {
let good = square(RED);
let mut nan = square(RED);
nan.mesh.uvs[2] = [f64::NAN, 0.0];
let mut infinite = square(RED);
infinite.mesh.normals[0] = [f64::INFINITY, 0.0, 0.0];
let mut short = square(RED);
short.mesh.uvs.pop();
let mut unnamed = square(RED);
unnamed.mesh.parts.pop();
for bad in [nan, infinite, short, unnamed] {
for format in FORMATS_3D {
assert!(plain_files("Box", format, &[good.clone(), bad.clone()]).is_err(), "{format} {bad:?}");
}
}
assert!(plain_files("Box", "obj", &[good]).is_ok());
}
#[test]
@@ -141,7 +173,10 @@ fn prim_names_are_usd_identifiers() {
fn textured(png: &[u8]) -> (Vec<SolidMesh>, Vec<Option<Texture>>) {
let uv = vec![[0.0, 1.0], [1.0, 1.0], [1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]];
let texture = Texture { png: Arc::new(png.to_vec()), opacity: None, uv };
(vec![square(RED), square(BLUE)], vec![None, Some(texture)])
// The picture's coordinates replace the mesh's own.
let mut blue = square(BLUE);
blue.mesh.uvs = vec![[0.25, 0.25]; 6];
(vec![square(RED), blue], vec![None, Some(texture)])
}
#[test]
@@ -154,16 +189,18 @@ fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() {
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["My_Box.obj", "My_Box.mtl", "My_Box-texture-1.png"]);
assert_eq!(files[2].1, png);
let obj = text(&files, "My_Box.obj");
assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::<Vec<_>>(), ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"]);
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/4/10 11/5/11 12/6/12"));
assert!(obj.contains("f 1//1 2//2 3//3"), "the plain part keeps no texture coordinates");
// The plain part's own coordinates come first, then the textured part's picture's.
let square_vt = ["vt 0 0", "vt 1 0", "vt 1 1", "vt 0 0", "vt 1 1", "vt 0 1"];
assert_eq!(obj.lines().filter(|l| l.starts_with("vt ")).collect::<Vec<_>>(), [square_vt, square_vt].concat());
assert_eq!(obj.lines().rfind(|l| l.starts_with("f ")), Some("f 10/10/10 11/11/11 12/12/12"));
assert!(obj.contains("f 1/1/1 2/2/2 3/3/3"), "the plain part keeps its mesh's texture coordinates");
let mtl = text(&files, "My_Box.mtl");
assert!(mtl.contains("newmtl Material_2\nKd 1 1 1\nd 1\nillum 1\nmap_Kd -clamp on My_Box-texture-1.png\n"), "{mtl}");
assert_eq!(mtl.matches("map_Kd").count(), 1);
// glTF: TEXCOORD_0 down from the top, and the picture embedded as a data URI.
let g: Value = serde_json::from_str(&text(&mesh_files("Box", "gltf", &parts, &pictures).unwrap(), "Box.gltf")).unwrap();
let prims = g["meshes"][0]["primitives"].as_array().unwrap();
assert!(prims[0]["attributes"].get("TEXCOORD_0").is_none());
assert!(prims[0]["attributes"].get("TEXCOORD_0").is_some(), "the plain part keeps its mesh's texture coordinates");
let uv = &g["accessors"][prims[1]["attributes"]["TEXCOORD_0"].as_u64().unwrap() as usize];
assert_eq!((uv["type"].as_str(), uv["count"].as_u64(), uv["componentType"].as_u64()), (Some("VEC2"), Some(6), Some(5126)));
let view = &g["bufferViews"][uv["bufferView"].as_u64().unwrap() as usize];
@@ -182,8 +219,7 @@ fn each_format_carries_a_textured_part_with_its_coordinates_and_picture() {
let files = mesh_files("Box", "usda", &parts, &pictures).unwrap();
assert_eq!(files.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), ["Box.usda", "Box-texture-1.png"]);
let u = text(&files, "Box.usda");
assert_eq!(u.matches("primvars:st").count(), 1);
assert!(u.contains("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]"), "{u}");
assert_eq!(u.matches("texCoord2f[] primvars:st = [(0, 0), (1, 0), (1, 1), (0, 0), (1, 1), (0, 1)]").count(), 2, "{u}");
assert!(u.contains("color3f inputs:diffuseColor.connect = </Box/Materials/Material_2/Texture.outputs:rgb>"), "{u}");
assert!(u.contains("asset inputs:file = @Box-texture-1.png@") && u.contains("uniform token info:id = \"UsdUVTexture\""));
assert!(u.contains("float2 inputs:st.connect = </Box/Materials/Material_2/Coordinates.outputs:result>"));
File diff suppressed because one or more lines are too long
+5 -1
View File
@@ -1148,10 +1148,14 @@ impl SaveJob {
/// Once written: Save and Save As (except to a template) make the file `st`'s own: path,
/// title, format, options, and the snapshot as the saved state (edits made since the job was
/// made keep the document modified; changes that are not edits to save don't,
/// [`DocState::same_content`]).
/// [`DocState::same_content`]). Saved outside a command a script runs, from the document's
/// content as it is now, the document is as the person left it ([`DocState::by_script`]).
pub fn finish(self, st: &mut DocState) {
let retargets = self.plan.retargets();
if let (true, Some(path)) = (retargets, self.plan.path) {
if !crate::file_access::in_script_command() && st.same_content(&self.source) {
st.by_script = None;
}
st.path = Some(path);
st.format = self.plan.format.id;
st.save_options = self.plan.options;
+5
View File
@@ -1154,11 +1154,16 @@ fn drop_own_overprints(n: &mut Node) {
(r.style.overprint_fill, r.style.overprint_stroke) = (false, false);
}
}
// An image keeps the flag after its color is removed, and a later color would overprint.
if n.extras().colorize_overprint {
n.extras_mut().colorize_overprint = false;
}
}
}
fn overprints(n: &Node) -> bool {
n.appearance.items.iter().any(AppearanceItem::overprint)
|| n.extras().colorize_overprint
|| matches!(&n.kind, NodeKind::Text(t) if t.runs.iter().any(|r| r.style.overprint_fill || r.style.overprint_stroke))
}
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -33,7 +33,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Apply Gradient Preset",
[],
None,
"{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient (while the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes, by the active proxy) → {name, ids: the objects painted (none: only the default changed)}",
"{name: a preset's name (gradient.presets.list), stroke?, item?, ids?|id?, defaultsOnly?, target? (as paint.editGradient)} give the gradient behind the active proxy (or the targeted fill or stroke) the preset's type, stops, method, spread and repeats (a freeform preset's: the first three), and a fill its dither, keeping its placement; a solid or no paint becomes the gradient. One undo step, as paint.editGradient (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, by the active proxy) → {name, ids: the objects painted (none: only the default changed)}",
has_doc,
apply
),
+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();
+16 -12
View File
@@ -712,7 +712,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Use Library Item",
[],
None,
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused, also when its art links to the document's own color of a name; a global or spot color its art links to whose name the document gives another color comes in numbered, or as the document's numbered copy of the same color, and the pattern links to it) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}",
"{library?, kind, item: name (graphic: id or name), center?: [x, y] (graphic; default: the first artboard's centre), to?: fill|stroke (colors, gradients, patterns; default: the kind's), defaultsOnly?: bool (colors, gradients, patterns: paint only the defaults, as with paint.setFill's; the journal records it for an item used while the Live Paint Bucket is the active tool), recorded?: the item as it was when used (recorded in the journal so a replay matches)} graphic: place a copy centred on `center`, its resources pasted along, selected, one undo step; colors and gradients: paint the selection (and the defaults) as paint.setFill/paint.setStroke, a gradient fitting each object; a spot color links to the document's spot swatch of its ink's name, added when the document has none of that colour (a name taken by another colour gets a number), one undo step; patterns: add the pattern and its swatch to the document (a name the document gives another pattern gets a number; the same pattern is reused, also when its art links to the document's own color of a name; a global or spot color its art links to whose name the document gives another color comes in numbered, or as the document's numbered copy of the same color, and the pattern links to it) and paint the selection (and the defaults) with it, one undo step; charStyle/paraStyle: add the style to the document (a name taken by different attributes gets a number; a character style's color linked to a swatch that isn't a global or spot swatch of the document keeps the color it shows, unlinked) and apply it to the selected text, one undo step → {kind, ids?, style?}",
has_doc,
use_item
),
@@ -1185,6 +1185,7 @@ fn item_param<'a>(s: &Session, p: &'a Value, cmd: &str) -> Result<(String, Kind,
fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "library.use";
super::switch_or(p, "defaultsOnly", false, C)?;
// A replay (the journal) carries what the item was, so it doesn't depend on the library.
let recorded = p.get("recorded").cloned();
let (kind, data) = match recorded {
@@ -1246,18 +1247,20 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
}
Kind::FillColor | Kind::StrokeColor => {
let stroke = to_stroke(p, kind)?;
let only = super::paint::defaults_only(s, p, C)?;
let color = data.get("color").cloned().ok_or_else(|| bad(C, "no colour"))?;
let set = if stroke { "paint.setStroke" } else { "paint.setFill" };
match str_param(&data, "spot").map(str::trim).filter(|n| !n.is_empty()) {
Some(ink) => use_spot(s, set, ink, &color, &data)?,
Some(ink) => use_spot(s, set, ink, &color, &data, only)?,
None => {
s.execute(set, &json!({ "color": color }))?;
s.execute(set, &super::paint::with_defaults_only(json!({ "color": color }), only))?;
}
}
Ok(json!({ "kind": if stroke { "strokeColor" } else { "fillColor" } }))
}
Kind::FillGradient | Kind::StrokeGradient => {
let stroke = to_stroke(p, kind)?;
let only = super::paint::defaults_only(s, p, C)?;
let damaged = || bad(C, "the library item is damaged");
let mut g: GradientPaint = data.get("gradient").cloned().and_then(|v| serde_json::from_value(v).ok()).ok_or_else(damaged)?;
if !clean_gradient(&mut g) {
@@ -1267,12 +1270,13 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
for st in &mut g.gradient.stops {
st.color = super::paint::new_color(s, &json!({}), st.color);
}
super::paint::apply_paint(s, &json!({}), Paint::Gradient(Box::new(g)), !stroke)?;
super::paint::apply_paint(s, &super::paint::with_defaults_only(json!({}), only), Paint::Gradient(Box::new(g)), !stroke)?;
Ok(json!({ "kind": if stroke { "strokeGradient" } else { "fillGradient" } }))
}
Kind::FillPattern | Kind::StrokePattern => {
let stroke = to_stroke(p, kind)?;
let pattern = use_pattern(s, &data, stroke)?;
let only = super::paint::defaults_only(s, p, C)?;
let pattern = use_pattern(s, &data, stroke, only)?;
Ok(json!({ "kind": if stroke { "strokePattern" } else { "fillPattern" }, "pattern": pattern }))
}
Kind::CharStyle | Kind::ParaStyle => {
@@ -1303,8 +1307,8 @@ fn use_item(s: &mut Session, p: &Value) -> Result<Value> {
/// Paint with library spot colour `ink` (`color` its full-strength colour, `data`'s `tint` its
/// tint) through `set` (paint.setFill or paint.setStroke), linked to the document's spot swatch of
/// that name: the one it has when it is the same colour, else a new one (a name taken by another
/// colour gets a number), one undo step (#5812).
fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value) -> Result<()> {
/// colour gets a number), one undo step (#5812). With `only`, only the default takes it.
fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value, only: bool) -> Result<()> {
const C: &str = "library.use";
let c = color_value(color).ok_or_else(|| bad(C, "the library item is damaged"))?;
let tint = data.get("tint").and_then(Value::as_f64).filter(|t| t.is_finite()).map_or(1.0, |t| t.clamp(0.0, 1.0));
@@ -1321,7 +1325,7 @@ fn use_spot(s: &mut Session, set: &str, ink: &str, color: &Value, data: &Value)
if tint < 1.0 {
p["tint"] = json!(tint * 100.0);
}
s.execute(set, &p)?;
s.execute(set, &super::paint::with_defaults_only(p, only))?;
Ok(())
})
}
@@ -1339,8 +1343,8 @@ fn to_stroke(p: &Value, kind: Kind) -> Result<bool> {
/// Add library pattern `data` (`{pattern, data}`) to the document, with its swatch and the
/// resources its art uses (the same pattern there already is reused; a name the document gives
/// another one gets a number), and paint the selection's fill (`stroke`: stroke) and the default
/// with it, one undo step → the pattern's name in the document.
fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result<String> {
/// with it (with `only`, only the default), one undo step → the pattern's name in the document.
fn use_pattern(s: &mut Session, data: &Value, stroke: bool, only: bool) -> Result<String> {
const C: &str = "library.use";
let damaged = || bad(C, "the library item is damaged");
let bytes = data.get("data").and_then(Value::as_str).and_then(vectorcraft_format::base64_decode).ok_or_else(damaged)?;
@@ -1356,7 +1360,7 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result<String> {
// 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);
@@ -1378,7 +1382,7 @@ fn use_pattern(s: &mut Session, data: &Value, stroke: bool) -> Result<String> {
}
// The pattern itself, not a swatch of its name (a color swatch can share it); `swatch` keeps
// the placement of a pattern the targets already have, as picking its swatch does.
super::paint::apply_paint(s, &json!({ "swatch": target }), paint.clone(), !stroke)
super::paint::apply_paint(s, &super::paint::with_defaults_only(json!({ "swatch": target }), only), paint.clone(), !stroke)
})?;
Ok(target)
}
+29 -1
View File
@@ -328,7 +328,12 @@ impl<'a> LinkBase<'a> {
/// The open document `st`'s. One with no file of its own looks beside the file it was read from.
pub(crate) fn of(st: &'a crate::DocState) -> Self {
let (path, from) = (st.path.as_deref(), st.links_from.as_deref());
Self::of_files(st.path.as_deref(), st.links_from.as_deref())
}
/// An open document's, by its own file `path` and the file it was read from, `from`
/// ([`crate::DocState::links_from`]), as [`Self::of`] gives them.
pub(crate) fn of_files(path: Option<&'a str>, from: Option<&'a str>) -> Self {
Self { doc: path.or(from), relative: from.or(path) }
}
}
@@ -401,6 +406,29 @@ fn locate(link: &LinkInfo, base: LinkBase) -> Option<Found> {
Some(f)
}
/// The files the links of `d` (a document looking from `base`) lead to now: where [`locate`]
/// finds each linked image's and placed document's file from `base` and from no document (as
/// output reads them, [`full_linked_images`]), the plate files of their own of images placed from
/// DCS files, and the image files its data sets name. The commands a script runs may read these
/// for the documents open when the run began, as the person left them
/// ([`crate::file_access::ScriptGate::linked`]).
pub(crate) fn files_linked(d: &Document, base: LinkBase) -> Vec<String> {
let mut out = vec![];
for g in groups(d, None) {
for from in [base, LinkBase::default()] {
let Some(f) = locate(&g.link, from) else { continue };
out.extend(g.plate_files.iter().filter_map(|p| super::place::dcs::plate_file_path(&f.path, &p.name)));
out.push(f.path);
}
}
let values = d.variables.datasets.iter().flat_map(|set| set.values.values());
out.extend(values.filter_map(|v| match v {
DataValue::Image(path) => fileio::document_path(path, base.doc).ok(),
_ => None,
}));
out
}
/// The place `stored` names from the file `from`, as `resolve` ([`fileio::document_path`]) follows
/// it, when it also follows that place from the document's own file `doc`: a network share the
/// document is no longer on is refused.
+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)
}
+67 -8
View File
@@ -13,14 +13,29 @@
//! resets new art when it opens such a document.
use std::borrow::Cow;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, ColorMode, DEFAULT_GRAPHIC_STYLE, Document, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer};
use vectorcraft_tools::PaintDefaults;
/// The object new art takes its appearance from, with that appearance
/// ([`Session::new_art_source`]).
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct NewArtSource {
doc: u64,
id: vectorcraft_doc::NodeId,
appearance: Appearance,
opacity: f32,
blend: BlendMode,
style: Option<String>,
}
use super::gradient::unplaced;
use super::paint::SelectionPaints;
use super::{CommandSpec, Result, Session, always, cmd, switch_or};
use crate::doc_state::{SelectionRecord, objects_only};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -207,16 +222,35 @@ impl Session {
/// After each command: with New Art Has Basic Appearance off, new art takes the appearance of
/// the first selected object (so the last selection's once nothing is selected). Not while the
/// Live Paint Bucket is the active tool: the fill and stroke are the colors it paints with.
/// Live Paint Bucket is the active tool: the fill and stroke are the colors it paints with. Nor
/// after a command that changed only them (`defaultsOnly`), unless a later step of a batch
/// changed what new art would take ([`Session::new_art_source`]).
pub(crate) fn inherit_new_art(&mut self) {
if self.prefs.new_art_basic || self.bucket_paints() {
return;
}
let Some(st) = self.active() else { return };
let Some(n) = st.selection.subjects().first().and_then(|id| st.doc.node(*id)) else { return };
let style = super::style::linked_style(&st.doc, n).map(|g| g.name.clone());
let (ap, opacity, blend) = (super::style::captured(n), n.opacity, n.blend);
self.take_new_art(ap, opacity, blend, style, true);
let Some(source) = self.new_art_source() else { return };
if matches!(&self.defaults_only_ran, Some(Some(ran)) if *ran == source) {
return;
}
let NewArtSource { appearance, opacity, blend, style, .. } = source;
self.take_new_art(appearance, opacity, blend, style, true);
}
/// What [`Session::inherit_new_art`] gives new art: the appearance of the active document's
/// first selected object, if any.
pub(crate) fn new_art_source(&self) -> Option<NewArtSource> {
let st = self.active()?;
let id = *st.selection.subjects().first()?;
let n = st.doc.node(id)?;
Some(NewArtSource {
doc: st.uid,
id,
appearance: super::style::captured(n),
opacity: n.opacity,
blend: n.blend,
style: super::style::linked_style(&st.doc, n).map(|g| g.name.clone()),
})
}
/// After a command changed the selection, with New Art Has Basic Appearance on: the fill and
@@ -236,9 +270,10 @@ impl Session {
if !has_paint {
return;
}
let (fill_mixed, stroke_mixed) = self.proxy_mixed();
let read = self.read_selection_paints();
let (fill_mixed, stroke_mixed) = read.as_ref().map_or_else(|| self.proxy_mixed(), |p| (p.fill_mixed, p.stroke_mixed));
let (fill, stroke) = self.proxy_paints();
let weight_mixed = self.active().is_some_and(|st| st.stroke_mixed().weight);
let weight_mixed = read.as_ref().map_or_else(|| self.active().is_some_and(|st| st.stroke_mixed().weight), |p| p.weight_mixed);
let weight = self.shown_stroke().filter(|st| st.paint != Paint::None && !weight_mixed).map(|st| st.width);
if !fill_mixed {
self.paint.fill = unplaced(&fill);
@@ -250,6 +285,30 @@ impl Session {
self.paint.stroke_width = width;
}
}
/// The [`SelectionPaints`] of the active document's selection, read now and kept in its
/// [`SelectionRecord`] when the record holds none. `None` when anything besides whole objects
/// is selected ([`objects_only`]), with an active Appearance item, when a selected object is in
/// a Live Paint group, and with gradient mesh points picked: the proxies then read the
/// selection with [`Session::proxy_mixed`] and [`crate::DocState::stroke_mixed`]. While the
/// Live Paint Bucket paints, [`Session::load_selection_paints`] returns before reading them.
fn read_selection_paints(&mut self) -> Option<SelectionPaints> {
if self.appearance_item().is_some() {
return None;
}
let st = self.active_mut()?;
if !objects_only(&st.selection) {
return None;
}
if st.selection_paints().is_none() {
let paints = SelectionPaints::of(&st.doc, &st.selection.objects);
let settled = st.selection_record().and_then(|r| r.settled);
st.selection_record =
Some(SelectionRecord { doc: Arc::downgrade(&st.doc), objects: st.selection.objects.clone(), settled, paints: Some(paints) });
}
let paints = st.selection_paints()?.clone();
(!paints.in_live_paint && self.fill_mesh_points().is_empty()).then_some(paints)
}
}
fn set_basic(s: &mut Session, p: &Value) -> Result<Value> {
+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)]);
+14 -1
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Overprint",
[],
None,
"{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too). Without item and ids, the Appearance panel's active item stands in when it is of that kind. A whole Live Paint group (also its contents with `item`) takes the fill flags on its faces and the stroke flags on its edges, and its hidden source paths keep theirs → {changed: objects}",
"{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too; a grayscale or 1-bit image colorized by paint.setFill: without item, the fill flags set whether its color overprints). Without item and ids, the Appearance panel's active item stands in when it is of that kind. A whole Live Paint group (also its contents with `item`) takes the fill flags on its faces and the stroke flags on its edges, and its hidden source paths keep theirs → {changed: objects}",
has_doc,
set_overprint
),
@@ -97,9 +97,18 @@ fn flags(n: &Node, fill: bool, index: Option<usize>) -> Vec<bool> {
if let (None, NodeKind::Text(t)) = (index, &n.kind) {
v.extend(t.runs.iter().map(|r| if fill { r.style.overprint_fill } else { r.style.overprint_stroke }));
}
if fill && index.is_none() && colorized(n) {
v.push(n.extras().colorize_overprint);
}
v
}
/// Is `n` an image colorized with a color, whose fill overprint is its color's
/// ([`vectorcraft_doc::NodeExtras::colorize_overprint`])?
fn colorized(n: &Node) -> bool {
matches!(n.kind, NodeKind::Image(_)) && n.extras().colorize.as_deref().is_some_and(|p| !p.is_none())
}
/// [`flags`], to change.
fn flags_mut(n: &mut Node, fill: bool, index: Option<usize>) -> Vec<&mut bool> {
let mut v: Vec<&mut bool> = n
@@ -178,6 +187,10 @@ pub(super) fn apply_overprint(d: &mut Document, jobs: &[OverprintJob], cmd: &str
changed.insert(*id);
}
}
if *fill && index.is_none() && colorized(n) && n.extras().colorize_overprint != *on {
n.extras_mut().colorize_overprint = *on;
changed.insert(*id);
}
}
}
Ok(())
File diff suppressed because one or more lines are too long
+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
+332 -23
View File
@@ -49,10 +49,11 @@
//! anything is selected: the settings, artboards, layers and swatches, as plain values
//! ([`context`]).
use std::collections::HashMap;
use std::sync::{Arc, Mutex, RwLock};
use serde_json::{Map, Value, json};
use vectorcraft_doc::{Effect, Node};
use vectorcraft_doc::{Document, Effect, Node};
use vectorcraft_plugins::{Budget, Command, Kind, Plugin, effect, export, objects, registry, safe_mode};
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, cmd, has_doc, ids_param, str_param, switch_or};
@@ -124,8 +125,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);
@@ -357,7 +369,8 @@ impl FilterRun {
/// Applies the plug-in's `output` to the active document as one undo step: its objects, and what
/// it keeps with the document from now on. An output its permissions don't allow, and one that
/// changes or leaves out a read-only object it was given, is refused, and the document stays as
/// it was.
/// it was. An output that changes neither the objects nor the kept data records no undo step and
/// leaves the document unmodified; its objects are still selected.
fn finish(self, s: &mut Session, output: &[u8]) -> Result<Value> {
let m = self.plugin.manifest();
let may = m.permissions();
@@ -369,18 +382,43 @@ impl FilterRun {
// A command's undo step is named after the command.
let label = self.label();
let (inputs, parent) = (self.inputs, self.parent);
let ids = s.edit(&label, |d, sel| {
let before = (!may_write).then(|| d.layers.clone());
let ids = objects::apply_output(d, &inputs, out.objects, parent, &admit_effects).map_err(err)?;
if before.is_some_and(|b| b != d.layers) {
return Err(not_granted(&m.name, Permission::DocWrite));
// The output is applied to a copy of the document, as `colorcmds::edit_if_changed` applies
// its pass: only a copy whose objects or kept data differ becomes the document, as one undo
// step. Otherwise the document, its undo and redo steps and its saved state stay as they
// were, and only the selection is set.
if s.script_running() {
return Err(EngineError::Busy);
}
if !s.previewing && super::typing_in_progress(s) {
super::settle_interaction(s)?;
}
let now = s.doc()?.doc.clone();
let mut d = (*now).clone();
let before = (!may_write).then(|| d.layers.clone());
let ids = objects::apply_output(&mut d, &inputs, out.objects, parent, &admit_effects).map_err(err)?;
if before.is_some_and(|b| b != d.layers) {
return Err(not_granted(&m.name, Permission::DocWrite));
}
if let Some(data) = out.document_data {
d.set_plugin_data(&m.id, data);
}
let selectable = |d: &Document| ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable)).collect::<Vec<_>>();
if same_art(&d.layers, &now.layers) && d.plugin_data(&m.id) == now.plugin_data(&m.id) {
let st = s.doc()?;
let mut sel = st.selection.clone();
sel.set(selectable(&st.doc));
if sel != st.selection {
s.select(|_, selection| *selection = sel)?;
}
if let Some(data) = out.document_data {
d.set_plugin_data(&m.id, data);
}
sel.set(ids.iter().copied().filter(|&id| d.node(id).is_some_and(objects::selectable)));
Ok(ids)
})?;
} else {
// The document is shared with `now` no longer, so `s.edit` does not copy it again.
drop(now);
s.edit(&label, |doc, sel| {
*doc = d;
sel.set(selectable(doc));
Ok(())
})?;
}
let mut out = json!({"plugin": m.id, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()});
if let Some(cmd) = &self.command {
out["command"] = json!(cmd.id);
@@ -389,6 +427,11 @@ impl FilterRun {
}
}
/// Whether layer lists `a` and `b` hold the same art: a layer that is shared is not compared again.
fn same_art(a: &[Arc<Node>], b: &[Arc<Node>]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| Arc::ptr_eq(x, y) || x == y)
}
/// The error of a filter `name` whose output needs `permission`, which it wasn't granted.
fn not_granted(name: &str, permission: Permission) -> EngineError {
let (name, p) = (permissions::display_text(name, permissions::MAX_SHOWN_NAME), permission.name());
@@ -493,15 +536,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();
@@ -510,15 +816,18 @@ fn spec_of(p: &Plugin, c: &Command) -> &'static CommandSpec {
fields.push_str(own);
}
let params = format!(
"{{{fields}}} run “{label}”, a command of plug-in {}, on the selected paths and compound paths as plugin.run runs a filter, with _context.command {:?}: one undo step → {{plugin, command, ids}}",
"{{{fields}}} run “{label}”, a command of plug-in {}, on the selected paths and compound paths as plugin.run runs a filter, with _context.command {:?}: one undo step, none when the run changes nothing → {{plugin, command, ids}}",
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),
@@ -1297,7 +1606,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), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), 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, 2 or 3), 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), context?: [\"settings\"|\"artboards\"|\"layers\"|\"swatches\"] (the parts of the active document a filter's runs and its or a live effect's commands are given in _context.document, with or without a selection, see docs/plugins.md), 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, 2 or 3), 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
),
@@ -1315,7 +1624,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Run Plug-in",
[],
None,
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}",
"{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step (an output that changes no object and no kept data records none and leaves the document unmodified); the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}",
has_doc,
run
),
@@ -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),
File diff suppressed because one or more lines are too long
+30 -6
View File
@@ -874,6 +874,11 @@ struct Meta {
/// images were kept apart: the document entry holds them).
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
images: BTreeMap<String, ImageRef>,
/// A command a script ran opened or changed the document since the person last saved it
/// ([`crate::DocState::by_script`]): the commands scripts run treat the restored document as
/// one a script opened.
#[serde(skip_serializing_if = "std::ops::Not::not")]
by_script: bool,
}
/// One of a copy's images: its entry in the copy's area.
@@ -1033,10 +1038,13 @@ impl RecoveryJob {
let meta_name = format!("{}{META_EXT}", self.file);
// The details name the images, so a crash between writing the document and its details
// would pair the new document with the old copy's images: when the new document has
// images the old details don't name, they name both until the new document is in.
let old = read_meta(store, &self.file).images;
if meta.images.iter().any(|(k, r)| old.get(k).is_none_or(|o| o.blob != r.blob)) {
// images the old details don't name, they name both until the new document is in. Likewise
// when a script's command changed the document since the old details: they say so first.
let old_meta = read_meta(store, &self.file);
let old = old_meta.images;
if (meta.by_script && !old_meta.by_script) || meta.images.iter().any(|(k, r)| old.get(k).is_none_or(|o| o.blob != r.blob)) {
let mut both = meta.clone();
both.by_script |= old_meta.by_script;
for (k, r) in old {
both.images.entry(k).or_insert(r);
}
@@ -1195,6 +1203,7 @@ pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<Reco
links_from: st.links_from.clone().filter(|_| st.path.is_none()),
// Filled in as the copy is written.
images: BTreeMap::new(),
by_script: st.by_script.is_some(),
};
out.push(RecoveryJob { uid: st.uid, file, title, meta, save, store: store.clone() });
}
@@ -1456,8 +1465,18 @@ fn targets(s: &mut Session, store: &dyn RecoveryStore, cmd: &str, p: &Value) ->
/// (for Save As) and format. The copy moves into this session's area (another crash keeps it).
fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> Result<Value> {
let bytes = store.read(&format!("{file}{DOC_EXT}")).map_err(EngineError::Other)?;
let meta_bytes = store.read(&format!("{file}{META_EXT}")).unwrap_or_default();
let meta: Meta = serde_json::from_slice(&meta_bytes).unwrap_or_default();
// A details entry that is missing or can't be parsed does not say whether a script's command
// changed the document: the copy restores as one a script opened, and the details written for
// it say so.
let read = store.read(&format!("{file}{META_EXT}")).ok().and_then(|b| serde_json::from_slice::<Meta>(&b).ok().map(|m| (m, b)));
let (meta, meta_bytes) = match read {
Some(both) => both,
None => {
let meta = Meta { by_script: true, ..Meta::default() };
let bytes = serde_json::to_vec_pretty(&meta).map_err(|e| EngineError::Other(e.to_string()))?;
(meta, bytes)
}
};
let (mut doc, _, mut warnings) = fileio::decode_native_file(&bytes).map_err(|e| EngineError::Other(format!("recovery copy `{file}`: {e}")))?;
// A frame whose first paragraph continues from the frame before draws it without the
// paragraph's first-line indent and list marker.
@@ -1497,8 +1516,10 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
for (blob, data) in &blobs {
store.write(&format!("{area}/{blob}"), data).map_err(EngineError::Other)?;
}
store.write(&format!("{mine}{DOC_EXT}"), &bytes).map_err(EngineError::Other)?;
// The details go first: a crash in between leaves no copy without them (a copy is its
// document entry), and the copy in the old area stays whole.
store.write(&format!("{mine}{META_EXT}"), &meta_bytes).map_err(EngineError::Other)?;
store.write(&format!("{mine}{DOC_EXT}"), &bytes).map_err(EngineError::Other)?;
}
// The copy's images in its old area go with the area, once no copy is left there.
store.remove(&format!("{file}{DOC_EXT}")).map_err(EngineError::Other)?;
@@ -1519,6 +1540,9 @@ fn restore_one(s: &mut Session, store: &Arc<dyn RecoveryStore>, file: &str) -> R
st.imported_from = meta.imported_from.clone();
st.import_losses = meta.import_losses.clone();
st.format = SAVE_FORMATS.iter().copied().find(|f| *f == meta.format).unwrap_or("vectorcraft");
if meta.by_script {
st.by_script = Some(crate::doc_state::ByScript::Opened);
}
if let Some(pdf) = meta.native_pdf_compatible {
st.save_options.insert("pdfCompatible".into(), json!(pdf));
}
+96 -8
View File
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Retype",
["Type"],
None,
"{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05",
"{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, a combining mark that would start a line (a shape whose first 16 matched glyphs include another character's starts it as that character), glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05",
has_selected_path,
retype
)]
@@ -777,10 +777,24 @@ fn set_apart(t: &TextObject, g: &vectorcraft_text::PositionedGlyph, m: &GlyphMat
/// The most glyphs [`verified`] measures the tracking of after a split.
const MEASURE_SPAN: usize = 32;
/// One part of shape `id`, by the glyph it matched (face, glyph, origin, turn and scale): the parts
/// of a compound path share its id.
type PartKey = (NodeId, u32, u32, [u64; 4]);
fn part_key(id: NodeId, m: &GlyphMatch) -> PartKey {
(id, m.face.id(), m.gid, [m.origin.x.to_bits(), m.origin.y.to_bits(), m.angle.to_bits(), m.scale.to_bits()])
}
/// `lines` checked against their own layout: a line splits where its type stops drawing the
/// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`).
/// The glyphs laid out are bounded by a multiple of the number of glyphs.
fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>) -> Vec<Line> {
/// `spacing` holds, for a part of a shape read as a combining mark, the other character that part
/// is. The glyphs laid out are bounded by a multiple of the number of glyphs.
fn verified(
lines: Vec<Line>,
system_layout: bool,
spacing: &std::collections::HashMap<PartKey, GlyphMatch>,
unmatched: &mut Vec<NodeId>,
) -> Vec<Line> {
// Glyphs laid out in all, at most: past it, the glyphs left unchecked stay outlines.
let mut budget = lines.iter().map(|l| l.pieces.len()).sum::<usize>().saturating_mul(16).saturating_add(256);
// Measuring the tracking of the glyphs after a split has a budget of its own, so it cannot
@@ -796,6 +810,44 @@ fn verified(lines: Vec<Line>, system_layout: bool, unmatched: &mut Vec<NodeId>)
let mut out = vec![];
while let Some(l) = todo.pop_front() {
let n = l.pieces.len();
// A combining mark goes with the character before it: a mark that a split left first on
// a line becomes the other character its shape is (`spacing`), alone on a line, or else
// stays an outline, and the line goes on from the glyph after it ([`new_line`] starts no
// line with one).
if l.matches.first().is_some_and(|m| vectorcraft_text::retype::is_combining_mark(m.ch)) {
let first = l.pieces.first().copied();
let alone = first.zip(l.matches.first()).and_then(|(id, mark)| spacing.get(&part_key(id, mark)).map(|m| reposed(&l, id, m)));
if alone.is_none() {
unmatched.extend(first);
}
if n > 1 {
// The tracking was measured with the mark's gap in it: the rest is measured again
// without it, from the same budgets as the rest after a split. A rest that starts
// with a mark too is not measured here: its own pass leaves that mark out and
// measures the glyphs after it.
let measurable = n > 3 && remeasured >= (n - 1).saturating_mul(6) && track_budget >= (n - 1).saturating_mul(6);
let rest = if l.matches.get(1).is_some_and(|m| vectorcraft_text::retype::is_combining_mark(m.ch)) {
l.part(1, n)
} else if measurable {
remeasured = remeasured.saturating_sub((n - 1).saturating_mul(6));
track_budget = track_budget.saturating_sub(n - 1);
l.respaced(1, n, 0.0).map(|r| r.tracked(system_layout, &mut track_budget))
} else if l.tracking == 0.0 {
l.part(1, n)
} else {
l.respaced(1, n, 0.0)
};
match rest {
Some(rest) => todo.push_front(rest),
None => unmatched.extend(l.pieces.get(1..).unwrap_or_default().iter().copied()),
}
}
// Checked before the rest, so the lines keep the outlines' order.
if let Some(alone) = alone {
todo.push_front(alone);
}
continue;
}
// The line's type is laid out over a window from its start that doubles while the type
// draws the window's glyphs as the outlines do, so finding where it stops costs about
// twice the glyphs before that point, not the whole rest of the line each time.
@@ -1244,6 +1296,8 @@ fn join(l: &mut Line, pc: &Piece, cands: &[GlyphMatch]) -> bool {
.iter()
.flat_map(|c| c.poses())
.filter(|fp| !(fp.gid == current.gid && fp.face.id() == current.face.id() && fp.angle == current.angle))
// No line starts with a combining mark (see [`new_line`]).
.filter(|fp| !vectorcraft_text::retype::is_combining_mark(fp.ch))
.collect();
for fp in others {
let mut turned = reposed(l, id, &fp);
@@ -1278,10 +1332,11 @@ fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line {
}
}
/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` (none: `None`),
/// with near matches taken at tolerance `slack`.
/// A new line of shape `pc` alone, as the first of its candidate glyphs `cands` that is not a
/// combining mark (none: `None`), with near matches taken at tolerance `slack`. No line starts
/// with a mark: a mark combines with the character before it.
fn new_line(pc: &Piece, cands: &[GlyphMatch], slack: f64) -> Option<Line> {
let m = cands.first()?;
let m = cands.iter().find(|m| !vectorcraft_text::retype::is_combining_mark(m.ch))?;
let dir = Vec2::new(m.angle.cos(), m.angle.sin());
Some(Line {
pieces: vec![pc.id],
@@ -1755,6 +1810,7 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
let mut unmatched = vec![];
// An unmatched shape between glyphs ends the line: the type after it is painted after it.
let mut open = false;
let mut spacing: std::collections::HashMap<PartKey, GlyphMatch> = std::collections::HashMap::new();
// How many glyphs each shape is: a shape of several becomes type only when all of them do.
let mut glyphs_of: std::collections::HashMap<NodeId, usize> = std::collections::HashMap::new();
for (pc, parts) in pieces.iter().zip(&found) {
@@ -1775,8 +1831,40 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
Some(l) if open => join(l, pc, &cands),
_ => false,
};
// A part that joined a line, perhaps as a mark, that is also another character, in
// that face or else in the face most shapes fit of those it is a character in: the
// character, should a split leave the part first on a line ([`verified`]). Kept by
// the glyph the part joined as, since the parts of a compound path share its id.
let is_mark = |m: &GlyphMatch| vectorcraft_text::retype::is_combining_mark(m.ch);
if joined
&& cands.iter().any(is_mark)
&& let Some(m) = cands
.iter()
.find(|m| !is_mark(m))
.or_else(|| ms.iter().enumerate().filter(|(_, m)| !is_mark(m)).max_by(ranked).map(|(_, m)| m))
&& let Some(at) = lines.last().and_then(|l| l.matches.last())
{
spacing.insert(part_key(pc.id, at), m.clone());
}
if !joined {
lines.extend(new_line(pc, &cands, tolerance));
// A part that is only marks in that face may be another character in a face
// fewer shapes fit: it starts its line in the one of those most shapes fit.
let started = new_line(pc, &cands, tolerance).or_else(|| {
let face = ms.iter().enumerate().filter(|(_, m)| !is_mark(m)).max_by(ranked).map(|(_, m)| m.face.id());
let cands: Vec<GlyphMatch> = ms.iter().filter(|m| Some(m.face.id()) == face).cloned().collect();
new_line(pc, &cands, tolerance)
});
match started {
Some(l) => lines.push(l),
// Only combining marks: no line starts with one, so the shape stays an
// outline (a shape of several glyphs then is not whole type, see
// `partial_lines`) and the glyph after it starts the next line.
None => {
unmatched.push(pc.id);
open = false;
continue;
}
}
}
open = true;
}
@@ -1795,7 +1883,7 @@ fn retype(s: &mut Session, p: &Value) -> Result<Value> {
lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(393))).fold(256usize, usize::saturating_add);
let mut lines: Vec<Line> = lines.into_iter().map(|l| l.tracked(system_layout, &mut budget)).collect();
share_tracking(&mut lines, system_layout);
let mut lines = verified(lines, system_layout, &mut unmatched);
let mut lines = verified(lines, system_layout, &spacing, &mut unmatched);
if pieces.len() > 1 || glyphs_of.values().any(|n| *n > 1) {
lines.retain(|l| {
let lone = matches!(l.pieces.as_slice(), [id] if lone_pieces.contains(id));
+17 -7
View File
@@ -26,7 +26,7 @@ pub(in crate::cmd) fn specs() -> Vec<CommandSpec> {
"Find Matching Fonts",
[],
None,
"{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only); of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error",
"{count?: 1..96 (default 10)} the fonts whose glyphs match the selected outlined text, as the Retype panel lists them: each selected shape (paths and compound paths, inside groups too) is compared with the glyphs of up to 96 loaded fonts, those of the document's live type first, by type.retype's matching (exact matches only), a font whose glyphs match the shapes only as combining marks not listed; of two versions of a font loaded at once, only the version its family and style name gives is compared, the one choosing the font sets; the fonts rank by how many shapes each matches, then by the mean distance left after fitting, then by family and style name; the document does not change → {fonts: [{family, style, matched (shapes it matches)}] (the first count), shapes (shapes compared), more (more fonts match than count), truncated (shapes past the limits were left out)}; a count that is not a whole number from 1 to 96 is an error",
has_selected_path,
retype_fonts
)]
@@ -44,6 +44,8 @@ struct Ranked {
matched: usize,
/// The sum of those matches' leftover distances.
residual: f64,
/// Whether some shape matched a glyph of it that is not a combining mark.
character: bool,
}
impl Ranked {
@@ -101,23 +103,31 @@ fn retype_fonts_in(s: &mut Session, p: &Value, db: &FontDb) -> Result<Value> {
for pc in &pieces {
// A shape can fit several glyphs or poses of one font: it counts once for the font, at its
// closest fit.
let mut best: Vec<(Arc<vectorcraft_text::FontFace>, f64)> = vec![];
let mut best: Vec<(Arc<vectorcraft_text::FontFace>, f64, bool)> = vec![];
for m in index.all_matches(&pc.path) {
match best.iter_mut().find(|(f, _)| f.id() == m.face.id()) {
Some(b) => b.1 = b.1.min(m.residual),
None => best.push((m.face, m.residual)),
let character = !vectorcraft_text::retype::is_combining_mark(m.ch);
match best.iter_mut().find(|(f, _, _)| f.id() == m.face.id()) {
Some(b) => {
b.1 = b.1.min(m.residual);
b.2 |= character;
}
None => best.push((m.face, m.residual, character)),
}
}
for (face, residual) in best {
for (face, residual, character) in best {
match ranked.iter_mut().find(|r| r.face.id() == face.id()) {
Some(r) => {
r.matched += 1;
r.residual += residual;
r.character |= character;
}
None => ranked.push(Ranked { face, matched: 1, residual }),
None => ranked.push(Ranked { face, matched: 1, residual, character }),
}
}
}
// A font whose glyphs match the shapes only as combining marks would retype none of them, as
// type.retype starts no line with a mark: it is not listed.
ranked.retain(|r| r.character);
ranked.sort_by(|a, b| {
b.matched
.cmp(&a.matched)

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