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

This commit is contained in:
dotCooCoo committed 2026-11-24 22:49:15 -08:00
commit 3ca2cf7d34
465 files changed
+27095 -2709

No files matched your search

+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() {
+273 -17
View File
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Document Info",
["Window", "Document Info"],
None,
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freeform, when it is named by its kind, else null; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone. brushNames, brushes, spotObjects, patternObjects and gradientObjects leave out hidden objects, objects at an opacity of 0 and the objects inside a hidden group or layer or one at an opacity of 0 (with selectionOnly too), their characters' paints and colorized images included; objects still counts them as paths, groups and the other kinds",
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document: {…, units (English), unitId: the units' Preferences › Units id (points, millimeters, feetInches, …), rasterEffectsPpi, transparency: {gridSize: small|medium|large, gridColors: [#rrggbb, #rrggbb], gridColorsName (a preset's name or Custom), simulatePaper, flattenerPreset} (File › Document Setup's transparency settings, which the document category lists), selectedArtboards: [{index, name, width, height, x, y}] (while the Artboard tool is the current tool, the artboards it has selected, in the document's units, x and y those of the top-left corner from the ruler origin of its active artboard, which the document category lists after the artboards; else empty)}, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts (the type in opacity masks and in the art of symbols and patterns included; with selectionOnly: the selected type's), fontUses: [{font, type: truetype|opentype|unknown, uses}] (each font of fonts, in order: truetype or opentype by the outlines (glyf, or CFF or CFF2) of the face its type is drawn in, unknown for a font not installed in the family and style it names; uses: the text objects set in it, each once however many of its runs use the font, the type in a mask or in a symbol's or pattern's art once however many objects show it; the fonts category's rows give them as `TrueType; 2 uses`), fontDetails: [{font, match: exact|style|missingWithFallback|missing, family, style, file, embedding: allowed|editing|previewPrint|forbidden|null}] (each font of fonts, in order: how it was found, the face shown (null when none), that face's file name (null for a built-in face) and what its license allows), images, imageObjects: [{name, width, height, linked, file, format, effectivePpi, memoryBytes, storedBytes}] (the image objects in the order Linked Images and Embedded Images list them; file: what a linked image's row shows, null for an embedded one; format: a linked image's file format by its extension, else the format of the pixels the document holds, null when unknown; effectivePpi: [x, y] pixels per inch at the size it is placed at, a distorted image measured at its middle, null when it has no area; memoryBytes: for an embedded image width × height × 4, the bytes of the 8-bit RGBA pixels it is drawn from, else null; storedBytes: for an embedded image the bytes of the encoded image the document holds, else null; a Linked Images row gives the format, the size, the resolution and the file (`PNG; 1200 × 800 px; 150 ppi — /art/photo.png`), an Embedded Images row the format, the size and the memory (`PNG; 1200 × 800 px; estimated memory 3.7 MiB`)), swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the brushes the art's drawn strokes use, each once; with selectionOnly: those the selected objects' strokes use), brushes: [{name, type: calligraphic|scatter|art|pattern|bristle|null}] (those brushes with their types; null: not in the Brushes panel), panelBrushNames (the Brushes panel's brushes), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), spotObjects: [{id, name, spotColors}] (the objects filled or stroked with a spot color swatch, as a solid color or in the stops of a gradient that color a part of it above opacity 0 (a stop at opacity 0 counts only where it mixes with a stop above opacity 0 over a stretch of some width), at a tint above 0, and grayscale images colorized with one, each once, by the rules patternObjects follows, with the spot colors they use; Registration and process colors are not spot colors; objects.spots counts them), spotColorNames and spotColors (the spot colors those objects use), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, fills and strokes at an opacity of 0, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients, kinds}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else its kind's name, such as Linear gradient; kinds gives each one's kind, linear|radial|conic|diamond|freef Line truncated
has_doc,
info
),
@@ -183,8 +183,126 @@ fn count_fonts(fonts: &mut BTreeMap<super::fonts::UsedFont, usize>, t: &vectorcr
}
}
/// An image object as Document Info lists it: (name, width, height, linked file).
type ImageRow = (String, u32, u32, Option<String>);
/// An image object as Linked Images or Embedded Images lists it.
struct ImageRow {
name: String,
width: u32,
height: u32,
/// What a linked image's row names: its file's path, or the file's name alone when the request
/// may not read it. `None` for an embedded image.
file: Option<String>,
/// The image's format ([`image_format`]); `None` when it is not known.
format: Option<&'static str>,
/// The pixels per inch across and down at the size the image is placed at; `None` when its
/// transform flattens it.
ppi: Option<[f64; 2]>,
/// For an embedded image, the bytes its pixels take when drawn (8-bit RGBA: width × height × 4).
memory: Option<u64>,
/// For an embedded image, the bytes of the encoded image the document holds.
stored: Option<u64>,
}
impl ImageRow {
/// Image object `n` (image `im`) of `d`, `file` the row value of its link.
fn of(d: &Document, n: &Node, im: &vectorcraft_doc::ImageObject, file: Option<String>) -> Self {
let name = im.link.as_ref().map_or_else(|| n.display_name(), |l| l.name().to_string());
// A distorted image is measured at its middle, as `image.info` measures it.
let xf = vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf);
let ppi = super::place::effective_ppi(xf);
// An image with no pixels across or down has no area, and so does one whose transform lays
// both pixel axes on one line. The determinant is compared with the product of the two
// axes' lengths, at any scale.
let [xx, xy, yx, yy, ..] = xf.as_coeffs();
let has_area = im.width > 0 && im.height > 0 && xf.determinant().abs() > 1e-9 * xx.hypot(xy) * yx.hypot(yy);
let embedded = im.link.is_none();
let memory = || u64::from(im.width).checked_mul(u64::from(im.height))?.checked_mul(4);
Self {
name,
width: im.width,
height: im.height,
file,
format: image_format(d, im),
ppi: (has_area && ppi.iter().all(|v| *v > 0.0 && v.is_finite())).then_some(ppi),
memory: if embedded { memory() } else { None },
stored: if embedded { d.images.get(&im.key).map(|b| b.bytes.len() as u64) } else { None },
}
}
/// The row's value: the format, the size in pixels, and for a linked image its resolution and
/// file, for an embedded one the memory its pixels take.
fn value(&self) -> String {
let format = self.format.unwrap_or("Unknown format");
let size = format!("{} × {} px", self.width, self.height);
match &self.file {
Some(file) => {
let ppi = match self.ppi {
Some([x, y]) if ppi_number(x) == ppi_number(y) => format!("{} ppi", ppi_number(x)),
Some([x, y]) => format!("{} × {} ppi", ppi_number(x), ppi_number(y)),
None => "resolution unavailable".into(),
};
format!("{format}; {size}; {ppi} — {file}")
}
None => {
let memory = self.memory.map_or_else(|| "memory unavailable".to_string(), |b| format!("estimated memory {}", byte_size(b)));
format!("{format}; {size}; {memory}")
}
}
}
/// The row's `imageObjects` entry.
fn entry(&self) -> Value {
json!({
"name": self.name,
"width": self.width,
"height": self.height,
"linked": self.file.is_some(),
"file": self.file,
"format": self.format,
"effectivePpi": self.ppi,
"memoryBytes": self.memory,
"storedBytes": self.stored,
})
}
}
/// The format of image `im` of `d`, as the Links panel names it: for a linked image its file's, by
/// its extension (DCS for a separated one), else the type of the pixels the document holds for it;
/// `None` when neither names a known format.
fn image_format(d: &Document, im: &vectorcraft_doc::ImageObject) -> Option<&'static str> {
use super::fileio;
if im.link.is_some() && d.images.get(&im.key).is_some_and(vectorcraft_doc::ImageBlob::is_separated) {
return Some("DCS");
}
im.link
.as_ref()
.and_then(|l| fileio::format_for_name(l.name()).or_else(|| fileio::readable_format_for_name(l.name())))
.or_else(|| d.images.get(&im.key).and_then(|b| fileio::FORMATS.iter().find(|f| f.raster && f.mime == b.mime)))
.map(|f| f.label)
}
/// A resolution as Document Info shows it: rounded to a tenth (below 1, to a hundredth), without a
/// trailing `.0`.
pub fn ppi_number(ppi: f64) -> String {
let k = if ppi.abs() < 1.0 { 100.0 } else { 10.0 };
format!("{}", (ppi * k).round() / k)
}
/// A number of bytes as Document Info shows it: in B below 1 KiB, else in KiB, MiB or GiB rounded
/// to a tenth.
pub fn byte_size(bytes: u64) -> String {
const UNITS: [&str; 3] = ["KiB", "MiB", "GiB"];
if bytes < 1024 {
return format!("{bytes} B");
}
let mut v = bytes as f64 / 1024.0;
let mut unit = 0;
// 1023.96 KiB is shown as 1 MiB rather than as 1024 KiB.
while v >= 1023.95 && unit + 1 < UNITS.len() {
v /= 1024.0;
unit += 1;
}
format!("{} {}", (v * 10.0).round() / 10.0, UNITS[unit])
}
/// A Repeat object as Document Info lists it: its `repeatObjects` entry, and its row, which gives
/// its name and then its kind with the number of instances it draws (for a grid, its rows and
@@ -337,11 +455,9 @@ fn sections(
"symbols" => names("symbols"),
"fonts" => fonts.to_vec(),
"fontDetails" => font_details.to_vec(),
"linkedImages" => {
images.iter().filter_map(|(name, w, h, link)| Some((name.clone(), format!("{w} × {h} px — {}", link.as_ref()?)))).collect()
}
"linkedImages" => images.iter().filter(|i| i.file.is_some()).map(|i| (i.name.clone(), i.value())).collect(),
"repeats" => repeats.to_vec(),
_ => images.iter().filter(|i| i.3.is_none()).map(|(name, w, h, _)| (name.clone(), format!("{w} × {h} px"))).collect(),
_ => images.iter().filter(|i| i.file.is_none()).map(|i| (i.name.clone(), i.value())).collect(),
};
Section { id, title, rows }
})
@@ -753,8 +869,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
im.key.clone(),
json!({ "width": im.width, "height": im.height, "linked": im.link.is_some(), "link": link.and_then(|(l, ok)| ok.then_some(&l.path)) }),
);
let name = im.link.as_ref().map_or_else(|| n.display_name(), |l| l.name().to_string());
image_rows.push((name, im.width, im.height, link.map(|(l, ok)| if ok { l.path.clone() } else { l.name().to_string() })));
let file = link.map(|(l, ok)| if ok { l.path.clone() } else { l.name().to_string() });
image_rows.push(ImageRow::of(d, n, im, file));
Some("images")
}
NodeKind::SymbolInstance { symbol, .. } => {
@@ -835,13 +951,8 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
let font_names: Vec<String> = fonts.keys().map(super::fonts::font_label).collect();
let (font_uses, font_use_rows): (Vec<Value>, Vec<(String, String)>) = fonts.iter().map(|(f, n)| font_use(f, *n)).unzip();
let (font_entries, font_rows): (Vec<Value>, Vec<(String, String)>) = fonts.keys().map(font_detail).unzip();
// The image objects in walk order, as Linked Images and Embedded Images list them: `file` is a
// linked image's row value (its path, or its file name alone when the request may not read it),
// and null for an embedded one.
let image_objects: Vec<Value> = image_rows
.iter()
.map(|(name, w, h, file)| json!({ "name": name, "width": w, "height": h, "linked": file.is_some(), "file": file }))
.collect();
// The image objects in walk order, as Linked Images and Embedded Images list them.
let image_objects: Vec<Value> = image_rows.iter().map(ImageRow::entry).collect();
// Each brush the art uses with its type, found by name in the Brushes panel as the renderer finds it (the first of two
// brushes with one name); a brush the panel does not hold draws as a plain stroke and has no type. A row names the type
// as the New Brush dialog does (`Art Brush`), and the panel translates these values when it shows them.
@@ -2246,11 +2357,156 @@ mod tests {
assert_eq!(objects.len(), 2, "{objects:?}");
for (o, r) in objects.iter().zip(&embedded) {
assert_eq!((o["linked"].clone(), o["file"].clone(), o["name"].clone()), (json!(false), Value::Null, r[0].clone()), "{o}");
assert_eq!(r[1], format!("{} × {} px", o["width"], o["height"]));
let memory = byte_size(o["memoryBytes"].as_u64().unwrap());
assert_eq!(r[1], format!("{}; {} × {} px; estimated memory {memory}", o["format"].as_str().unwrap(), o["width"], o["height"]));
}
assert!(section("linkedImages").is_empty());
}
/// An image object to place: (key, MIME type, linked path, width, height, transform).
type Placed<'a> = (&'a str, &'a str, Option<&'a str>, u32, u32, Affine);
/// Image objects `images` placed in a new document, with a blob of `100 + n` bytes of type
/// `mime` for each new key; their ids in order.
fn images_in(s: &mut Session, images: &[Placed]) -> Vec<NodeId> {
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.edit("Place", |d, _| {
let mut ids = vec![];
for (n, (key, mime, link, width, height, xf)) in images.iter().enumerate() {
if !d.images.contains_key(*key) {
d.images.insert((*key).into(), vectorcraft_doc::ImageBlob::new(*mime, vec![0; 100 + n]));
}
let id = d.alloc_id();
let im = vectorcraft_doc::ImageObject {
key: (*key).into(),
width: *width,
height: *height,
xf: *xf,
link: link.map(vectorcraft_doc::LinkInfo::new),
placement: Default::default(),
pixels: None,
};
d.insert(d.default_layer(), usize::MAX, Node::new(id, NodeKind::Image(Box::new(im))))?;
ids.push(id);
}
Ok(ids)
})
.unwrap()
}
/// Linked Images gives each linked image's format, size in pixels, resolution at the size it is
/// placed at and file, and Embedded Images each embedded image's format, size and the memory
/// its pixels take; `imageObjects` gives the same facts with the bytes the document holds for an
/// embedded image, the text report writes the same rows, and Selection Only lists the selected
/// images alone.
#[test]
fn image_rows_give_format_resolution_and_memory() {
let mut s = Session::new();
let half = Affine::scale(0.5);
let ids = images_in(
&mut s,
&[
("a", "image/png", None, 1200, 800, half),
("b", "image/jpeg", None, 10, 10, half),
("c", "image/x-unheard-of", None, 3, 2, half),
("a", "image/png", Some("/art/photo.png"), 1200, 800, Affine::scale(0.48)),
("a", "image/png", Some("/art/photo.png"), 1200, 800, Affine::scale(0.24)),
("a", "image/png", Some("/art/wide.png"), 1200, 800, Affine::scale_non_uniform(0.5, 1.0)),
("a", "image/png", Some("/art/scan.tif"), 1200, 800, half),
("a", "image/png", Some("/art/flat.png"), 1200, 800, Affine::scale_non_uniform(0.5, 0.0)),
// Both pixel axes on one line: neither has length 0, but the image has no area.
("a", "image/png", Some("/art/line.png"), 1200, 800, Affine::new([0.5, 0.5, 1.0, 1.0, 0.0, 0.0])),
("c", "image/x-unheard-of", Some("/art/odd.qqq"), 3, 2, half),
],
);
let i = s.execute("document.info", &json!({})).unwrap();
let rows = |i: &Value, id: &str| -> Vec<(String, String)> {
let section = i["sections"].as_array().unwrap().iter().find(|s| s["id"] == id).unwrap().clone();
section["rows"].as_array().unwrap().iter().map(|r| (r[0].as_str().unwrap().into(), r[1].as_str().unwrap().into())).collect()
};
let embedded = rows(&i, "embeddedImages");
let values: Vec<&str> = embedded.iter().map(|(_, v)| v.as_str()).collect();
assert_eq!(
values,
[
"PNG; 1200 × 800 px; estimated memory 3.7 MiB",
"JPEG; 10 × 10 px; estimated memory 400 B",
"Unknown format; 3 × 2 px; estimated memory 24 B"
]
);
let linked = rows(&i, "linkedImages");
assert_eq!(
linked,
[
("photo.png", "PNG; 1200 × 800 px; 150 ppi — /art/photo.png"),
("photo.png", "PNG; 1200 × 800 px; 300 ppi — /art/photo.png"),
("wide.png", "PNG; 1200 × 800 px; 144 × 72 ppi — /art/wide.png"),
("scan.tif", "TIFF; 1200 × 800 px; 144 ppi — /art/scan.tif"),
("flat.png", "PNG; 1200 × 800 px; resolution unavailable — /art/flat.png"),
("line.png", "PNG; 1200 × 800 px; resolution unavailable — /art/line.png"),
("odd.qqq", "Unknown format; 3 × 2 px; 144 ppi — /art/odd.qqq"),
]
.map(|(a, b)| (a.to_string(), b.to_string()))
);
let objects = i["imageObjects"].as_array().unwrap();
assert_eq!(objects.len(), 10);
assert_eq!(
(objects[0]["format"].clone(), objects[0]["effectivePpi"].clone(), objects[0]["memoryBytes"].clone(), objects[0]["storedBytes"].clone()),
(json!("PNG"), json!([144.0, 144.0]), json!(1200 * 800 * 4), json!(100))
);
assert_eq!((objects[1]["format"].clone(), objects[1]["storedBytes"].clone()), (json!("JPEG"), json!(101)));
assert_eq!(objects[2]["format"], Value::Null);
// A linked image gives no memory and no stored bytes: the document holds only its preview.
assert_eq!((objects[3]["memoryBytes"].clone(), objects[3]["storedBytes"].clone()), (Value::Null, Value::Null));
let ppi = |o: &Value| -> Vec<f64> { o["effectivePpi"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect() };
assert!(ppi(&objects[3]).iter().all(|v| (v - 150.0).abs() < 1e-9), "{}", objects[3]);
assert_eq!(ppi(&objects[5]), [144.0, 72.0]);
assert_eq!((objects[7]["effectivePpi"].clone(), objects[8]["effectivePpi"].clone()), (Value::Null, Value::Null));
let text = s.execute("document.info", &json!({"format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
assert!(text.contains("\nphoto.png: PNG; 1200 × 800 px; 150 ppi — /art/photo.png\n"), "{text}");
assert!(text.contains(": JPEG; 10 × 10 px; estimated memory 400 B\n"), "{text}");
// Selection Only lists the selected images alone, with the same rows.
s.execute("select.set", &json!({"ids": [ids[1].0, ids[5].0]})).unwrap();
let selected = s.execute("document.info", &json!({"selectionOnly": true})).unwrap();
assert_eq!(rows(&selected, "embeddedImages").iter().map(|(_, v)| v.as_str()).collect::<Vec<_>>(), [values[1]]);
assert_eq!(rows(&selected, "linkedImages"), [linked[2].clone()]);
}
/// An image placed at a very small size still has an area, so its row gives a resolution.
#[test]
fn a_tiny_placement_still_gives_a_resolution() {
let mut s = Session::new();
images_in(&mut s, &[("a", "image/png", Some("/art/huge.png"), 100_000, 100_000, Affine::scale(1e-7))]);
let i = s.execute("document.info", &json!({})).unwrap();
let ppi = i["imageObjects"][0]["effectivePpi"].as_array().map(|v| v.iter().map(|v| v.as_f64().unwrap_or(0.0)).collect::<Vec<_>>());
let ppi = ppi.unwrap_or_default();
assert!(ppi.len() == 2 && ppi.iter().all(|v| (v / 7.2e8 - 1.0).abs() < 1e-9), "{}", i["imageObjects"][0]);
}
/// An image with no pixels across or down has no area, so its row gives no resolution whatever
/// its transform.
#[test]
fn a_zero_pixel_image_has_no_resolution() {
let mut s = Session::new();
let half = Affine::scale(0.5);
images_in(&mut s, &[("a", "image/png", Some("/art/none.png"), 0, 800, half), ("a", "image/png", Some("/art/flat.png"), 1200, 0, half)]);
let i = s.execute("document.info", &json!({})).unwrap();
let objects = i["imageObjects"].as_array().cloned().unwrap_or_default();
assert_eq!(objects.iter().map(|o| o["effectivePpi"].clone()).collect::<Vec<_>>(), [Value::Null, Value::Null], "{objects:?}");
let text = s.execute("document.info", &json!({"format": "text"})).unwrap()["text"].as_str().unwrap_or_default().to_string();
assert!(text.contains("none.png: PNG; 0 × 800 px; resolution unavailable — /art/none.png\n"), "{text}");
assert!(text.contains("flat.png: PNG; 1200 × 0 px; resolution unavailable — /art/flat.png\n"), "{text}");
}
/// A number of bytes reads in B below 1 KiB, else in KiB, MiB or GiB to a tenth, and a
/// resolution to a tenth without a trailing `.0`.
#[test]
fn byte_sizes_and_resolutions_read_to_a_tenth() {
let shown = [0, 1023, 1024, 1536, 1024 * 1024 - 1, 3_840_000, 5 << 30, u64::MAX].map(byte_size);
assert_eq!(shown, ["0 B", "1023 B", "1 KiB", "1.5 KiB", "1 MiB", "3.7 MiB", "5 GiB", "17179869184 GiB"]);
assert_eq!([150.0, 72.0 / 0.48, 205.714, 0.04, 0.001].map(ppi_number), ["150", "150", "205.7", "0.04", "0"]);
}
/// A `gradientObjects` entry's `kinds` gives the kind of each gradient listed by its kind
/// rather than by a swatch, and null for a swatch's name, even one that reads like a kind and
/// one an object's gradient of that kind shares; a type object's characters count as its own.
+1 -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>"));
+1 -1
View File
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export PDF",
[],
None,
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in Line truncated
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning, and so does a count of the visible objects that reach the trim edge (within 0.5 pt) on a side with a bleed but end before the bleed edge; layers that don't print are left out unless includeNonPrinting, and art and boxes are written unchanged). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in Line truncated
has_doc,
export_pdf
),
+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))
}
+1 -1
View File
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Gradient",
["Window", "Gradient"],
None,
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected, the Live Paint Bucket's gradient, or a fill edit of a Live Paint group without faces: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucket is the active tool and no ids, id or i Line truncated
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; diamond runs the stops from the center out to a square with a corner at the end of the vector; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (how the colours between the stops mix: in display RGB, perceptually (OKLab) so the steps look even, or around the hue wheel: hue, saturation and brightness each change evenly from one stop to the next, the hue angle falling with hue-clockwise (red, magenta, blue, cyan, green, yellow) and rising with hue-counterclockwise; two stops whose hues are less than half a color level apart keep that hue; a stop whose RGB numbers are less than half a color level apart is gray and takes the hue of the stop it mixes with, and black that stop's saturation too; these two methods are VectorCraft's own, and SVG and PDF exports draw their gradients as RGB images, CMYK and spot color stops included; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial, conic or diamond, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), spread?: pad|repeat|reflect (linear, radial, conic and diamond: what the gradient paints past the ends of its stops: pad carries the end colors on; repeat and reflect run the stops `repeats` times along the vector (around the circle, for a conic) and on past both ends, reflect mirroring every other run; an error on a freeform gradient), repeats?: 1..100 (a whole number: how many times repeat and reflect run the stops along the vector; VectorCraft's own limit; pad keeps it unused), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial, conic and diamond: the vector turns about the center), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep and is an error for the other kinds; an error when no object is edited, as with nothing selected, the Live Paint Bucket's gradient, or a fill edit of a Live Paint group without faces: the default gradient fits each new object and keeps no aspect), reverse?: bool (the same ramp the other way round: the stops in reverse order, and a hue method turned the other way unless `method` is given too), dither?: bool (fills only: a linear, radial, conic or diamond gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), aligned?: bool (as paint.setFill; without stroke, the kind of the row edited), ids?|id?, defaultsOnly?: bool (as paint.setFill), strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient. Without `item`, a Live Paint group's faces take a fill edit and its edges take a stroke edit. On a path directly in a graph series, the graph also stores the gradient when it is on the topmost visible fill or stroke (docs/mcp.md); on a graph label's row, or on a graph's axis line, tick mark or radar ring, the graph stores that object's topmost visible fill and stroke rows for every label or line of its kind (a line's gradient without its placement), and on its characters their gradient without its placement, fitted to each label. While the Live Paint Bucke Line truncated
has_doc,
edit_gradient
),
+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(())
+454 -114
View File
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fill",
[],
None,
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), only the default changes (the color the bucket paints with) and the selection keeps its paint → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row o Line truncated
has_doc,
|s, p| set_paint(s, p, true)
),
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke",
[],
None,
"{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill)} same as paint.setFill, for the stroke; without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
"{…as paint.setFill, item?: the stroke item to set, aligned?: bool (as paint.setFill), opacity?: 0..100 (the opacity of that stroke item, as paint.setFill's for the fill item)} same as paint.setFill, for the stroke; without `item`, a Live Paint group among the targets (or inside one) takes the stroke on its edges only; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's stroke changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint and weight of the topmost visible stroke when the command wrote that row or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, as paint.setFill",
has_doc,
|s, p| { set_paint(s, p, false) }
),
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Swap Fill and Stroke",
[],
Some("Shift+X"),
"{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ (a freeform gradient counts as differing), or that has no face or no edge, keeps its paint. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change",
"{ids?|id?, defaultsOnly?: bool} swap the fill and stroke of the selection (type too) and of the defaults. A Live Paint group's faces take the stroke its edges share and its edges take the fill its faces share, a gradient fitted to each face or edge; a group whose faces' fills or edges' strokes differ (a freeform gradient counts as differing), or that has no face or no edge, keeps its paint. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given, only the defaults change",
has_doc,
swap
),
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Default Fill and Stroke",
[],
Some("D"),
"{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, in place of their whole appearance and also when the Default Graphic Style is redefined, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters 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 (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), only the defaults change",
"{ids?|id?, defaultsOnly?: bool} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. A Live Paint group's faces get no fill and its edges get a 0.5 pt black stroke, in place of their whole appearance and also when the Default Graphic Style is redefined, and with only Live Paint groups selected (or in ids) the defaults become no fill and a 0.5 pt black stroke (with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command). On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters 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 (exceptions: docs/mcp.md). While the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none), or `defaultsOnly: true` is given, only the defaults change",
has_doc,
default_paint
),
@@ -75,11 +75,12 @@ pub fn specs() -> Vec<CommandSpec> {
"None",
[],
Some("/"),
"{} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does (while the Live Paint Bucket is the active tool, only the default changes) → {objects}",
"{defaultsOnly?: bool} set the active proxy (fill or stroke) to None, as paint.setFill or paint.setStroke with none does (while the Live Paint Bucket is the active tool, or with `defaultsOnly: true`, only the default changes) → {objects}",
has_doc,
|s, _| {
|s, p| {
let f = s.fill_active;
set_paint(s, &json!({"none": true}), f)
let only = switch_or(p, "defaultsOnly", false, "paint.none")?;
set_paint(s, &with_defaults_only(json!({"none": true}), only), f)
}
),
cmd!(
@@ -102,7 +103,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Invert",
[],
None,
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or 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), invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color 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); no undo step when no color changes → {changed}",
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} invert the active proxy's colours of the selection (or ids; groups recolour their contents and, except with target \"contents\", their own fills and strokes; a compound path's member stands for its compound path; a Live Paint group recolors its faces' fills or its edges' strokes) keeping each colour's model, as edit.colors.invert does; the Appearance panel's active fill/stroke item (appearance.setActiveItem) is inverted instead when it is of that kind and no ids are given; with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's solid color changes for this instance only, and a gradient or pattern, or type whose characters differ in color, is refused; with nothing selected, or 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, invert the default. On a path directly in a graph series, the graph also stores the new color of the topmost visible fill or stroke, and on a graph label the new color 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); no undo step when no color changes → {changed}",
has_doc,
|s, p| proxy_recolor(s, p, "paint.invert", "Invert", &super::colorcmds::invert)
),
@@ -111,7 +112,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Complement",
[],
None,
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or 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), the default; no undo step when no color changes → {changed}",
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} replace the active proxy's colours by their complements ((highest + lowest) − each component, over RGB or CMY; grey unchanged) keeping each colour's model; a Live Paint group recolors its faces' fills or its edges' strokes as with paint.invert; honours the Appearance panel's active item and a selected object of a dynamic symbol instance as paint.invert does; with nothing selected, or 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, the default; no undo step when no color changes → {changed}",
has_doc,
|s, p| proxy_recolor(s, p, "paint.complement", "Complement", &|c: Color| c.complement_keep_model())
),
@@ -120,7 +121,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Apply Last Color",
[],
Some(","),
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default (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), to the default only) → {objects} (as paint.setFill)",
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last solid colour used (paint.recent lastColor) to the active proxy of the selection and the default (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, to the default only) → {objects} (as paint.setFill)",
has_doc,
|s, p| {
let paint = Paint::solid(s.last_solid);
@@ -132,7 +133,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Apply Last Gradient",
[],
Some("."),
"{stroke?: bool (default: the active proxy), ids?|id?, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default (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), to the default only) → {objects} (as paint.setFill)",
"{stroke?: bool (default: the active proxy), ids?|id?, defaultsOnly?: bool, item?: appearance item index|null, aligned?: bool (as paint.setFill), target?: \"object\"|\"contents\"} apply the last gradient used (paint.recent lastGradient), fitted to each object, to the active proxy of the selection and the default (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, to the default only) → {objects} (as paint.setFill)",
has_doc,
|s, p| {
let paint = super::gradient::unplaced(&Paint::Gradient(Box::new(s.last_gradient.clone())));
@@ -160,7 +161,7 @@ pub fn proxy_specs() -> Vec<CommandSpec> {
"Fill and Stroke",
[],
None,
"{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors)}",
"{} → {fill, stroke: the paints the Fill/Stroke proxies show (the Appearance panel's active item for the proxy of its kind, else the first selected object's, a group's first painted object's, a Live Paint group's first face's fill and first edge's stroke, type: its first run's; else the defaults for new art; when that object is a gradient mesh with points picked by the Mesh tool, Direct Selection or the Lasso and no fill item is active, the fill is its first picked point's color), fillActive, fillMixed, strokeMixed: the selected objects' (or a selected group's contents') fills (strokes) differ, a Live Paint group counting with its faces' fills and its edges' strokes, shown as a \"?\" proxy (a gradient mesh with points picked counts with their colors), fillOpacity, strokeOpacity: 0..100, the opacity of the fill item that paint.setFill {opacity} sets (the stroke item that paint.setStroke {opacity} sets), from the first selected object (or painted object in a selected group; a selected path of a compound path stands for its compound, and a Live Paint group for its faces' fills and its edges' strokes) that has one (a gradient mesh's first picked point's), or null with nothing selected (the defaults for new art), for an object selected in a symbol instance, while the Live Paint Bucket is the active tool, while the Type tool has characters selected, and when only type characters or objects without that item are selected}",
always,
proxies
),
@@ -223,7 +224,7 @@ impl Session {
// A Live Paint group without faces (or edges) shows the next selected object's paint; any other
// object without a painted object shows the defaults for new art. A face or edge selected with
// its Live Paint group counts with the group, wherever it is in the selection.
let covered = live_paint_covered(&st.doc, st.selection.subjects());
let covered = st.selection_live_paint_covered(st.selection.subjects());
for id in st.selection.subjects().iter().filter(|id| !covered.contains(*id)) {
let Some(n) = st.doc.node(*id) else { continue };
let mut nodes = vec![];
@@ -238,6 +239,80 @@ impl Session {
None
}
/// The opacity (0..1) of the fill that `paint.setFill {opacity}` sets (or of the stroke that
/// `paint.setStroke {opacity}` sets): the item's, or for a gradient mesh with points picked the
/// first picked point's. The rows the command would edit are read in order (a group without an
/// active Appearance row stands for its contents), and the first that exists answers. `None`
/// with nothing selected, for an object selected in a symbol instance, while the Live Paint
/// Bucket is the active tool (or another tool works for it, [`Session::bucket_paints`]), while
/// the Type tool has characters selected, and when only type
/// characters, objects without that item or the art of graph designs in a graph series are
/// selected.
pub fn proxy_opacity(&self, stroke: bool) -> Option<f32> {
let st = self.active()?;
// The Live Paint Bucket takes a fill or stroke chosen as the color it paints with, and the
// selection keeps its own (for_bucket).
if st.selection.symbol_part.is_some() || self.bucket_paints() {
return None;
}
// The command would give the opacity to the characters, which have none of their own.
if super::textedit::selected_range(self).is_some_and(|(_, a, b)| a != b) {
return None;
}
let item = self.appearance_item();
let of = |n: &Node, item: Option<usize>| -> Option<f32> {
if item.is_none() && matches!(n.kind, NodeKind::Text(_)) {
return None;
}
if !stroke
&& item.is_none()
&& let NodeKind::Mesh(m) = &n.kind
&& let Some((_, points)) = picked_mesh_points(self, &[n.id]).first()
{
return points.first().and_then(|i| m.points.get(*i)).map(|q| q.opacity);
}
if stroke { n.appearance.stroke_at(item).map(|s| s.opacity) } else { n.appearance.fill_at(item).map(|f| f.opacity) }
};
let subjects = st.selection.subjects();
// The command leaves out the art of a graph design in a series, which the graph draws again
// from the design, and a series group stands for the paths directly in it
// (graph::paint_targets).
let editable = |id: &&NodeId| !super::graph::is_design_art(&st.doc, **id);
// As the command picks its rows (ItemTarget::of_kind): the active item when it is a row of
// this kind in the first selected object's stack, read in the stacks the command edits;
// else the topmost one of the painted leaves of the selected objects (a group's
// contents; for a targeted layer, its editable art, ItemTarget::targets). A row of a
// graph design's art selected first stands for nothing (item_target_at).
let first = subjects.first().filter(editable).and_then(|id| st.doc.node(*id));
let active = item.filter(|i| first.and_then(|n| n.appearance.items.get(*i)).is_some_and(|it| it.is_fill() == !stroke));
if let Some(index) = active {
// The objects whose own stacks the command edits (appearance_targets: a selected
// compound-path member stands for its compound, and an object inside another selected
// one is left out), with the one whose stack the row belongs to first.
// Each target reads the row the command edits there (ItemTarget::per_target and
// ItemTarget::resolve): the row equal to the active one, else its topmost of the kind.
let row = ItemTarget::Item { index, explicit: false, aligned: true };
let mut roots = super::appearance::appearance_targets(self, &Value::Null).ok()?;
let anchor = row.anchor(self, &roots);
if let Some(head) = roots.get_mut(..=anchor) {
head.rotate_right(1);
}
let targets: Vec<NodeId> = super::graph::series_group_marks_where(&st.doc, &roots, |n| n.extras().series_index.is_some())
.into_iter()
.filter(|id| editable(&id))
.collect();
return targets.iter().zip(row.per_target(self, &targets)).find_map(|(id, at)| {
let n = st.doc.node(*id)?;
of(n, at?.resolve(&n.appearance, !stroke, "paint.proxies").ok()?)
});
}
// A Live Paint group stands for its faces in a fill edit and for its edges in a stroke edit
// (ItemTarget::targets_for).
let leaves = super::leaf_targets(self, &st.selection.objects).ok()?;
let skipped = live_paint_parts_skipped(&st.doc, &st.selection.objects, !stroke);
leaves.iter().filter(editable).filter(|id| !skipped.contains(*id)).filter_map(|id| st.doc.node(*id)).find_map(|n| of(n, None))
}
pub(crate) fn remember_paint_now(&mut self, p: &Paint) {
match p {
Paint::Solid { color, .. } => {
@@ -302,6 +377,74 @@ pub(crate) fn painted<'a>(n: &'a Node, top: bool, stroke: bool, out: &mut Vec<&'
}
}
/// What the proxies read from selected objects: the first fill, stroke and stroke weight met, and
/// whether another one differs ([`DocState::proxy_mixed`] without an active Appearance item or
/// picked mesh points, and [`super::stroke::StrokeMixed::weight`]), and whether an object lies in a
/// Live Paint group or may hold a gradient mesh. The objects added to a selection are read with
/// [`SelectionPaints::add`].
#[derive(Clone, Debug, Default)]
pub(crate) struct SelectionPaints {
fill: Option<Paint>,
pub(crate) fill_mixed: bool,
stroke: Option<Paint>,
pub(crate) stroke_mixed: bool,
weight: Option<f64>,
pub(crate) weight_mixed: bool,
/// An object is a face or edge of a Live Paint group, or lies inside one
/// ([`live_paint_covered`]).
pub(crate) in_live_paint: bool,
/// An object is a gradient mesh or a container ([`Session::fill_mesh_points`]).
pub(crate) may_hold_mesh: bool,
}
impl SelectionPaints {
/// Read objects `ids` of `doc`.
pub(crate) fn of(doc: &Document, ids: &[NodeId]) -> Self {
let mut p = Self::default();
p.add(doc, ids);
p
}
/// Read objects `ids` of `doc` too.
pub(crate) fn add(&mut self, doc: &Document, ids: &[NodeId]) {
fn meet<T>(first: &mut Option<T>, mixed: &mut bool, value: T, same: impl Fn(&T, &T) -> bool) {
match first {
Some(f) => *mixed |= !same(f, &value),
None => *first = Some(value),
}
}
// As in `proxy_mixed_with`: every node with an added id, in tree order.
let (mut fills, mut strokes) = (vec![], vec![]);
for n in doc.nodes_in_order(ids.iter().copied()) {
painted(n, true, false, &mut fills);
painted(n, true, true, &mut strokes);
}
for n in fills {
meet(&mut self.fill, &mut self.fill_mixed, proxy_paint(n, false, None), same_in_proxy);
}
for n in strokes {
meet(&mut self.stroke, &mut self.stroke_mixed, proxy_paint(n, true, None), same_in_proxy);
}
// As in `stroke_mixed`: the node each added id names.
for id in ids {
let Some(n) = doc.node(*id) else { continue };
self.in_live_paint |= in_live_paint(doc, *id);
self.may_hold_mesh |= matches!(n.kind, NodeKind::Mesh(_)) || n.is_container();
let mut nodes = vec![];
painted(n, true, true, &mut nodes);
for n in nodes {
let widths: Vec<f64> = match &n.kind {
NodeKind::Text(t) => t.runs.iter().map(|r| r.style.stroke_layer().width).collect(),
_ => n.appearance.stroke().map(|s| s.width).into_iter().collect(),
};
for w in widths {
meet(&mut self.weight, &mut self.weight_mixed, w, |a, b| a == b);
}
}
}
}
}
impl DocState {
/// Whether the selected objects' fills and strokes differ as the proxies show them (a "?"
/// proxy; a group whose contents differ counts). `item` (the Appearance panel's active item)
@@ -328,7 +471,7 @@ impl DocState {
let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]);
// The faces and edges of the selected Live Paint groups (or of those inside selected groups): selected as well,
// they count with their group's.
let covered = live_paint_covered(&self.doc, &self.selection.objects);
let covered = self.selection_live_paint_covered(&self.selection.objects);
// Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each
// place it appears.
for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) {
@@ -414,7 +557,12 @@ impl Session {
fn proxies(s: &mut Session, _: &Value) -> Result<Value> {
let (fill, stroke) = s.proxy_paints();
let (fill_mixed, stroke_mixed) = s.proxy_mixed();
Ok(json!({"fill": fill, "stroke": stroke, "fillActive": s.fill_active, "fillMixed": fill_mixed, "strokeMixed": stroke_mixed}))
// As transparency.info answers an opacity: a percentage to two places.
let percent = |o: Option<f32>| o.map(|o| (f64::from(o) * 10_000.0).round() / 100.0);
Ok(json!({
"fill": fill, "stroke": stroke, "fillActive": s.fill_active, "fillMixed": fill_mixed, "strokeMixed": stroke_mixed,
"fillOpacity": percent(s.proxy_opacity(false)), "strokeOpacity": percent(s.proxy_opacity(true)),
}))
}
/// `stroke` param, defaulting to the proxy that is in front.
@@ -533,13 +681,36 @@ fn set_paint(s: &mut Session, p: &Value, fill: bool) -> Result<Value> {
return Err(bad(cmd, "`tint` goes with a global or spot `swatch`"));
}
check_keep_model(p, cmd)?;
let paint = paint_from(s, p)?.ok_or_else(|| bad(cmd, "give color, none, swatch or gradient"))?;
let opacity = opacity_param(p, cmd)?;
let paint = paint_from(s, p)?;
// A `swatch` that is no name gives no paint, and does not turn the request into an opacity alone.
let swatch_not_a_name = p.get("swatch").is_some_and(|v| !v.is_null() && !v.is_string());
if paint.is_none() && (opacity.is_none() || swatch_not_a_name) {
return Err(bad(cmd, "give color, none, swatch, gradient or opacity"));
}
// As `paint.editGradient`: a `dither` given applies to gradient fills only. A gradient swatch
// (named) keeps its own dither; `"swatch": null` names none.
if !fill && matches!(&paint, Paint::Gradient(g) if g.gradient.dither) && p.get("swatch").and_then(Value::as_str).is_none() {
if !fill && matches!(&paint, Some(Paint::Gradient(g)) if g.gradient.dither) && p.get("swatch").and_then(Value::as_str).is_none() {
return Err(bad(cmd, "`dither` applies to gradient fills (paint.setFill)"));
}
apply_paint(s, p, paint, fill)
apply_paint_opacity(s, p, paint, opacity, fill)
}
/// The `opacity` param of `paint.setFill` and `paint.setStroke` (a percentage) as 0..1; `None`
/// when it is left out or null.
fn opacity_param(p: &Value, cmd: &str) -> Result<Option<f32>> {
match p.get("opacity") {
None | Some(Value::Null) => Ok(None),
Some(v) => match v.as_f64() {
Some(o) if (0.0..=100.0).contains(&o) => Ok(Some((o / 100.0) as f32)),
_ => Err(bad(cmd, "`opacity` must be a number from 0 to 100")),
},
}
}
/// The error for an `opacity` that would go to type characters, which have no opacity of their own.
fn characters_have_no_opacity(cmd: &str) -> EngineError {
bad(cmd, "type characters have no opacity of their own: add a fill or stroke with the Appearance panel's Add New Fill or Add New Stroke")
}
/// [`apply_paint`] on the proxy named by `stroke` (default: the active one), focusing it.
@@ -552,17 +723,31 @@ fn apply_to_proxy(s: &mut Session, p: &Value, paint: Paint, cmd: &str) -> Result
/// `paint.setFill`) and of the defaults for new art, focus its proxy unless `focus` is false, and
/// remember the paint. Replies `{objects}`: how many objects took the paint.
pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) -> Result<Value> {
apply_paint_opacity(s, p, Some(paint), None, fill)
}
/// [`apply_paint`] with `paint` optional, which also sets the `opacity` (0..1) of the fill (or
/// stroke) item each target takes it on, in the same undo step: the picked gradient mesh points'
/// own opacity for a fill (with no paint or a solid color), nothing on a target without that item.
/// The opacity alone changes neither the defaults for new art nor the remembered colors; with New
/// Art Has Basic Appearance off, new art copies the first selected object's appearance after any
/// command, its opacity included. An opacity that would go only to type
/// characters, to an object selected in a symbol instance, or to no target at all is an error.
fn apply_paint_opacity(s: &mut Session, p: &Value, paint: Option<Paint>, opacity: Option<f32>, fill: bool) -> Result<Value> {
let cmd = if fill { "paint.setFill" } else { "paint.setStroke" };
let bucket = bucket_color_params(s, p, cmd)?;
let p = bucket.as_ref().unwrap_or(p);
let focus = switch_or(p, "focus", true, cmd)?;
let span = spans_targets(p, &paint).map_err(|e| bad(cmd, e))?;
// Characters selected with the Type tool take the paint, not the whole type object (#1063).
if p.get("ids").is_none()
// An opacity alone places no gradient, so `span` may only be "object" with it.
let span = spans_targets(p, paint.as_ref().unwrap_or(&Paint::None)).map_err(|e| bad(cmd, e))?;
// Characters selected with the Type tool take the paint, not the whole type object (#1063). A
// null `ids` or `id` names no object, as `given_nodes` reads it.
if ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null))
&& p.get("item").is_none()
&& let Some((id, a, b)) = super::textedit::editing_range(s)?
&& a != b
{
let (Some(paint), None) = (paint, opacity) else { return Err(characters_have_no_opacity(cmd)) };
// After Select All in threaded text, every frame's text takes it.
let story = super::textedit::editing_story(s);
let ranges: Vec<(NodeId, usize, usize)> =
@@ -615,6 +800,9 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
// An object of a dynamic symbol instance's art selected with Direct Selection: that object's
// fill or stroke changes for this instance only (solid, none, gradient or pattern).
if let Some((id, path)) = selected_part_target(s, p, cmd)? {
let Some(paint) = paint.filter(|_| opacity.is_none()) else {
return Err(bad(cmd, "an object selected in a symbol instance has no fill or stroke opacity of its own"));
};
super::brushsym::edit_part(s, id, &path, if fill { "Fill Color" } else { "Stroke Color" }, |o| {
if fill {
o.fill = Some(paint.clone());
@@ -633,36 +821,146 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
let item = item_target(s, p, cmd)?.of_kind(s, fill);
let selected = item.targets_for(s, p, fill)?;
let ids = super::graph::paint_targets(&s.doc()?.doc, &selected);
// An opacity has nothing to go to without targets; with a paint, the defaults then stay too.
if opacity.is_some() && ids.is_empty() {
return Err(bad(cmd, "select objects or give ids"));
}
let of = super::appearance::reference_of(s, p, item, cmd)?;
let paint = if span {
// With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. Each
// object's box is that of the row it edits.
let d = &s.doc()?.doc;
let mut spanned = Vec::with_capacity(ids.len());
for (id, it) in ids.iter().zip(item.per_target_of(s, of, &ids)) {
let (Some(it), Some(n)) = (it, d.node(*id)) else { continue };
spanned.push((*id, it.resolve(&n.appearance, fill, cmd)?));
let paint = match paint {
Some(paint) if span => {
// With a design's art, the gradient spans only the objects with a row equal to the art's, which take it. Each
// object's box is that of the row it edits.
let d = &s.doc()?.doc;
let mut spanned = Vec::with_capacity(ids.len());
for (id, it) in ids.iter().zip(item.per_target_of(s, of, &ids)) {
let (Some(it), Some(n)) = (it, d.node(*id)) else { continue };
spanned.push((*id, it.resolve(&n.appearance, fill, cmd)?));
}
Some(placed_across(d, &spanned, paint, p, fill))
}
placed_across(d, &spanned, paint, p, fill)
} else {
paint
paint => paint,
};
// The gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso: a solid
// fill recolors just those points of their meshes (the proxies show them: `fill_mesh_points`).
let mesh_points = if fill && matches!(paint, Paint::Solid { .. }) { picked_mesh_points(s, &ids) } else { vec![] };
// fill recolors just those points of their meshes (the proxies show them: `fill_mesh_points`),
// and a fill opacity fades just them.
let mesh_points = if fill && matches!(paint, Some(Paint::Solid { .. }) | None) { picked_mesh_points(s, &ids) } else { vec![] };
// Without `item`, unless the Appearance panel's active fill item takes the paint.
let colorized = if fill && p.get("item").is_none() && item == ItemTarget::Top {
colorized_images(&s.doc()?.doc, &ids, &paint).map_err(|e| bad(cmd, e))?
} else {
vec![]
let colorized = match &paint {
Some(paint) if fill && p.get("item").is_none() && item == ItemTarget::Top => {
colorized_images(&s.doc()?.doc, &ids, paint).map_err(|e| bad(cmd, e))?
}
_ => vec![],
};
let label = match paint {
None => "Opacity",
Some(_) if fill => "Fill Color",
Some(_) => "Stroke Color",
};
let label = if fill { "Fill Color" } else { "Stroke Color" };
// Each object whose appearance took the paint, with the row it went to, for the paint a graph stores for its series
// (a series mark is a path, so it always has a row here).
let written = std::cell::RefCell::new(Vec::new());
// The type objects whose characters took the paint (no row targeted): only those change what a graph's labels keep
// for their characters; a row edit is kept with the label's rows.
let characters = std::cell::RefCell::new(Vec::new());
// The targets that took the opacity, and whether one would have given it to its characters.
let (took_opacity, characters_skipped) = (std::cell::RefCell::new(std::collections::BTreeSet::new()), std::cell::Cell::new(false));
// The row each target took the opacity on, for what a graph keeps.
let opacity_written = std::cell::RefCell::new(Vec::new());
let paint_one = |n: &mut Node, index: Option<usize>, paint: &Paint| -> Result<()> {
if index.is_none() && matches!(n.kind, NodeKind::Text(_)) {
characters.borrow_mut().push(n.id);
}
if index.is_none() && colorized.contains(&n.id) {
let colorize = paint.color().map(|_| Box::new(paint.clone()));
// Without a color the image has nothing to overprint, and a later color starts
// knocking out.
if colorize.is_none() {
n.extras_mut().colorize_overprint = false;
}
n.extras_mut().colorize = colorize;
return Ok(());
}
if index.is_none()
&& let Paint::Solid { color, .. } = paint
&& let Some((_, points)) = mesh_points.iter().find(|(id, _)| *id == n.id)
&& let NodeKind::Mesh(m) = &mut n.kind
{
for i in points {
if let Some(q) = m.points.get_mut(*i) {
q.color = *color;
}
}
return Ok(());
}
if index.is_none()
&& let NodeKind::Text(t) = &mut n.kind
{
let (xf, lb) = (t.xf, t.local_bounds());
for r in &mut t.runs {
if !fill && !paint.is_none() {
run_stroke_weight(&mut r.style);
}
let (cur, b) = run_paint_mut(r, !fill, lb);
*cur = place_run_paint(paint, p, xf, b);
}
return Ok(());
}
// A missing top fill or stroke is created first: a new stroke's weight sizes the box its
// gradient fits.
if n.appearance.paint_at(index, fill).is_none() {
n.appearance.set_paint_at(index, fill, Paint::None);
}
if !fill {
restore_unpainted_stroke(&mut n.appearance, index, paint);
}
let new_paint = keep_pattern_xf(paint, p, n.appearance.paint_at(index, fill));
let placed = place_paint(&new_paint, p, item_paint_bounds(n, index, fill));
n.appearance.set_paint_at(index, fill, placed);
if !fill
&& paint.is_none()
&& let Some(stroke) = n.appearance.stroke_at_mut(index)
{
// A stroke without paint has no weight; painting it again restores the 1 pt default.
stroke.width = 0.0;
}
if !fill {
super::object::snap_if_aligned(n);
}
let at = match index {
Some(_) => n.appearance.item_of_kind(index, fill),
None => n.appearance.items.iter().rposition(|it| it.is_fill() == fill),
};
written.borrow_mut().extend(at.map(|at| (n.id, at)));
Ok(())
};
// The opacity goes to what the paint went to: the picked mesh points, else the fill or stroke
// item. Characters, and targets without that item, are left as they are.
let opacity_one = |n: &mut Node, index: Option<usize>, o: f32| {
if index.is_none() && matches!(n.kind, NodeKind::Text(_)) {
characters_skipped.set(true);
return;
}
if index.is_none()
&& let Some((_, points)) = mesh_points.iter().find(|(id, _)| *id == n.id)
&& let NodeKind::Mesh(m) = &mut n.kind
{
for i in points {
if let Some(q) = m.points.get_mut(*i) {
q.opacity = o;
took_opacity.borrow_mut().insert(n.id);
}
}
return;
}
let item =
if fill { n.appearance.fill_at_mut(index).map(|f| &mut f.opacity) } else { n.appearance.stroke_at_mut(index).map(|s| &mut s.opacity) };
if let Some(item) = item {
*item = o;
took_opacity.borrow_mut().insert(n.id);
let at = index.or_else(|| n.appearance.items.iter().rposition(|it| it.is_fill() == fill));
opacity_written.borrow_mut().extend(at.map(|at| (n.id, at)));
}
};
// The objects counted: with a design's art, those with a row equal to the art's.
let ids = edit_items_then(
s,
@@ -673,114 +971,140 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
label,
fill,
|n, index| {
if index.is_none() && matches!(n.kind, NodeKind::Text(_)) {
characters.borrow_mut().push(n.id);
if let Some(paint) = &paint {
paint_one(n, index, paint)?;
}
if index.is_none() && colorized.contains(&n.id) {
n.extras_mut().colorize = paint.color().map(|_| Box::new(paint.clone()));
return Ok(());
if let Some(o) = opacity {
opacity_one(n, index, o);
}
if index.is_none()
&& let Paint::Solid { color, .. } = &paint
&& let Some((_, points)) = mesh_points.iter().find(|(id, _)| *id == n.id)
&& let NodeKind::Mesh(m) = &mut n.kind
{
for i in points {
if let Some(q) = m.points.get_mut(*i) {
q.color = *color;
}
}
return Ok(());
}
if index.is_none()
&& let NodeKind::Text(t) = &mut n.kind
{
let (xf, lb) = (t.xf, t.local_bounds());
for r in &mut t.runs {
if !fill && !paint.is_none() {
run_stroke_weight(&mut r.style);
}
let (cur, b) = run_paint_mut(r, !fill, lb);
*cur = place_run_paint(&paint, p, xf, b);
}
return Ok(());
}
// A missing top fill or stroke is created first: a new stroke's weight sizes the box its
// gradient fits.
if n.appearance.paint_at(index, fill).is_none() {
n.appearance.set_paint_at(index, fill, Paint::None);
}
if !fill {
restore_unpainted_stroke(&mut n.appearance, index, &paint);
}
let new_paint = keep_pattern_xf(&paint, p, n.appearance.paint_at(index, fill));
let placed = place_paint(&new_paint, p, item_paint_bounds(n, index, fill));
n.appearance.set_paint_at(index, fill, placed);
if !fill
&& paint.is_none()
&& let Some(stroke) = n.appearance.stroke_at_mut(index)
{
// A stroke without paint has no weight; painting it again restores the 1 pt default.
stroke.width = 0.0;
}
if !fill {
super::object::snap_if_aligned(n);
}
let at = match index {
Some(_) => n.appearance.item_of_kind(index, fill),
None => n.appearance.items.iter().rposition(|it| it.is_fill() == fill),
};
written.borrow_mut().extend(at.map(|at| (n.id, at)));
Ok(())
},
|before, d, changed| {
// An opacity that no target took is an error, which also takes back the paint given with it.
if opacity.is_some() && took_opacity.borrow().is_empty() {
if characters_skipped.get() {
return Err(characters_have_no_opacity(cmd));
}
return Err(bad(cmd, "no target has that fill or stroke to take the opacity"));
}
// A graph keeps the opacity of a series mark's topmost visible fill and stroke for the whole series, and of a
// graph line's, also when the object already showed it.
let kept = opacity.is_some() && {
let rows = opacity_written.borrow();
let on = super::graph::RowWrites { opacity: true, ..super::graph::RowWrites::NONE };
let (on_fill, on_stroke) = if fill { (on, super::graph::RowWrites::NONE) } else { (super::graph::RowWrites::NONE, on) };
let marks = super::appearance::capture_series_changes(before, d, changed);
let written = super::appearance::capture_series_opacity_writes(d, &rows);
marks | written | super::graph::capture_line_row_writes(d, &rows, on_fill, on_stroke)
};
let Some(paint) = &paint else { return Ok(kept) };
let series = super::appearance::capture_series_paint_writes(before, d, changed, &written.borrow());
// A graph line keeps the paint written to it, also when it already showed it.
let lines = super::graph::capture_line_paint_writes(d, &written.borrow());
let labels = super::graph::capture_label_styles(d, &characters.borrow(), &|st| {
if fill {
st.fill = unplaced(&paint);
st.fill = unplaced(paint);
} else {
if !paint.is_none() {
run_stroke_weight(st);
}
st.stroke = unplaced(&paint);
st.stroke = unplaced(paint);
}
});
Ok(series || lines || labels)
Ok(series || lines || labels || kept)
},
)?;
// Rejected edits leave the next shape's appearance and active proxy untouched.
paint_new_art(s, &paint, fill);
if focus {
s.fill_active = fill;
}
s.remember_paint(&paint);
Ok(json!({"objects": ids.iter().collect::<std::collections::BTreeSet<_>>().len()}))
// Rejected edits leave the next shape's appearance and active proxy untouched.
if let Some(paint) = &paint {
paint_new_art(s, paint, fill);
s.remember_paint(paint);
}
// An opacity alone counts only the targets that took it.
let objects = if paint.is_none() { took_opacity.borrow().len() } else { ids.iter().collect::<std::collections::BTreeSet<_>>().len() };
Ok(json!({"objects": objects}))
}
/// Is the Live Paint Bucket the active tool ([`Session::bucket_paints`]) while `p` names no `ids`,
/// `id` or `item`? A fill,
/// stroke or stroke weight chosen then is what the bucket paints with, so it goes to the defaults
/// and the selection keeps its paint.
pub(crate) fn for_bucket(s: &Session, p: &Value) -> bool {
/// Does `p` name no `ids`, `id` or `item`?
fn names_no_target(p: &Value) -> bool {
// A null `ids` or `id` is no target, as `given_nodes` reads it; `item: null` names the top row.
s.bucket_paints() && ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none()
["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none()
}
/// `p` with `ids: []` when [`for_bucket`]: the paint goes to the defaults only. None otherwise.
/// A bad `target` or `aligned` is refused first, as it is without the bucket.
pub(crate) fn bucket_color_params(s: &Session, p: &Value, cmd: &str) -> Result<Option<Value>> {
/// Is the Live Paint Bucket the active tool ([`Session::bucket_paints`]), or does `p` give
/// `defaultsOnly: true`, while `p` names no `ids`, `id` or `item`? A fill, stroke or stroke weight
/// chosen then is what the bucket paints with, so it goes to the defaults and the selection keeps
/// its paint.
pub(crate) fn for_bucket(s: &Session, p: &Value) -> bool {
names_no_target(p) && (s.bucket_paints() || asks_defaults_only(p))
}
/// Does `p` give `defaultsOnly: true`?
pub(crate) fn asks_defaults_only(p: &Value) -> bool {
p.get("defaultsOnly") == Some(&Value::Bool(true))
}
/// `p` with `ids: []` (and without `defaultsOnly`) when [`for_bucket`]: the paint goes to the
/// defaults only. None otherwise. A bad `target` or `aligned` is refused first, as it is without
/// the bucket, and so is a `defaultsOnly` that is not a bool or comes with `ids`, `id` or `item`.
/// When the bucket routed the command, the journal entry notes `defaultsOnly: true`, so replaying
/// it with another tool active changes the defaults only as well.
pub(crate) fn bucket_color_params(s: &mut Session, p: &Value, cmd: &str) -> Result<Option<Value>> {
let only = switch_or(p, "defaultsOnly", false, cmd)?;
if only && !names_no_target(p) {
return Err(bad(cmd, "`defaultsOnly` cannot be combined with `ids`, `id` or `item`"));
}
if !for_bucket(s, p) {
return Ok(None);
}
super::appearance::aligned(p, cmd)?;
super::appearance::targets_contents(p)?;
if !only {
s.note_journal("defaultsOnly", json!(true));
}
s.note_defaults_only();
let mut v = p.as_object().cloned().unwrap_or_default();
v.remove("defaultsOnly");
v.insert("ids".into(), json!([]));
Ok(Some(Value::Object(v)))
}
/// Whether the paint commands that `cmd` runs with params of its own change only the defaults:
/// `p` gives `defaultsOnly: true`, or the Live Paint Bucket paints ([`Session::bucket_paints`]),
/// which the journal entry of `cmd` notes for a replay.
pub(crate) fn defaults_only(s: &mut Session, p: &Value, cmd: &str) -> Result<bool> {
if switch_or(p, "defaultsOnly", false, cmd)? {
s.note_defaults_only();
return Ok(true);
}
let bucket = s.bucket_paints();
if bucket {
s.note_journal("defaultsOnly", json!(true));
s.note_defaults_only();
}
Ok(bucket)
}
impl Session {
/// Note that the running command changed only the paint defaults, with the appearance new art
/// takes from the selection now ([`Session::inherit_new_art`]). No appearance is captured
/// while inheritance does not run (New Art Has Basic Appearance on, or the bucket painting).
fn note_defaults_only(&mut self) {
let inherits = !self.prefs.new_art_basic && !self.bucket_paints();
self.defaults_only_ran = Some(if inherits { self.new_art_source() } else { None });
}
}
/// `q` with `defaultsOnly: true` when `only` ([`defaults_only`]).
pub(crate) fn with_defaults_only(mut q: Value, only: bool) -> Value {
if only && let Some(o) = q.as_object_mut() {
o.insert("defaultsOnly".into(), json!(true));
}
q
}
/// The Live Paint groups in `roots` (or inside them), given or selected whole, with the ids of
/// their faces and of their edges, found where [`leaf_targets`] finds the objects a paint command
/// changes: a given or selected object other than a group or layer (a blend, say) and a compound
@@ -864,8 +1188,7 @@ pub(crate) fn live_paint_split(d: &Document, roots: &[NodeId]) -> LivePaintParts
/// object: they count with their group, wherever they are in `selected`. The groups are looked for only when an
/// object in `selected` is inside a Live Paint group.
pub(crate) fn live_paint_covered(d: &Document, selected: &[NodeId]) -> std::collections::HashSet<NodeId> {
let inside = |id: &NodeId| d.ancestry(*id).is_some_and(|up| up.iter().rev().skip(1).filter_map(|a| d.node(*a)).any(is_live_paint));
if !selected.iter().any(inside) {
if !selected.iter().any(|id| in_live_paint(d, *id)) {
return std::collections::HashSet::new();
}
let (mut parts, edges, _) = live_paint_split(d, selected);
@@ -873,6 +1196,22 @@ pub(crate) fn live_paint_covered(d: &Document, selected: &[NodeId]) -> std::coll
parts
}
/// Is `id` inside a Live Paint group (one of the groups around it is one)?
fn in_live_paint(d: &Document, id: NodeId) -> bool {
d.ancestry(id).is_some_and(|up| up.iter().rev().skip(1).filter_map(|a| d.node(*a)).any(is_live_paint))
}
impl DocState {
/// [`live_paint_covered`] for `ids`, the selected objects or the selection's subjects: none
/// when the [`SelectionPaints`] of the selection say no selected object is in a Live Paint group.
pub(crate) fn selection_live_paint_covered(&self, ids: &[NodeId]) -> std::collections::HashSet<NodeId> {
if self.selection_paints().is_some_and(|p| !p.in_live_paint) {
return std::collections::HashSet::new();
}
live_paint_covered(&self.doc, ids)
}
}
/// The instance whose object is selected with Direct Selection, and that object's path
/// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands
/// then change that object. A bad `target` or `aligned` is refused as it is for any other selection.
@@ -1118,7 +1457,8 @@ impl Session {
// Only gradient meshes have points to pick: a selection with no mesh and no container that
// could hold one skips reading the tool's options.
let may_hold_mesh = |id: &NodeId| st.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Mesh(_)) || n.is_container());
if st.selection.symbol_part.is_some() || !st.selection.subjects().iter().any(may_hold_mesh) {
let none_may = || st.selection_paints().map_or_else(|| !st.selection.subjects().iter().any(may_hold_mesh), |p| !p.may_hold_mesh);
if st.selection.symbol_part.is_some() || none_may() {
return vec![];
}
let Ok(item) = item_target(self, &Value::Null, "paint.setFill").map(|t| t.of_kind(self, true)) else { return vec![] };
+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),
+8 -3
View File
@@ -5,7 +5,7 @@
use serde::Deserialize;
use serde_json::{Value, json};
use vectorcraft_doc::Document;
use vectorcraft_eps::{Level, PrintJob, PrintPage};
use vectorcraft_eps::{Level, PrintFonts, PrintJob, PrintPage};
use vectorcraft_geom::{Affine, Rect};
use vectorcraft_pdf::{PrintLayers, PrintOptions, PrintPreview, PrintSettings};
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Print Setup",
[],
None,
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or preset → {settings} (the current ones, defaults if never set up)",
"{preset?: name ([Default] or a saved print preset, any case: print.presets.list; its settings replace the document's, as choosing it in the Print dialog does), settings?: {copies: 1 (1–999), collate: true, reverse, artboards: all|range|ignore (all the art as one page), range: \"1-3, 5\" (1-based, with artboards: range), skipBlank (leave out artboards with no art that prints), media: letter|legal|tabloid|a3|a4|a5|a6|b4|b5|b4 (jis)|b5 (jis)|b6 (jis)|japanese postcard|japanese double postcard|japanese envelope #3|japanese envelope #4|kaku #2|kaku #3|yonroku-ban|custom (a paper is named by its id or its dialog label, any case and spacing, so `B5 (JIS)` works; b4 and b5 stay the ISO 216 sizes, 250 × 353 and 176 × 250 mm, and the JIS sizes are b4 (jis) 257 × 364 mm, b5 (jis) 182 × 257 mm and b6 (jis) 128 × 182 mm), width, height (custom paper, 72–14400 pt), orientation: portrait|landscape|portraitFlipped|landscapeFlipped, autoRotate: true (turn the paper to each artboard; orientation ignored), transverse (the page a quarter turn on the paper), printLayers: visiblePrintable|visible|all (template layers never print), placement: {origin: topLeft|top|topRight|left|center|right|bottomLeft|bottom|bottomRight (the point of the printed area, the artboard with its bleed and marks, on the same point of the imageable area), x, y (pt, right and down)}, scaling: none|fit|custom|tileFull|tileImageable, scale: {width: 100, height: 100 (1–1000 % with custom and tiling), linked: true (width and height stay equal: give one and the other follows, and turning it on sets the height to the width; a different width and height without linked turn it off, and with linked: true, or linked: null over a linked scale, are an error; a saved scale without linked reads it as false)}, overlap: 0 (pt between tiles), tileRange: \"\" (1-based tiles across then down; empty: all), copiesPerSheet: false (not with tiling: as many copies of each artboard, with its bleed and marks, as fit the imageable area, across then down, not turned; the placement places the grid; an artboard that doesn't fit prints one copy per sheet, with a warning), gutter: 0 (pt between copies, 0–720), margin: 0 (pt the device can't print around the paper: the imageable area is inside it), marks: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25, offset: 6} (as document.exportPdf, at the paper's scale; page information adds the tile and the ink), bleed: {useDocument: true (the document's bleed, document.setup), top, bottom, left, right} (pt), output: {mode: composite|separations (one gray page per ink that prints), emulsion: up|down (down mirrors), image: positive|negative, spotsToProcess, overprintBlack: false (separations: solid 100% K or 100% gray fills, strokes and characters, to within half a percent, overprint in the printed copy, gradients when every stop is (every point of a freeform one); rich, RGB, spot-linked and lighter blacks are not marked, and paints already set to overprint keep it; composite ignores it), inks: [{name: \"Cyan\"|…|a spot swatch, print: true, frequency (lpi, default 60), angle (screen angle, degrees counter-clockwise as PostScript setscreen takes it; default C 15, M 75, Y 0, K 45, spots 45), convertToProcess: false (a spot ink only: it prints on the process plates, with no plate of its own, and its print, frequency and angle are kept for when it prints as a spot ink again; spotsToProcess converts every spot ink whatever it says)}]}, graphics: {autoFlatness: true, flatness: 1 (0.2–100), fonts: none|subset|complete (PostScript output: subset (default) sends each page the glyphs it shows, complete sends every glyph of each font once before the first page, none sends no font and names the printer's own; PDF output embeds subsets of the fonts whose licenses allow it, and draws the others as outlines, with any of them, and none or complete adds a note)}, color: {intent: perceptual|relativeColorimetric|saturation|absoluteColorimetric, preserveNumbers: true (CMYK colors keep their values), profile: \"\" (the printer profile, an RGB or CMYK one: composite PDF colors are converted to it with the intent, separations separate with a CMYK one; empty: as they are)}, advanced: {printAsBitmap (composite pages print as one image each, at the document's raster effects resolution, or lower for a page larger than 64 Mpx or 32,768 px a side), overprints: preserve|discard|simulate (composite output; preserve writes them to overprint (/OP), simulate prints them as Overprint Preview shows them; separations always keep them), flattenerPreset: \"\" (a flattener preset, built-in or saved: transparency is flattened before printing; empty: it prints live; PostScript defaults to medium)}, tileOrigin: {placed: false, x, y} (where the Print Tiling tool put the pages: print.tiling.set)}} store the print settings with the document, over the ones it has or the preset's (null keeps a value), as one undo step; no settings or pre Line truncated
has_doc,
setup
),
@@ -276,6 +276,11 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
setting_notes.push("the printer profile converts the colours of PDF output: PostScript prints the document's colours".to_string());
}
let flatness = (!set.graphics.auto_flatness).then_some(set.graphics.flatness);
let fonts = match set.graphics.fonts {
vectorcraft_pdf::FontDownload::None => PrintFonts::Resident,
vectorcraft_pdf::FontDownload::Subset => PrintFonts::Subset,
vectorcraft_pdf::FontDownload::Complete => PrintFonts::Complete,
};
let plan = vectorcraft_pdf::plan(prepared.as_ref().unwrap_or(doc), &PrintOptions { settings: set, postscript: true, ..Default::default() })
.map_err(|e| pdf_error(PRINT, e))?;
let pages: Vec<PrintPage> = plan
@@ -294,7 +299,7 @@ fn print(s: &mut Session, p: &Value) -> Result<Value> {
ink: sh.ink.as_ref().map(|i| (i.name.as_str(), i.frequency, i.angle)),
})
.collect();
let job = PrintJob { level, title: plan.title.clone(), created: plan.created, flatness };
let job = PrintJob { level, title: plan.title.clone(), created: plan.created, flatness, fonts };
let out = vectorcraft_eps::print(&pages, &plan.order, &job).map_err(|e| bad(PRINT, e))?;
for w in plan.warnings.iter().chain(&out.warnings) {
if !warnings.contains(w) {
+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)
Loaded 100 of 465 files, more files were not shown because too many files have changed in this diff. Show more