diff --git a/ASSETS.md b/ASSETS.md index c14753a7d9..a21d7a9692 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -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 | | diff --git a/Cargo.lock b/Cargo.lock index 2db5a4112b..1b57f15652 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml index bbc2a8bc2d..15f14067e6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" } diff --git a/ROADMAP.md b/ROADMAP.md index 90a6100167..12f4bb334f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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 `_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. diff --git a/apps/vectorcraft-web/Cargo.toml b/apps/vectorcraft-web/Cargo.toml index 780259f957..ce5110f8ac 100644 --- a/apps/vectorcraft-web/Cargo.toml +++ b/apps/vectorcraft-web/Cargo.toml @@ -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 } diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 0a1f938ced..dd9dc3f774 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -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(); diff --git a/assets/icons/dc-corner-tool.svg b/assets/icons/dc-corner-tool.svg new file mode 100644 index 0000000000..7b467ce306 --- /dev/null +++ b/assets/icons/dc-corner-tool.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-cycle-sizes.svg b/assets/icons/dc-cycle-sizes.svg new file mode 100644 index 0000000000..77bcc7c9af --- /dev/null +++ b/assets/icons/dc-cycle-sizes.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-area.svg b/assets/icons/dc-graph-area.svg new file mode 100644 index 0000000000..4aae0a6663 --- /dev/null +++ b/assets/icons/dc-graph-area.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-bar.svg b/assets/icons/dc-graph-bar.svg new file mode 100644 index 0000000000..ee08f9eba3 --- /dev/null +++ b/assets/icons/dc-graph-bar.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-column.svg b/assets/icons/dc-graph-column.svg new file mode 100644 index 0000000000..bf896fe563 --- /dev/null +++ b/assets/icons/dc-graph-column.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-line.svg b/assets/icons/dc-graph-line.svg new file mode 100644 index 0000000000..46a2ef7ecd --- /dev/null +++ b/assets/icons/dc-graph-line.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-pie.svg b/assets/icons/dc-graph-pie.svg new file mode 100644 index 0000000000..a406bf7b7a --- /dev/null +++ b/assets/icons/dc-graph-pie.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-radar.svg b/assets/icons/dc-graph-radar.svg new file mode 100644 index 0000000000..82fe72d29e --- /dev/null +++ b/assets/icons/dc-graph-radar.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-scatter.svg b/assets/icons/dc-graph-scatter.svg new file mode 100644 index 0000000000..c674fc8cd1 --- /dev/null +++ b/assets/icons/dc-graph-scatter.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-stacked-bar.svg b/assets/icons/dc-graph-stacked-bar.svg new file mode 100644 index 0000000000..989dfaaf58 --- /dev/null +++ b/assets/icons/dc-graph-stacked-bar.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-graph-stacked-column.svg b/assets/icons/dc-graph-stacked-column.svg new file mode 100644 index 0000000000..f7f234f280 --- /dev/null +++ b/assets/icons/dc-graph-stacked-column.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-help.svg b/assets/icons/dc-help.svg new file mode 100644 index 0000000000..2b6f6f5bab --- /dev/null +++ b/assets/icons/dc-help.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-lasso-enclosing.svg b/assets/icons/dc-lasso-enclosing.svg new file mode 100644 index 0000000000..c15d730f97 --- /dev/null +++ b/assets/icons/dc-lasso-enclosing.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-lasso-polygonal.svg b/assets/icons/dc-lasso-polygonal.svg new file mode 100644 index 0000000000..4f69572878 --- /dev/null +++ b/assets/icons/dc-lasso-polygonal.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-lasso.svg b/assets/icons/dc-lasso.svg new file mode 100644 index 0000000000..5143e0d447 --- /dev/null +++ b/assets/icons/dc-lasso.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-perspective-select.svg b/assets/icons/dc-perspective-select.svg new file mode 100644 index 0000000000..e31fa0b254 --- /dev/null +++ b/assets/icons/dc-perspective-select.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-recolor-arrow-off.svg b/assets/icons/dc-recolor-arrow-off.svg new file mode 100644 index 0000000000..9a972d3804 --- /dev/null +++ b/assets/icons/dc-recolor-arrow-off.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-recolor-arrow.svg b/assets/icons/dc-recolor-arrow.svg new file mode 100644 index 0000000000..41dd50e3be --- /dev/null +++ b/assets/icons/dc-recolor-arrow.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-shared-edge.svg b/assets/icons/dc-shared-edge.svg new file mode 100644 index 0000000000..7301265544 --- /dev/null +++ b/assets/icons/dc-shared-edge.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-slice-select.svg b/assets/icons/dc-slice-select.svg new file mode 100644 index 0000000000..9cdce42a1e --- /dev/null +++ b/assets/icons/dc-slice-select.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-slice.svg b/assets/icons/dc-slice.svg new file mode 100644 index 0000000000..5a1791b428 --- /dev/null +++ b/assets/icons/dc-slice.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-slide-anchor.svg b/assets/icons/dc-slide-anchor.svg new file mode 100644 index 0000000000..0107876985 --- /dev/null +++ b/assets/icons/dc-slide-anchor.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-swatch-global.svg b/assets/icons/dc-swatch-global.svg new file mode 100644 index 0000000000..972e265f41 --- /dev/null +++ b/assets/icons/dc-swatch-global.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-swatch-process.svg b/assets/icons/dc-swatch-process.svg new file mode 100644 index 0000000000..708d9dd27e --- /dev/null +++ b/assets/icons/dc-swatch-process.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-swatch-spot.svg b/assets/icons/dc-swatch-spot.svg new file mode 100644 index 0000000000..7ba3dcaef3 --- /dev/null +++ b/assets/icons/dc-swatch-spot.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-screener.svg b/assets/icons/dc-symbol-screener.svg new file mode 100644 index 0000000000..cbb9aa899f --- /dev/null +++ b/assets/icons/dc-symbol-screener.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-scruncher.svg b/assets/icons/dc-symbol-scruncher.svg new file mode 100644 index 0000000000..4b4203acba --- /dev/null +++ b/assets/icons/dc-symbol-scruncher.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-shifter.svg b/assets/icons/dc-symbol-shifter.svg new file mode 100644 index 0000000000..bd3c2b67d2 --- /dev/null +++ b/assets/icons/dc-symbol-shifter.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-sizer.svg b/assets/icons/dc-symbol-sizer.svg new file mode 100644 index 0000000000..771627cf72 --- /dev/null +++ b/assets/icons/dc-symbol-sizer.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-spinner.svg b/assets/icons/dc-symbol-spinner.svg new file mode 100644 index 0000000000..c5a3ab7423 --- /dev/null +++ b/assets/icons/dc-symbol-spinner.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-stainer.svg b/assets/icons/dc-symbol-stainer.svg new file mode 100644 index 0000000000..79f2541d28 --- /dev/null +++ b/assets/icons/dc-symbol-stainer.svg @@ -0,0 +1 @@ + diff --git a/assets/icons/dc-symbol-styler.svg b/assets/icons/dc-symbol-styler.svg new file mode 100644 index 0000000000..b81ffaa5e7 --- /dev/null +++ b/assets/icons/dc-symbol-styler.svg @@ -0,0 +1 @@ + diff --git a/crates/doc/src/appearance/layers.rs b/crates/doc/src/appearance/layers.rs index 11d2b0664d..614616dadd 100644 --- a/crates/doc/src/appearance/layers.rs +++ b/crates/doc/src/appearance/layers.rs @@ -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 } diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index 4d66f5d74c..3e08f96977 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -389,6 +389,12 @@ pub enum DimensionSource { #[serde(default, rename = "freeB", skip_serializing_if = "Option::is_none")] free_b: Option, }, + /// 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 { let mut first: Option = 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)?; diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 04a96c97fd..3e5743aec3 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -343,18 +343,27 @@ impl Document { /// tree order where `id` appears. pub fn index_path(&self, id: NodeId) -> Option> { 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>, 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::>>() + }); 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) } diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index fdd18c4693..6d5cb0f1a5 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -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()) } diff --git a/crates/doc/src/id_index.rs b/crates/doc/src/id_index.rs index 149a8e488b..34453234ec 100644 --- a/crates/doc/src/id_index.rs +++ b/crates/doc/src/id_index.rs @@ -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 = HashMap>; -/// 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>; + +/// 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, + gaps: Arc, +} + +/// 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>, 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>> { - 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> { - 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 { + 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>>, std::sync::atomic::AtomicU32); +pub struct IdIndex(RwLock>>, 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]) -> Arc { - fn walk(nodes: &[Arc], parent: u32, out: &mut Paths) { + fn walk(nodes: &[Arc], 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()) } } diff --git a/crates/doc/src/image_quad.rs b/crates/doc/src/image_quad.rs index 92f7f24758..8f514a3b71 100644 --- a/crates/doc/src/image_quad.rs +++ b/crates/doc/src/image_quad.rs @@ -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 { + 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 { diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 3813b24950..e9d5296470 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -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() { diff --git a/crates/doc/src/live/expand.rs b/crates/doc/src/live/expand.rs index e1eb3acc3d..f0b5d98879 100644 --- a/crates/doc/src/live/expand.rs +++ b/crates/doc/src/live/expand.rs @@ -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 diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs index 439d3605fd..0eed9c7829 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -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>, + /// 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(), diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index 60a3c75d79..d9642e7866 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -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>, #[serde(default)] + colorize_overprint: bool, + #[serde(default)] compound_shape: bool, #[serde(default)] shape_mode: crate::ShapeMode, @@ -477,6 +481,7 @@ impl From 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, diff --git a/crates/doc/src/overprint.rs b/crates/doc/src/overprint.rs index 58f6b5abc2..7c13b8f755 100644 --- a/crates/doc/src/overprint.rs +++ b/crates/doc/src/overprint.rs @@ -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, 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) -> Option { + 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) -> 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) -> 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, 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, discard_white: &DiscardWhite, images: &BTreeMap) { 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) -> 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, +} + +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 { + 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 { 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) { (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| { + 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); diff --git a/crates/doc/src/selection.rs b/crates/doc/src/selection.rs index de8ad66364..d2488b8b5f 100644 --- a/crates/doc/src/selection.rs +++ b/crates/doc/src/selection.rs @@ -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, toggle: bool) { use std::collections::hash_map::{Entry, HashMap}; - let mut ids = ids.into_iter().peekable(); - if ids.peek().is_none() { + let ids: Vec = 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 = self.objects.iter().map(|id| (*id, 0)).collect(); let mut added: Vec<(NodeId, usize)> = Vec::new(); let mut removed = false; diff --git a/crates/doc/src/tests/lookups.rs b/crates/doc/src/tests/lookups.rs index d7c24934e0..295c347765 100644 --- a/crates/doc/src/tests/lookups.rs +++ b/crates/doc/src/tests/lookups.rs @@ -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) { + 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> = (0..3).map(|_| Arc::new(square(&mut d))).collect(); + let members: Vec = 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 = 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 = (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> = + (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 { diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 46fd9344e2..1b8067e91c 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -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; diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index c7ab85e7a8..ee68067d2f 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -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(); diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index a6f0d6b2ae..dfaf8c35e6 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -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::>>() 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() { diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 5d1493fcd7..ea5d72f7ef 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -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::>>() else { continue }; - let points: Option> = corners.iter().map(|(m, n)| on_mesh.art_point(*m, *n)).collect(); + let points: Option> = 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() { diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 348d21ba38..3b0acaa821 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -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`. diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 283958e4e1..56f955106b 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -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>> { diff --git a/crates/engine/src/cmd/addons/color.rs b/crates/engine/src/cmd/addons/color.rs index 703d81ddc3..8bf1e00d16 100644 --- a/crates/engine/src/cmd/addons/color.rs +++ b/crates/engine/src/cmd/addons/color.rs @@ -52,7 +52,7 @@ pub fn specs() -> Vec { "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 ), diff --git a/crates/engine/src/cmd/addons/color/print_fixes.rs b/crates/engine/src/cmd/addons/color/print_fixes.rs index c5f430eb76..12c4f3a7c2 100644 --- a/crates/engine/src/cmd/addons/color/print_fixes.rs +++ b/crates/engine/src/cmd/addons/color/print_fixes.rs @@ -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) -> 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) -> (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 { 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); } } diff --git a/crates/engine/src/cmd/addons/color/print_fixes/tests.rs b/crates/engine/src/cmd/addons/color/print_fixes/tests.rs index e4c1915879..8e28701572 100644 --- a/crates/engine/src/cmd/addons/color/print_fixes/tests.rs +++ b/crates/engine/src/cmd/addons/color/print_fixes/tests.rs @@ -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)]); diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index 586dc9947e..2c14c3deba 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -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 { v.extend(tangent_circle::specs()); v.extend(tangents::specs()); v.extend(bounding::specs()); + v.extend(inscribed::specs()); v } diff --git a/crates/engine/src/cmd/addons/pathtools/bounding.rs b/crates/engine/src/cmd/addons/pathtools/bounding.rs index 954a4f829a..b82b67832e 100644 --- a/crates/engine/src/cmd/addons/pathtools/bounding.rs +++ b/crates/engine/src/cmd/addons/pathtools/bounding.rs @@ -49,7 +49,7 @@ pub(super) fn specs() -> Vec { /// 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) } diff --git a/crates/engine/src/cmd/addons/pathtools/inscribed.rs b/crates/engine/src/cmd/addons/pathtools/inscribed.rs new file mode 100644 index 0000000000..e240fdf43d --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/inscribed.rs @@ -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 { + 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 { + // 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::>() })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs b/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs new file mode 100644 index 0000000000..86f0342ff7 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/inscribed/tests.rs @@ -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 { + 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::>()})).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::>(); + 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 = 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"); + } +} diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 99ccd2d828..ac993f7ab5 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -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 = 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::>() + }) + .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 { let fill = ap.items.get(at)?.is_fill(); diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 79dbd6e488..aa3cf36cba 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -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, + /// 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>, } 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::>()? }) - } - 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::>()?, + 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>) -> 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, /// The global and spot colors that took the document's color (merged). merged_swatches: BTreeSet, + /// 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, 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| 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) } diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 1b394fa95c..54e7a3bbf4 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -169,7 +169,7 @@ pub fn specs() -> Vec { "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 ), diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index 9f631aafd2..9caec2ae92 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -14,7 +14,7 @@ pub fn specs() -> Vec { "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 { "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 { | (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 { 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 { 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 { 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() { diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index bb22ae5c16..f20a413473 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "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|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", has_doc, info ), @@ -183,8 +183,126 @@ fn count_fonts(fonts: &mut BTreeMap, t: &vectorcr } } -/// An image object as Document Info lists it: (name, width, height, linked file). -type ImageRow = (String, u32, u32, Option); +/// 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, + /// 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, + /// For an embedded image, the bytes of the encoded image the document holds. + stored: Option, +} + +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) -> 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 { 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 { let font_names: Vec = fonts.keys().map(super::fonts::font_label).collect(); let (font_uses, font_use_rows): (Vec, Vec<(String, String)>) = fonts.iter().map(|(f, n)| font_use(f, *n)).unzip(); let (font_entries, font_rows): (Vec, 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 = 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 = 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 { + 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 { 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::>(), [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::>()); + 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::>(), [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. diff --git a/crates/engine/src/cmd/docsetup.rs b/crates/engine/src/cmd/docsetup.rs index dadafaa1b8..8aacbb1eb0 100644 --- a/crates/engine/src/cmd/docsetup.rs +++ b/crates/engine/src/cmd/docsetup.rs @@ -17,7 +17,7 @@ pub fn specs() -> Vec { "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 )] diff --git a/crates/engine/src/cmd/draw2.rs b/crates/engine/src/cmd/draw2.rs index 885fd35988..1054ca3ddc 100644 --- a/crates/engine/src/cmd/draw2.rs +++ b/crates/engine/src/cmd/draw2.rs @@ -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}; diff --git a/crates/engine/src/cmd/draw2/anchors.rs b/crates/engine/src/cmd/draw2/anchors.rs index 5b80fcc80f..8068418edd 100644 --- a/crates/engine/src/cmd/draw2/anchors.rs +++ b/crates/engine/src/cmd/draw2/anchors.rs @@ -166,7 +166,7 @@ pub(super) fn remove_anchors(s: &mut Session, _: &Value) -> Result { /// 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, diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 9c3dcbd47a..bce1e24d98 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -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 { 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 { "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 ), diff --git a/crates/engine/src/cmd/draw2/quickpen.rs b/crates/engine/src/cmd/draw2/quickpen.rs index 84640bc876..c6549075df 100644 --- a/crates/engine/src/cmd/draw2/quickpen.rs +++ b/crates/engine/src/cmd/draw2/quickpen.rs @@ -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 { })?; 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 { + 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 })) +} diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index b5291b4621..b787bc5d0e 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -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 { /// 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 { + #[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 = 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, + /// 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>, + /// The stretches whose reach covers more than [`MAX_STRETCH_CELLS`] cells. + wide: Vec, +} + +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 { + 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) { - let near = |q: Point| dist_to_polyline(pts, q) <= radius; +fn mark_reached(sp: &SubPath, reach: &DragReach, share: usize) -> (SubPath, Vec) { + let (pts, radius) = (reach.pts, reach.radius); let n = sp.anchors.len(); - let marked: Vec = sp.anchors.iter().map(|a| near(a.p)).collect(); + let marked: Vec = 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 { +fn smooth_subpath(sp: &SubPath, reach: &DragReach, share: usize, tol: f64, sigma: f64) -> Option { 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 { + /// The start of the list. + head: Vec, + /// The rest of the list, last item first. + rest: Vec, +} + +impl EditsFromEnd { + fn new(items: Vec) -> 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) { + 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 { + 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) = (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, 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 { @@ -696,15 +937,16 @@ pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { 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 = 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 { _ => sp.clone(), }) .collect(); - if changed { + // A subpath whose result would not be smoother stays as it was. + let subs: Vec = + 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 = (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::>(), 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 { + (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 = + (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 = (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 = (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::>(), 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"); + } + } } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 514e6e78e1..b07950d52a 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -225,7 +225,7 @@ pub fn specs() -> Vec { "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 { fn clear(s: &mut Session, p: &Value) -> Result { 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 { } // 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 { 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 { + 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 { const CMD: &str = "edit.dropSelection"; diff --git a/crates/engine/src/cmd/fileio/mesh3d.rs b/crates/engine/src/cmd/fileio/mesh3d.rs index 2e781772ea..205a3cec35 100644 --- a/crates/engine/src/cmd/fileio/mesh3d.rs +++ b/crates/engine/src/cmd/fileio/mesh3d.rs @@ -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]) -> Vec { /// 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]) -> Result)>, String> { + check_parts(parts)?; let (images, image) = images(parts.len(), textures); let maps: Vec = 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 )"); } diff --git a/crates/engine/src/cmd/fileio/mesh3d/tests.rs b/crates/engine/src/cmd/fileio/mesh3d/tests.rs index 876140fce7..f87625d9fe 100644 --- a/crates/engine/src/cmd/fileio/mesh3d/tests.rs +++ b/crates/engine/src/cmd/fileio/mesh3d/tests.rs @@ -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::>(), ["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, Vec>) { 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::>(), ["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::>(), ["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::>(), [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::>(), ["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 = "), "{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 = ")); diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 819895414c..8e080e8d80 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "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 another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{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 another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones not linked to a spot swatch at a tint above 0% knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", has_doc, export_pdf ), diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index f03dc6fe0d..7585861e9b 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -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; diff --git a/crates/engine/src/cmd/flatten/apply.rs b/crates/engine/src/cmd/flatten/apply.rs index 1525a97e1d..fe1e183d16 100644 --- a/crates/engine/src/cmd/flatten/apply.rs +++ b/crates/engine/src/cmd/flatten/apply.rs @@ -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)) } diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index 8cf1091492..2b14fdba2d 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "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 item are given (a null ids or id counts as none), only the default changes (the paint the bucket paints with)", + "{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 Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the paint the bucket paints with)", has_doc, edit_gradient ), diff --git a/crates/engine/src/cmd/gradpresets.rs b/crates/engine/src/cmd/gradpresets.rs index c8eaa07135..89deda43ad 100644 --- a/crates/engine/src/cmd/gradpresets.rs +++ b/crates/engine/src/cmd/gradpresets.rs @@ -33,7 +33,7 @@ pub fn specs() -> Vec { "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 ), diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index d0ed27ca8a..45242affa3 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -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 = 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(); diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index ecbfa760bb..80c4cbefb9 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -712,7 +712,7 @@ pub fn specs() -> Vec { "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 { 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 { } 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 { 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 { /// 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 { /// 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 { +/// 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 { 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 { // 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(¤t, &doc, &name, &clip)?; + let (choices, probe, imported) = super::patternlib::probe_import(¤t, &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 { } // 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) } diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index fd76896ce3..1115c7e917 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -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 { 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 { + 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. diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index aa330e11ea..96365e6553 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -187,7 +187,7 @@ pub fn specs() -> Vec { "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 { 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> = 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 = d.artboards.iter().map(|a| a.rect).collect(); + let laid: Vec = picked.clone().unwrap_or_else(|| (0..count).collect()); + let rects: Vec = 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 = - 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 { } Ok(()) })?; - Ok(json!({ "artboards": count, "rows": rows, "columns": cols })) + Ok(result) } diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index a42088e7e3..b95134aa59 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -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, +} + 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 { 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 { + 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 { + 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 { diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 97438ec6b1..4785816809 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -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, 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)]); diff --git a/crates/engine/src/cmd/overprint.rs b/crates/engine/src/cmd/overprint.rs index 4c0b3ea9f4..9256062e66 100644 --- a/crates/engine/src/cmd/overprint.rs +++ b/crates/engine/src/cmd/overprint.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "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) -> Vec { 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) -> 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(()) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 6666a1d7a3..b09bc04d4b 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -27,7 +27,7 @@ pub fn specs() -> Vec { "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 or changed it, and its opacity when `opacity` changed it (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change the bucket made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}", has_doc, |s, p| set_paint(s, p, true) ), @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "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 { "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 { "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 { "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 { "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 { "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 { "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 { "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 { "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 { + 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| -> Option { + 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 = 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, + pub(crate) fill_mixed: bool, + stroke: Option, + pub(crate) stroke_mixed: bool, + weight: Option, + 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(first: &mut Option, 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 = 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 { 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| 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 { 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> { + 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 { + 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, opacity: Option, fill: bool) -> Result { 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, 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, 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::>().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::>().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> { +/// 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> { + 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 { + 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 { - 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 { + 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![] }; diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index d32594d92d..feb1c0ad10 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "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 { /// 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 { + 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 { // `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 { d.remove_many(&whole_ids)?; } let mut survivors = vec![]; + let mut following = vec![]; let remaining: Vec = 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 { 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 = { let path = path_mut(d, *id)?; @@ -1731,6 +1760,11 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result { } } selection.set(survivors); + for (id, next) in following { + if !next.is_empty() { + selection.anchors.insert(id, next); + } + } Ok(()) })?; ok() diff --git a/crates/engine/src/cmd/patternlib.rs b/crates/engine/src/cmd/patternlib.rs index 64342b21dd..53fc83b7c9 100644 --- a/crates/engine/src/cmd/patternlib.rs +++ b/crates/engine/src/cmd/patternlib.rs @@ -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>; + /// 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 = 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 { - 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 { + 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 diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index fad852e14f..e7416a6a42 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -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 { 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::>(); + 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::>()}); 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], b: &[Arc]) -> 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 { + 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>; + static PLACED: Mutex> = 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 { "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.), format? and extensions? (an exporter's or importer's format id, plugin., 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.., 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.), format? and extensions? (an exporter's or importer's format id, plugin., 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.., 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 { "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 ), diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..ec7d3ac989 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -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", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 81a26dd46e..890f72455d 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -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), diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index 8c507db007..13086d1321 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -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 { "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 preset → {settings} (the current ones, defaults if never set up)", has_doc, setup ), @@ -276,6 +276,11 @@ fn print(s: &mut Session, p: &Value) -> Result { 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 = plan @@ -294,7 +299,7 @@ fn print(s: &mut Session, p: &Value) -> Result { 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) { diff --git a/crates/engine/src/cmd/recovery.rs b/crates/engine/src/cmd/recovery.rs index 5a70d49ab7..54906b5a1d 100644 --- a/crates/engine/src/cmd/recovery.rs +++ b/crates/engine/src/cmd/recovery.rs @@ -874,6 +874,11 @@ struct Meta { /// images were kept apart: the document entry holds them). #[serde(skip_serializing_if = "BTreeMap::is_empty")] images: BTreeMap, + /// 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) -> Result<(Vec /// (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, file: &str) -> Result { 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::(&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, 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, 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)); } diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index 29ead30e52..8a68798aed 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "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, system_layout: bool, unmatched: &mut Vec) -> Vec { +/// `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, + system_layout: bool, + spacing: &std::collections::HashMap, + unmatched: &mut Vec, +) -> Vec { // 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::().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, system_layout: bool, unmatched: &mut Vec) 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 { - 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 { 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 = 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 = std::collections::HashMap::new(); for (pc, parts) in pieces.iter().zip(&found) { @@ -1775,8 +1831,40 @@ fn retype(s: &mut Session, p: &Value) -> Result { 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 = 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 { 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 = 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)); diff --git a/crates/engine/src/cmd/retype_fonts.rs b/crates/engine/src/cmd/retype_fonts.rs index dc9a413d5f..a901ac7e12 100644 --- a/crates/engine/src/cmd/retype_fonts.rs +++ b/crates/engine/src/cmd/retype_fonts.rs @@ -26,7 +26,7 @@ pub(in crate::cmd) fn specs() -> Vec { "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 { 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, f64)> = vec![]; + let mut best: Vec<(Arc, 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) diff --git a/crates/engine/src/cmd/retype_fonts_tests.rs b/crates/engine/src/cmd/retype_fonts_tests.rs index d7e675f503..ac7723d82a 100644 --- a/crates/engine/src/cmd/retype_fonts_tests.rs +++ b/crates/engine/src/cmd/retype_fonts_tests.rs @@ -106,6 +106,21 @@ fn shapes_that_are_no_glyph_list_no_font() { assert!(s.execute("type.retypeFonts", &json!({})).is_err()); } +#[test] +fn a_font_that_matches_only_combining_marks_is_not_listed() { + let mut s = session(); + // A lone combining mark (a drawn dot, bar or ring is the same shape): type.retype keeps it. + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = query(&mut s, json!({}), bundled()); + assert_eq!(r, json!({"fonts": [], "shapes": 1, "more": false, "truncated": false})); + // After a base, the mark counts with it. + let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = query(&mut s, json!({}), bundled()); + assert!(names(&r).contains(&("Source Sans 3".into(), "Regular".into(), 2)), "{r}"); +} + #[test] fn shapes_past_the_limits_are_reported_as_left_out() { let mut s = session(); diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 59afb45487..5e000d52ab 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -97,6 +97,165 @@ fn a_drawn_shape_is_reported_and_left_alone() { assert!(s.doc().unwrap().doc == before); } +#[test] +fn a_mark_in_one_font_starts_its_line_as_another_fonts_character() { + use vectorcraft_text::test_fonts::{SPACING_COMMA_FAMILY, spacing_comma_font}; + // The comma below of Source Sans 3 is only marks there, and a modifier letter in this face. + vectorcraft_text::FontDb::global().add_font(spacing_comma_font().unwrap()); + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{326}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["\u{2bb}"]), "{r}"); + assert_eq!(r["fonts"][0]["family"], json!(SPACING_COMMA_FAMILY), "{r}"); + // After a base, it joins the line as the mark; moved off its base, the split leaves it first, + // and it becomes the other face's character there. + let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "x\u{326}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0; + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "\u{2bb}", "yz"]), &json!([])), "{r}"); + assert_eq!(r["fonts"][1]["family"], json!(SPACING_COMMA_FAMILY), "{r}"); +} + +#[test] +fn a_combining_mark_starts_no_line() { + // A combining mark on its own (a drawn dot, bar or ring is the same shape) stays an outline. + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "\u{312}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("type.retype", &json!({})).unwrap_err().to_string(); + assert!(e.contains("no selected shape matches"), "{e}"); + assert!(s.doc().unwrap().doc == before, "nothing changes"); + // A shape that is both a mark (tilde below) and a character (small tilde) starts its line as + // the character. + let g = outlined(&mut s, json!({"x": 140, "y": 100, "text": "\u{303}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["\u{2dc}"]), "{r}"); + // A glyph after it does not turn it back into the mark (diaeresis below, diaeresis). + let g = outlined(&mut s, json!({"x": 240, "y": 100, "text": "\u{324}a", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["\u{a8}", "a"]), &json!([])), "{r}"); + // First on a line, the mark stays an outline and the glyphs after it are retyped. + let g = outlined(&mut s, json!({"x": 40, "y": 200, "text": "\u{312}ab", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[0].id.0; + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["ab"]), "{r}"); + assert_eq!(r["unmatched"], json!([mark])); + // After a base, the mark is retyped with it. + let g = outlined(&mut s, json!({"x": 40, "y": 300, "text": "x\u{323}", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["x\u{323}"]), "{r}"); + // Moved off its base, the mark is where the line splits, and the part after the split does + // not start with it either. + let g = outlined(&mut s, json!({"x": 300, "y": 200, "text": "x\u{312}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0; + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yz"]), &json!([mark])), "{r}"); + // A mark that is also another character (dot below, dot above) becomes that character there. + let g = outlined(&mut s, json!({"x": 300, "y": 120, "text": "x\u{323}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0; + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "\u{2d9}", "yz"]), &json!([])), "{r}"); + // Tracked, the part after the mark keeps the tracking its own glyphs are spaced by. + let id = s + .execute("text.create", &json!({"x": 40, "y": 60, "text": "x\u{312}yzw", "size": 40, "font": "Source Sans 3", "style": "Regular"})) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 5, "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mark = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap()[1].id.0; + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!((&r["texts"], &r["unmatched"]), (&json!(["x", "yzw"]), &json!([mark])), "{r}"); + assert_eq!(r["fonts"][1]["tracking"], json!(50.0), "{r}"); + // A one-contour glyph after a mark that stays an outline (a bar, then a dot) is alone, and + // beside other shapes it stays an outline too. + let dot = outlined(&mut s, json!({"x": 300, "y": 300, "text": "\u{312}.", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let mut pair: Vec = s.doc().unwrap().doc.children(Some(NodeId(dot))).unwrap().iter().map(|n| n.id.0).collect(); + pair.sort_unstable(); + let word = outlined(&mut s, json!({"x": 40, "y": 380, "text": "ab", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + s.execute("select.set", &json!({"ids": [dot, word]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["ab"]), "{r}"); + let mut left: Vec = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + left.sort_unstable(); + assert_eq!(left, pair, "{r}"); +} + +#[test] +fn marks_of_one_compound_path_each_become_their_own_character() { + // Two marks that are also other characters (dot below, dot above; tilde, small tilde), moved + // off their base and made one compound path: each becomes the character its own shape is. + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "x\u{323}\u{303}yz", "size": 40, "font": "Source Sans 3", "style": "Regular"})); + let kids: Vec = s.doc().unwrap().doc.children(Some(NodeId(g))).unwrap().iter().map(|n| n.id.0).collect(); + assert_eq!(kids.len(), 5); + s.execute("select.set", &json!({"ids": [kids[1], kids[2]]})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["unmatched"], json!([]), "{r}"); + let texts: Vec<&str> = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap()).collect(); + let mut marks = texts.get(1..3).unwrap_or_default().to_vec(); + marks.sort_unstable(); + assert_eq!((texts.first(), texts.get(3), texts.len()), (Some(&"x"), Some(&"yz"), 4), "{r}"); + assert_eq!(marks, ["\u{2d9}", "\u{2dc}"], "{r}"); +} + +#[test] +fn marks_first_after_a_split_leave_other_lines_their_tracking() { + // Twenty marks moved off their base, each one first on its line in turn, do not use up the + // measures of the other lines: the tracked line retyped with them keeps its tracking. + let mut s = session(); + let marks = outlined( + &mut s, + json!({"x": 40, "y": 100, "text": format!("x{}a", "\u{312}".repeat(20)), "size": 40, "font": "Source Sans 3", "style": "Regular"}), + ); + let mut moved: Vec = s.doc().unwrap().doc.children(Some(NodeId(marks))).unwrap().iter().map(|n| n.id.0).collect(); + assert_eq!(moved.len(), 22); + moved = moved[1..21].to_vec(); + let id = s + .execute("text.create", &json!({"x": 40, "y": 300, "text": "x\u{312}yzw", "size": 40, "font": "Source Sans 3", "style": "Regular"})) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 5, "tracking": 50})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let tracked = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mark = s.doc().unwrap().doc.children(Some(NodeId(tracked))).unwrap()[1].id.0; + moved.push(mark); + s.execute("select.set", &json!({"ids": moved})).unwrap(); + s.execute("object.move", &json!({"dx": 3, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [marks, tracked]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + let texts = r["texts"].as_array().unwrap(); + let at = texts.iter().position(|t| t == "yzw").unwrap_or_else(|| panic!("yzw in {r}")); + assert_eq!(r["fonts"][at]["tracking"], json!(50.0), "{r}"); + let mut left: Vec = r["unmatched"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + left.sort_unstable(); + moved.sort_unstable(); + assert_eq!(left, moved, "{r}"); +} + #[test] fn mixed_selection_retypes_the_glyphs_and_keeps_the_rest() { let mut s = session(); @@ -1777,7 +1936,7 @@ fn the_glyphs_after_one_type_cannot_draw_keep_their_tracking() { l.matches[bad].gid = other; let bad_id = l.pieces[bad]; let mut unmatched = vec![]; - let out = super::verified(vec![l], false, &mut unmatched); + let out = super::verified(vec![l], false, &Default::default(), &mut unmatched); assert_eq!(unmatched, vec![bad_id], "{bad}"); let last = out.last().unwrap(); assert_eq!(last.pieces.len(), 5 - bad, "{bad}: {:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); @@ -1829,7 +1988,7 @@ fn the_rest_of_a_widely_tracked_line_keeps_its_tracking_after_a_split() { assert_eq!(l.tracking, 8000.0); l.matches[0].gid += 1; let mut unmatched = vec![]; - let out = super::verified(vec![l], false, &mut unmatched); + let out = super::verified(vec![l], false, &Default::default(), &mut unmatched); assert_eq!(unmatched.len(), 1); let last = out.last().unwrap(); assert_eq!((last.pieces.len(), last.tracking), (99, 8000.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); @@ -1851,7 +2010,7 @@ fn glyphs_type_cannot_draw_do_not_use_up_the_tracking_measure() { m.gid += 1; } let mut unmatched = vec![]; - let out = super::verified(vec![l], false, &mut unmatched); + let out = super::verified(vec![l], false, &Default::default(), &mut unmatched); assert_eq!(unmatched.len(), 5); let last = out.last().unwrap(); assert_eq!((last.pieces.len(), last.tracking), (95, 300.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); @@ -1944,7 +2103,7 @@ fn a_long_run_after_a_split_keeps_a_tracking_under_one_unit_that_adds_up() { assert!(near(l.tracking, 0.2, 0.01), "{}", l.tracking); l.matches[0].gid += 1; let mut unmatched = vec![]; - let out = super::verified(vec![l], false, &mut unmatched); + let out = super::verified(vec![l], false, &Default::default(), &mut unmatched); assert_eq!(unmatched.len(), 1); let last = out.last().unwrap(); assert!(last.pieces.len() == 399 && near(last.tracking, 0.2, 0.01), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); @@ -1974,7 +2133,7 @@ fn a_long_rest_tracked_past_a_negative_space_advance_keeps_its_word_spaces_after assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking), "{times}"); l.matches[0].gid += 1; let mut unmatched = vec![]; - let out = super::verified(vec![l], false, &mut unmatched); + let out = super::verified(vec![l], false, &Default::default(), &mut unmatched); assert_eq!(unmatched.len(), 1, "{times}"); let texts: Vec<(&str, f64)> = out.iter().map(|l| (l.text.as_str(), l.tracking)).collect(); assert_eq!(texts, vec![(&text[1..], tracking)], "{times}"); @@ -2011,7 +2170,7 @@ fn a_long_rest_with_a_positive_pair_kerning_that_matches_a_space_gains_no_space_ assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking)); l.matches[0].gid += 1; let mut unmatched = vec![]; - let out = super::verified(vec![l], false, &mut unmatched); + let out = super::verified(vec![l], false, &Default::default(), &mut unmatched); assert_eq!(unmatched.len(), 1); let texts: Vec<(&str, f64)> = out.iter().map(|l| (l.text.as_str(), l.tracking)).collect(); assert_eq!(texts, vec![(&text[1..], tracking)]); @@ -2131,7 +2290,7 @@ fn a_long_tightly_tracked_rest_keeps_its_word_spaces_after_a_split() { assert_eq!((l.text.as_str(), l.tracking), (text.as_str(), tracking)); l.matches[0].gid += 1; let mut unmatched = vec![]; - let out = super::verified(vec![l], false, &mut unmatched); + let out = super::verified(vec![l], false, &Default::default(), &mut unmatched); assert_eq!(unmatched.len(), 1); let texts: Vec<(&str, f64)> = out.iter().map(|l| (l.text.as_str(), l.tracking)).collect(); assert_eq!(texts, vec![(&text[1..], tracking)]); diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index dc33c46ab1..2640433606 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec { "List Script File Permissions", [], None, - "{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web)}", + "{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web)}; a missing grants file lists none, and one that is there but cannot be read, is too large, is not a grants file of this version or holds no list of grants, or whose lock cannot be taken, is an error (a grant in it that is not well formed is left out)", always, grants ), @@ -369,7 +369,8 @@ fn grants(s: &mut Session, _: &Value) -> Result { let Some(dir) = s.script_data_dir() else { return Ok(json!({"grants": [], "file": null})) }; let file = dir.with_file_name(script::files::GRANTS_FILE); // A script or a granted path outside the automation read roots is named by its file name alone. - let mut grants = script::files::stored_grants(dir); + let mut grants = + script::files::stored_grants(dir).map_err(|e| EngineError::Other(format!("the script file permissions could not be read: {e}")))?; for g in &mut grants { for key in ["script", "path"] { if let Some(name) = g[key].as_str().and_then(hidden_name) { diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index cb5d1fd374..78e56e8f33 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -11,7 +11,7 @@ use vectorcraft_geom::PathData; use vectorcraft_tools::builder::is_live_paint; use super::appearance::{ItemTarget, edit_items, item_target}; -use super::paint::{live_paint_covered, live_paint_parts_skipped, painted}; +use super::paint::{live_paint_parts_skipped, painted}; use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ok, str_param}; use crate::DocState; use crate::inspect::{ALIGNS, CAPS, JOINS, StrokeMixed, node_stroke, scale_layer}; @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, target?: \"object\"|\"contents\", 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)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. 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 stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, target?: \"object\"|\"contents\", 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)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. 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 (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", has_doc, stroke_set ), @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Stroke Weight Up", [], Some("Cmd+Alt+."), - "{ids?|id?} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke, and a Live Paint group's faces, are left alone. With nothing selected (and no ids), the weight of the next object drawn, and so while the Live Paint Bucket is the active tool and no ids or id are given (a null one counts as none). On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row 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) → {objects}", + "{ids?|id?, defaultsOnly?: bool (as stroke.set)} raise each selected stroke's weight by one step of Units › Stroke (a quarter unit below one unit, then whole units; up to 1000 pt), each from its own weight: the selected objects' active or top stroke, type's stroked characters; objects without a stroke, and a Live Paint group's faces, are left alone. With nothing selected (and no ids), the weight of the next object drawn, and so 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. On a path directly in a graph series, the graph also stores the new weight of the topmost visible stroke, and on a graph label the new weight of its characters' stroke or its stroke row 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) → {objects}", has_doc, |s, p| stroke_step(s, p, true) ), @@ -41,7 +41,7 @@ pub fn specs() -> Vec { "Stroke Weight Down", [], Some("Cmd+Alt+,"), - "{ids?|id?} lower each selected stroke's weight by one step, as stroke.weightUp raises it, down to a quarter unit (a thinner weight is kept) → {objects}", + "{ids?|id?, defaultsOnly?: bool (as stroke.set)} lower each selected stroke's weight by one step, as stroke.weightUp raises it, down to a quarter unit (a thinner weight is kept) → {objects}", has_doc, |s, p| stroke_step(s, p, false) ), @@ -50,7 +50,7 @@ pub fn specs() -> Vec { "Stroke Options", [], None, - "{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn, and so while the Live Paint Bucket is the active tool and no ids, id, item or brush are given, a null ids or id counting as none; without item, a Live Paint group's edges take them and its faces are left alone)", + "{arrowScale?: [start %, end %], swapArrows?: bool, flipProfile?: \"along\"|\"across\", brush?: name|null, item?: stroke item index|null, aligned?: bool (as stroke.set), ids?|id?, defaultsOnly?: bool (as stroke.set; refused with brush), target?: \"object\"|\"contents\"} Stroke panel extras (with nothing selected, all but brush set up the next object drawn, and so while the Live Paint Bucket is the active tool, or with `defaultsOnly: true`, and no ids, id, item or brush are given, a null ids or id counting as none; without item, a Live Paint group's edges take them and its faces are left alone)", has_doc, stroke_advanced ), @@ -465,7 +465,7 @@ impl Session { // A Live Paint group without edges shows the next selected object's stroke; any other object // without a painted object shows none. A face or edge selected with its Live Paint group counts // with the group, wherever it is in the selection. - let covered = live_paint_covered(&st.doc, &st.selection.objects); + let covered = st.selection_live_paint_covered(&st.selection.objects); for id in st.selection.objects.iter().filter(|id| !covered.contains(*id)) { let Some(n) = st.doc.node(*id) else { continue }; let mut nodes = vec![]; @@ -540,7 +540,7 @@ impl DocState { } else { let selected: Vec<&Node> = self.selection.objects.iter().filter_map(|id| self.doc.node(*id)).collect(); // The faces and edges of the selected Live Paint groups: selected as well, they count with their group's. - let covered = live_paint_covered(&self.doc, &self.selection.objects); + let covered = self.selection_live_paint_covered(&self.selection.objects); for n in selected.into_iter().filter(|n| !covered.contains(&n.id)) { painted(n, true, true, &mut nodes); } @@ -618,7 +618,10 @@ fn stroke_advanced(s: &mut Session, p: &Value) -> Result { return Err(bad(C, "nothing to change")); } // As stroke.set: the stroke the Live Paint Bucket paints with changes; the selection keeps its own. - // A brush still goes to the selection. + // A brush still goes to the selection, and new art has no brush for `defaultsOnly` to set. + if brush.is_some() && super::switch_or(p, "defaultsOnly", false, C)? { + return Err(bad(C, "`defaultsOnly` cannot be combined with `brush`")); + } let bucket_p = if brush.is_none() { super::paint::bucket_color_params(s, p, C)? } else { None }; let bucket = bucket_p.is_some(); let p = bucket_p.as_ref().unwrap_or(p); diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index 1eddbef1af..c4db83826e 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -17,6 +17,7 @@ use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{Paint, Swatch, SwatchGroup, SwatchLibrary, default_swatches}; use vectorcraft_doc::pattern::pattern_paint; +use super::clipboard::resources::numbered_name; use super::fileio::{create_dir, extension, read_file, read_file_head, write_file, write_new_file}; use super::menucmds::squash; use super::package::free_name; @@ -49,7 +50,7 @@ pub fn specs() -> Vec { "Add to Swatches", ["Window", "Swatch Libraries"], None, - "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, skipping the names of the library's other swatches, and the pattern links to it → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}", + "{library: id or name, names?: [swatch or colour group names in the library] (default: all of it; a group comes as a colour group, a single swatch ungrouped), apply?: \"fill\"|\"stroke\" (also apply the first one to the selection and the defaults, as paint.setFill / paint.setStroke), focus?: true (with apply: false keeps the active proxy), defaultsOnly?: bool (with apply: apply it to the defaults only, as paint.setFill does; the journal records it for swatches applied while the Live Paint Bucket is the active tool)} copy library swatches into the document as one undo step. A swatch the document already has (same name and paint, and for a color the same process, global or spot kind, or a numbered copy of that name with the same color when the name has another color there) isn't added again; a name taken by another swatch gets a number (\"Clay 1 2\"); a tint or gradient whose global or spot color comes in under a numbered name, or is in the document as such a numbered copy, links to that copy; a global or spot color it links to that the document lacks comes in with it. A pattern swatch brings its pattern, as pasting art painted with it does: the same pattern the document has is used, also when its art links to the document's own color of a name, and a name another pattern or swatch has gets a number; a global or spot color its art links to whose name the document gives another color comes in numbered, skipping the names of the library's other swatches, and the pattern links to it, not to a numbered copy that is the library's other swatch of that name; a swatch of a numbered library name that the art brings, such as a tint \"Ink 2\" or a pattern's swatch when its pattern comes in under another name, keeps that name when the document does not use it, and a pattern swatch or a pattern the art is painted with that comes in numbered skips the library's other names too → {library, added: [names in the document, the colors patterns, tints and gradients brought included], existing: [names already there], applied?: name}", has_doc, add ), @@ -1029,55 +1030,27 @@ fn free_copy_in(taken: &mut HashSet, base: &str, reserved: impl Fn(&str) name } -/// [`patternlib::import`] of pattern `pattern` of `src` into `d`, keeping the library's numbered -/// swatch names (the keys of `names`, such as "Ink 2") that `d` does not use for the library's own -/// swatches of those names, so that a color the art brings under a numbered name does not take one -/// of them. While the import runs, a placeholder swatch holds each such name the art does not -/// bring, and a copy of the library's color holds each one the art brings, which the art then -/// takes. The placeholders are removed before it returns, and so is a copy the art did not take; -/// a copy the art took is listed with the colors the import brought. Names of the patterns the -/// import brings are not held. -fn import_holding( - d: &mut vectorcraft_doc::Document, - src: &vectorcraft_doc::Document, - pattern: &str, - names: &HashMap<&str, &Swatch>, -) -> Result<(String, patternlib::SwatchNames, patternlib::SwatchNames)> { - let numbered = |n: &str| n.rsplit_once(' ').is_some_and(|(_, k)| !k.is_empty() && k.bytes().all(|b| b.is_ascii_digit())); - let taken = taken_names(d); - let mut free: Vec<&str> = names.keys().copied().filter(|n| numbered(n) && !taken.contains(*n)).collect(); - free.sort_unstable(); - let (mut held, mut copies): (Vec, Vec) = (vec![], vec![]); - if !free.is_empty() { - let brings = patternlib::brought_names(src, pattern); - let patterns = patternlib::brought_patterns(src, pattern); - for n in free.into_iter().filter(|n| !patterns.contains(*n)) { - if !brings.contains(n) { - held.push(Swatch { name: n.to_string(), paint: Paint::None, global: false, spot: false }); - } else if let Some(w) = names.get(n).filter(|w| w.paint.color().is_some() && linked_names(&w.paint).is_empty()) { - copies.push((*w).clone()); - } +/// The name of the document's swatch for library pattern swatch `w`, whose pattern came in as +/// `target`, the import having made swatch `made` for it (removed again). A numbered name skips +/// the names of the library's other swatches (`lib_by_name`), as for a color; so does a swatch +/// named after its pattern when the pattern's name is one of them. The swatch takes the library +/// swatch's numbered name when it is free and the library has no other swatch of that name, and leaves a +/// numbered name the library gives an earlier swatch to that one. +fn pattern_swatch_name(w: &Swatch, target: &str, made: Option, taken: &mut HashSet, lib_by_name: &HashMap<&str, &Swatch>) -> String { + let reserved = |n: &str| lib_by_name.contains_key(n); + let owns = lib_by_name.get(w.name.as_str()).is_some_and(|o| *o == w); + let named_after = matches!(&w.paint, Paint::Pattern { pattern, .. } if *pattern == w.name); + match made { + _ if named_after && owns && numbered_name(&w.name) && !taken.contains(&w.name) => w.name.clone(), + _ if !owns && numbered_name(&w.name) && !taken.contains(&w.name) => { + let mut held = taken.clone(); + held.insert(w.name.clone()); + free_copy_in(&mut held, &w.name, reserved) } + Some(made) if named_after => made, + None if named_after && (target == w.name || !reserved(target)) => free_copy_in(taken, target, reserved), + _ => free_copy_in(taken, &w.name, reserved), } - let start = d.swatches.len(); - d.swatches.extend(held.iter().chain(&copies).cloned()); - let imported = patternlib::import(d, src, pattern); - let used = |n: &str| { - imported - .as_ref() - .is_ok_and(|(_, colors, took)| !colors.iter().any(|(from, _)| from == n) && !took.iter().any(|(from, to)| from == n && to != n)) - }; - let used: HashSet = copies.iter().map(|w| w.name.clone()).filter(|n| used(n)).collect(); - let mut i = 0; - d.swatches.retain(|w| { - i += 1; - let ours = held.iter().chain(&copies).any(|h| h.name == w.name && h.paint == w.paint); - !(i > start && ours && !used.contains(&w.name)) - }); - let (target, mut colors, mut took) = imported?; - took.retain(|(from, _)| !used.contains(from)); - colors.extend(copies.into_iter().map(|w| w.name).filter(|n| used.contains(n)).map(|n| (n.clone(), n))); - Ok((target, colors, took)) } /// Link the swatches of `d` that `pending` names (document name, library swatch) to their colors @@ -1175,6 +1148,7 @@ fn add(s: &mut Session, p: &Value) -> Result { Some(other) => return Err(bad(C, format!("apply is \"fill\" or \"stroke\", not `{other}`"))), }; let focus = switch_or(p, "focus", true, C)?; + switch_or(p, "defaultsOnly", false, C)?; let picked = picked(&lib, &names_param(p, C)?, C)?; // Swatches the document already has (same name and paint; for a pattern swatch, a swatch of the // same pattern) are reused, not added again. The patterns are in a built-in pattern library's @@ -1201,6 +1175,25 @@ fn add(s: &mut Session, p: &Value) -> Result { for w in lib.swatches.iter().chain(lib.groups.iter().flat_map(|g| &g.swatches)) { lib_by_name.entry(w.name.as_str()).or_insert(w); } + // A swatch a pattern's art brings under a numbered name skips the library's numbered names, + // which a later add looks up as those swatches'. Only the names a picked pattern's swatches and + // patterns can come in under, their own or one numbered after them, are needed. + let mut brings_names: HashSet = HashSet::new(); + if let Some(src) = patterns.as_ref().filter(|_| lib_by_name.keys().any(|n| numbered_name(n))) { + let picked_patterns: BTreeSet<&str> = picked + .iter() + .filter_map(|(_, w)| match &w.paint { + Paint::Pattern { pattern, .. } => Some(pattern.as_str()), + _ => None, + }) + .collect(); + for pattern in picked_patterns { + brings_names.extend(patternlib::brought_resource_names(src, pattern)); + } + } + let can_take = |n: &str| brings_names.contains(n) || n.rsplit_once(' ').is_some_and(|(base, _)| brings_names.contains(base)); + let lib_names: patternlib::Reserved = + Arc::new(lib_by_name.iter().filter(|(n, _)| numbered_name(n) && can_take(n)).map(|(n, w)| (n.to_string(), (*w).clone())).collect()); let group_names: HashSet<&str> = d.swatch_groups.iter().map(|g| g.name.as_str()).collect(); // A color whose name the document gives another color, or a color group, is the numbered copy // of it that an earlier add or a pattern's art brought in, when that copy is the same color. A @@ -1232,7 +1225,7 @@ fn add(s: &mut Session, p: &Value) -> Result { if let Some(src) = &patterns { for (_, w) in &picked { let Paint::Pattern { pattern, .. } = &w.paint else { continue }; - present.entry(pattern.as_str()).or_insert_with(|| patternlib::present_pattern(d, src, pattern)); + present.entry(pattern.as_str()).or_insert_with(|| patternlib::present_pattern(d, src, pattern, &lib_names)); } } // Whether the document's swatch `x` of the name of library swatch `w` is `w` with its colors @@ -1437,7 +1430,7 @@ fn add(s: &mut Session, p: &Value) -> Result { let mut learned = vec![]; if pending.iter().any(|(_, w)| linked_names(&w.paint).iter().any(waited)) { let mut probe = d.clone(); - let (_, colors, took) = import_holding(&mut probe, src, pattern, &lib_by_name)?; + let (_, colors, took) = patternlib::import(&mut probe, src, pattern, &lib_names)?; for (from, to) in colors_of(&probe, &colors, &took) { if let std::collections::hash_map::Entry::Vacant(e) = links.entry(from.clone()) { e.insert(to); @@ -1447,7 +1440,7 @@ fn add(s: &mut Session, p: &Value) -> Result { } let settled = settle(d, &mut pending, &links); let had = taken_names(d); - let (target, colors, took) = import_holding(d, src, pattern, &lib_by_name)?; + let (target, colors, took) = patternlib::import(d, src, pattern, &lib_names)?; // Those colors are the ones the library's tints of them link to, unless the // document already has one for them. A name the copy gave that the import // into the document did not give is replaced, and the tints linked to it are @@ -1482,11 +1475,7 @@ fn add(s: &mut Session, p: &Value) -> Result { d.swatches.retain(|x| x.name != *made); } taken = taken_names(d); - let name = match made { - Some(made) if w.name == *pattern => made, - None if w.name == *pattern => d.free_swatch_name(&target), - _ => free_in(&mut taken, &w.name), - }; + let name = pattern_swatch_name(w, &target, made, &mut taken, &lib_by_name); taken.insert(name.clone()); // The library swatch's placement of its pattern is kept. let paint = match &w.paint { @@ -1596,7 +1585,8 @@ fn add(s: &mut Session, p: &Value) -> Result { let mut out = json!({"library": shown_library_id(s, &info.id), "added": added_names, "existing": names(&existing)}); if let (Some(cmd), Some((_, first))) = (apply, picked.first()) { let name = added.iter().chain(&existing).find(|(l, _)| *l == first.name).map_or(first.name.clone(), |(_, n)| n.clone()); - s.execute(cmd, &json!({"swatch": name, "focus": focus}))?; + let only = super::paint::defaults_only(s, p, C)?; + s.execute(cmd, &super::paint::with_defaults_only(json!({"swatch": name, "focus": focus}), only))?; // Adding and applying undo together. squash(s, undo_before, "Add to Swatches"); out["applied"] = json!(name); diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 1b0766e658..734e7fd972 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -1895,14 +1895,21 @@ enum Step { /// The Type tool's selected text while it edits (its typing session ends first: one undo step, /// with typing that Real-time Drawing off left unapplied applied first). pub(crate) fn editing_range(s: &mut Session) -> Result> { - let o = s.tool_options(); - let Some(id) = o.get("editing").and_then(Value::as_u64).map(NodeId) else { return Ok(None) }; + let Some(range) = selected_range(s) else { return Ok(None) }; if super::edit::typing_in_progress(s) { s.set_tool_option("commitTyping", &Value::Bool(true)); super::edit::settle_interaction(s)?; } + Ok(Some(range)) +} + +/// The Type tool's selected text while it edits, as [`editing_range`] reads it, with its typing +/// session left running. +pub(crate) fn selected_range(s: &Session) -> Option<(NodeId, usize, usize)> { + let o = s.tool_options(); + let id = o.get("editing").and_then(Value::as_u64).map(NodeId)?; let at = |k: &str| byte_param(&o, k).unwrap_or(0); - Ok(Some((id, at("start"), at("end")))) + Some((id, at("start"), at("end"))) } /// The frames of the story whose whole text the Type tool has selected after Select All in a diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index 006f39ac19..fcb176a793 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -30,7 +30,7 @@ pub fn specs() -> Vec { "Sample Color", [], None, - "{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool, `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); with `stop` and objects in `ids`, whatever tool is active, the stops come from the topmost fill (or stroke) of the first object that paint.editGradient edits for those ids (a compound path for its member); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", + "{color (#rrggbbaa and #rgba are refused), stroke?: bool (default: whichever proxy is active), ids?, defaultsOnly?: bool, stop?: index, clearStroke?: bool} sample a color into the active fill/stroke (and the selection; `ids: []` changes only the paint default, and so does a sample without ids while the Live Paint Bucket is the active tool or with `defaultsOnly: true` (refused with ids), `stop` included); `clearStroke: true` requires `stroke: false`, `ids: []` and no `stop`, and clears the default stroke after sampling an image into the fill; with `stop`, recolor that stop of the gradient behind the proxy instead (paint.editGradient); with `stop` and objects in `ids`, whatever tool is active, the stops come from the topmost fill (or stroke) of the first object that paint.editGradient edits for those ids (a compound path for its member); in a CMYK document an RGB color is stored as CMYK through the color settings, as paint.setFill stores it", has_doc, sample_color ), @@ -523,6 +523,10 @@ fn sample_color(s: &mut Session, p: &Value) -> Result { if clear_stroke && (stroke || p.get("stroke") != Some(&Value::Bool(false)) || p.get("ids") != Some(&json!([])) || p.get("stop").is_some()) { return Err(bad(C, "`clearStroke` requires `stroke: false`, `ids: []` and no `stop`")); } + let only = super::switch_or(p, "defaultsOnly", false, C)?; + if only && p.get("ids").is_some_and(|v| !v.is_null()) { + return Err(bad(C, "`defaultsOnly` cannot be combined with `ids`, `id` or `item`")); + } let c = p.get("color").ok_or_else(|| bad(C, "missing color"))?; let (id, mut q) = match p.get("stop") { None | Some(Value::Null) => (if stroke { "paint.setStroke" } else { "paint.setFill" }, json!({ "color": c })), @@ -532,7 +536,9 @@ fn sample_color(s: &mut Session, p: &Value) -> Result { let (paint, source) = match given_stop_paint(s, p, stroke)? { Some(paint) => (paint, "the paint of the first object in `ids`"), None => { - let (fill, stroke_paint) = s.proxy_paints(); + // The default's gradient with `defaultsOnly`, as the proxies show it while the Live + // Paint Bucket paints. + let (fill, stroke_paint) = if only { (s.paint.fill.clone(), s.paint.stroke.clone()) } else { s.proxy_paints() }; (if stroke { stroke_paint } else { fill }, "the paint behind the proxy") } }; @@ -548,6 +554,7 @@ fn sample_color(s: &mut Session, p: &Value) -> Result { if let Some(ids) = p.get("ids") { q["ids"] = ids.clone(); } + let q = super::paint::with_defaults_only(q, only); let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?; let result = super::run_checked(s, spec, &q)?; if clear_stroke { diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 39303760a3..eef620521f 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -129,6 +129,11 @@ pub struct DocState { /// paths the document links to are looked at within them later too, when the Links panel /// asks about a link outside any caller's scope. pub opened_by: Option>, + /// What the commands scripts ran did to the document since the person last opened or saved it: + /// `None` when they did nothing. The commands a script runs read and write the document's file, + /// and read the files it links to, only as the person left them ([`DocState::as_person_left`]). + /// Not saved. + pub(crate) by_script: Option, /// The live-effect plug-in stages deferred while the document is drawn on screen, and the time /// budget of its first view ([`vectorcraft_plugins::deferred`]). Not saved. pub plugin_effects: vectorcraft_plugins::deferred::Deferrals, @@ -145,6 +150,50 @@ pub struct DocState { /// measured: the next refresh checks only the layer trees that differ from it /// ([`cmd::inline::refresh`]). Not saved. pub(crate) inline_resolved: Option, + /// The selected objects as [`crate::Session::select`] last checked them or the proxies last + /// read them, with the document they were checked in ([`SelectionRecord`]). Not saved. + pub(crate) selection_record: Option, +} + +/// A selection of objects alone ([`objects_only`]) with the document it was checked or read in: +/// while the document and the selected objects stay the same, a command that adds objects checks +/// and reads only the added ones. +#[derive(Clone, Debug)] +pub(crate) struct SelectionRecord { + /// The document, held as [`EmptyArtboards::doc`] holds it. + pub(crate) doc: std::sync::Weak, + pub(crate) objects: Vec, + /// Lock Guides as it was when [`crate::Session::select`] left these objects selected; `None` + /// when it did not. + pub(crate) settled: Option, + /// What the proxies read from these objects; `None` when they were not read. + pub(crate) paints: Option, +} + +/// Whether `sel` holds selected objects and nothing else: no anchors, segments, key, target, +/// slices, ruler guides, object of a symbol instance's art or object on a path. +pub(crate) fn objects_only(sel: &Selection) -> bool { + sel.anchors.is_empty() + && sel.segments.is_empty() + && sel.key.is_none() + && sel.target.is_none() + && sel.slices.is_empty() + && sel.guides.is_empty() + && sel.key_guide.is_none() + && sel.key_anchor.is_none() + && sel.symbol_part.is_none() + && sel.on_path_member.is_none() +} + +/// What the commands scripts ran did to an open document since the person last opened or saved it +/// ([`DocState::by_script`]). +#[derive(Clone, Debug)] +pub(crate) enum ByScript { + /// A command a script ran opened it (or made it). + Opened, + /// A command a script ran changed it or gave it another file: the document, its file and the + /// file it was read from as they were before the first such command. + Changed { doc: Arc, path: Option, links_from: Option }, } /// Whether a document has an artboard for Delete Empty Artboards to delete, with the document that @@ -385,11 +434,77 @@ impl DocState { links_from: None, last_perspective: None, opened_by: file_access::current(), + by_script: None, empty_artboards: Default::default(), plugin_effects: Default::default(), art_to_fit: Default::default(), measured_in_own: None, inline_resolved: None, + selection_record: None, + } + } + /// The [`SelectionRecord`] of the selection now: `None` when the document or the selected + /// objects changed since it was made, or when anything besides whole objects is selected + /// ([`objects_only`]). Only a new [`Document`] makes the record stale: the document's new art + /// is the one state that changes in place and matters to it, and [`crate::Session::select`] + /// checks the whole selection while there is new art. + pub(crate) fn selection_record(&self) -> Option<&SelectionRecord> { + self.selection_record + .as_ref() + .filter(|r| std::ptr::eq(r.doc.as_ptr(), Arc::as_ptr(&self.doc)) && objects_only(&self.selection) && r.objects == self.selection.objects) + } + /// What the proxies read from the selected objects, when the [`SelectionRecord`] of the + /// selection now holds it. + pub(crate) fn selection_paints(&self) -> Option<&cmd::SelectionPaints> { + self.selection_record().and_then(|r| r.paints.as_ref()) + } + /// Keep the [`SelectionRecord`] of the selection that [`crate::Session::select`] left, with + /// Lock Guides `guides_locked`. `record` is the record of the selection before: when the + /// selected objects start with its objects, the added objects are read into its paints. + pub(crate) fn record_selection(&mut self, record: Option, guides_locked: bool) { + if !objects_only(&self.selection) { + self.selection_record = None; + return; + } + let objects = &self.selection.objects; + self.selection_record = Some(match record { + Some(mut r) if objects.starts_with(&r.objects) => { + let added = &objects[r.objects.len()..]; + if let Some(p) = &mut r.paints { + p.add(&self.doc, added); + } + r.objects.extend_from_slice(added); + r.settled = Some(guides_locked); + r + } + _ => SelectionRecord { doc: Arc::downgrade(&self.doc), objects: objects.clone(), settled: Some(guides_locked), paints: None }, + }); + } + + /// The document, its file and the file it was read from as the person last left them, for the + /// commands scripts run ([`DocState::by_script`]): `None` for a document a script's command + /// opened. + pub(crate) fn as_person_left(&self) -> Option<(&Arc, Option<&str>, Option<&str>)> { + match &self.by_script { + None => Some((&self.doc, self.path.as_deref(), self.links_from.as_deref())), + Some(ByScript::Opened) => None, + Some(ByScript::Changed { doc, path, links_from }) => Some((doc, path.as_deref(), links_from.as_deref())), + } + } + + /// Notes what a command a script ran did to the document, which was `was` (the document, its + /// file and the file it was read from) before the command ran, or not open when `was` is + /// `None`. The first change is kept until the person saves the document. + pub(crate) fn note_script_command(&mut self, was: Option<(&Arc, &Option, &Option)>) { + if self.by_script.is_some() { + return; + } + let Some((doc, path, links_from)) = was else { + self.by_script = Some(ByScript::Opened); + return; + }; + if !Arc::ptr_eq(doc, &self.doc) || *path != self.path || *links_from != self.links_from { + self.by_script = Some(ByScript::Changed { doc: doc.clone(), path: path.clone(), links_from: links_from.clone() }); } } /// `measure`'s answer for the document now. `measure` runs once for each version of the document, diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index abc7fa0740..c96bf81084 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -27,7 +27,8 @@ //! [`ScriptScope`] holds the folders a running script's own files (its includes and `$.evalFile`) //! are read from, and the places its `File` and `Folder` objects read and write, inside the roots. //! [`ScriptGate`] holds the same places for the commands the script runs with `vc.run`, with the -//! files of the open documents. +//! files of the open documents, and for reading, the files the documents open when the run began +//! link to, each as the person last left the document. use std::cell::RefCell; use std::ffi::OsString; @@ -276,19 +277,56 @@ impl ScopeHandle { /// What a command a running script runs (`vc.run`) may read and write: the places the script's /// `File` and `Folder` objects may ([`ScriptScope`]), and the files the documents open in the app -/// were opened from or saved to. The automation roots apply as well. A path refused by its name -/// alone ([`ScriptScope::refused_by_name`]) is refused here too. +/// were opened from or saved to by the person ([`crate::DocState::as_person_left`]). Reading, and +/// only reading, the files the documents link to as the person left them when the run began is +/// allowed as well ([`ScriptGate::linked`]). The automation roots apply as well. A path refused by +/// its name alone ([`ScriptScope::refused_by_name`]) is refused here too. #[derive(Clone, Debug)] pub(crate) struct ScriptGate { pub(crate) read: ScriptScope, pub(crate) write: ScriptScope, - /// The paths of the open documents' files, as the documents hold them. + /// The paths of the open documents' files, as the documents held them when the person last + /// opened or saved them. A document a script's command opened has none here. pub(crate) documents: Vec, + /// The files the documents link to as the person left them when the run began: readable, not + /// writable. + pub(crate) linked: LinkedFiles, /// Another gate a path must pass as well ([`ScopeHandle::within_current`]). pub(crate) also: Option>, } +/// The files the commands a script runs may only read because the documents open when the run +/// began link to them as the person left them ([`ScriptGate::linked`]). +#[derive(Clone, Debug, Default)] +pub(crate) struct LinkedFiles { + /// The real paths of the files, as they were when the run's first command was run, sorted. A + /// path that leads to another file now is not one of them. + files: Arc<[PathBuf]>, +} + +impl LinkedFiles { + /// Is `real`, a real path, one of the files? + fn has(&self, real: &Path) -> bool { + self.files.binary_search_by(|f| f.as_path().cmp(real)).is_ok() + } +} + impl ScriptGate { + /// The real paths of the files at `paths` that are files now, each once, for + /// [`ScriptGate::linked`]. A path refused by its name alone, and one that cannot be resolved, + /// is left out. + pub(crate) fn real_files(paths: impl IntoIterator) -> LinkedFiles { + let mut real: Vec = paths + .into_iter() + .filter(|p| !ScriptScope::refused_by_name(Path::new(p))) + .filter_map(|p| resolve(&p).ok()) + .filter(|p| p.is_file()) + .collect(); + real.sort(); + real.dedup(); + LinkedFiles { files: real.into() } + } + /// This gate with `next` at the end of its chain of `also` gates, so a path must pass every /// gate already in the chain as well as `next`. fn followed_by(&self, next: Arc) -> ScriptGate { @@ -310,7 +348,8 @@ impl ScriptGate { Access::Read => self.read.allows(&real) || self.write.allows(&real), Access::Write => self.write.allows(&real), }; - scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) + let linked = matches!(access, Access::Read) && self.linked.has(&real) && !self.read.keeps_out(&real); + scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked }); if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } } @@ -354,6 +393,11 @@ fn check_gate(path: &str, access: Access) -> Result<(), String> { GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check(path, access)) } +/// Whether this thread runs a command a script runs ([`with_script_gate`]). +pub(crate) fn in_script_command() -> bool { + GATE.with(|g| g.borrow().is_some()) +} + /// The roots in force on this thread, if any. pub fn current() -> Option> { match SCOPE.with(|s| s.borrow().clone()) { @@ -620,7 +664,13 @@ impl ScriptScope { pub(crate) fn allows(&self, real: &Path) -> bool { (self.files.iter().any(|f| inside(real, f) && real.components().count() == f.components().count()) || self.roots.iter().any(|r| inside(real, r))) - && !self.fenced.iter().any(|f| inside(real, f) && !self.open.iter().any(|o| inside(o, f) && inside(real, o))) + && !self.keeps_out(real) + } + + /// Is the real path `real` in a folder kept out ([`ScriptScope::fence`]), and not in a place + /// left open there? + fn keeps_out(&self, real: &Path) -> bool { + self.fenced.iter().any(|f| inside(real, f) && !self.open.iter().any(|o| inside(o, f) && inside(real, o))) } /// The scope of a script run from a file in the folder whose real path, with its links already @@ -920,8 +970,13 @@ mod tests { #[test] fn a_narrowed_scope_keeps_the_script_gates_of_both() { let (base, _) = folders("narrowed-gate"); - let gate = - |dir: &str| ScriptGate { read: ScriptScope::of_folder(&base.join(dir)), write: ScriptScope::default(), documents: vec![], also: None }; + let gate = |dir: &str| ScriptGate { + read: ScriptScope::of_folder(&base.join(dir)), + write: ScriptScope::default(), + documents: vec![], + linked: LinkedFiles::default(), + also: None, + }; let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); let reads = |saved: ScopeHandle, gate_here: Option| { let narrowed = match gate_here { @@ -944,7 +999,13 @@ mod tests { #[test] fn a_scope_narrowed_several_times_keeps_every_gate() { let (base, _) = folders("narrowed-thrice"); - let gate = |dir: &Path| ScriptGate { read: ScriptScope::of_folder(dir), write: ScriptScope::default(), documents: vec![], also: None }; + let gate = |dir: &Path| ScriptGate { + read: ScriptScope::of_folder(dir), + write: ScriptScope::default(), + documents: vec![], + linked: LinkedFiles::default(), + also: None, + }; let (inside, other) = (s(base.join("in/a.svg")), s(base.join("outside/secret.svg"))); let narrow = |saved: ScopeHandle, g: ScriptGate| with_script_gate(g, || saved.within_current()); let reads = |h: &ScopeHandle| h.clone().run(|| (check_read(&inside).is_ok(), check_read(&other).is_ok())); @@ -959,6 +1020,114 @@ mod tests { let _ = std::fs::remove_dir_all(base); } + /// A file an open document linked to when the run began is readable through the gate; its path + /// written with `..`, writing it, a file next to it and a file that was not there when the gate + /// was made are not allowed, and the automation roots still apply. + #[test] + fn a_gate_reads_only_the_linked_files_it_was_given() { + let (base, roots) = folders("linked"); + let (secret, other) = (base.join("outside/secret.svg"), base.join("outside/other.svg")); + std::fs::write(&other, "").unwrap(); + let later = base.join("outside/later.svg"); + let linked = ScriptGate::real_files([s(secret.clone()), s(later.clone()), s(base.join("outside"))]); + assert_eq!(linked.files.len(), 1, "a missing file and a folder are left out: {linked:?}"); + let gate = + ScriptGate { read: ScriptScope::of_folder(&base.join("in")), write: ScriptScope::default(), documents: vec![], linked, also: None }; + std::fs::write(&later, "").unwrap(); + let (read, write) = + (|p: &Path| gate.check(&s(p.to_path_buf()), Access::Read).is_ok(), |p: &Path| gate.check(&s(p.to_path_buf()), Access::Write).is_ok()); + assert!(read(&secret)); + assert!(!read(&base.join("outside/../outside/secret.svg")), "a path with `..` is refused by its name"); + assert!(!write(&secret), "linked files are not written"); + assert!(!read(&other), "a file next to a linked one"); + assert!(!read(&later), "a file made after the gate"); + assert!(!read(&base.join("outside")), "the linked file's folder"); + let g = gate.clone(); + assert!(confine(Some(&roots), || with_script_gate(g, || check_read(&s(secret.clone())).is_err())), "the roots apply first"); + let _ = std::fs::remove_dir_all(base); + } + + /// A linked file in a folder the script's scope keeps out, such as the settings folder, is not + /// read through the gate; one in a place left open there is. + #[test] + fn a_gate_reads_no_linked_file_in_a_folder_kept_out() { + let (base, _) = folders("linked-fenced"); + let (kept, open) = (base.join("outside/kept.svg"), base.join("outside/open/a.svg")); + std::fs::create_dir_all(base.join("outside/open")).unwrap(); + std::fs::write(&kept, "").unwrap(); + std::fs::write(&open, "").unwrap(); + let real = |p: &Path| resolve(&s(p.to_path_buf())).unwrap(); + let mut read = ScriptScope::of_folder(&base.join("in")); + read.fence(real(&base.join("outside")), &[real(&base.join("outside/open"))]); + let gate = ScriptGate { + read, + write: ScriptScope::default(), + documents: vec![], + linked: ScriptGate::real_files([s(kept.clone()), s(open.clone())]), + also: None, + }; + assert!(gate.check(&s(kept), Access::Read).is_err(), "in the folder kept out"); + assert!(gate.check(&s(open), Access::Read).is_ok(), "in a place left open"); + let _ = std::fs::remove_dir_all(base); + } + + /// A path read through the linked files gives no access to the file it leads to after it is + /// pointed elsewhere by a link in one of its folders. + #[test] + fn a_path_read_through_a_linked_file_gives_nothing_once_it_leads_elsewhere() { + let (base, _) = folders("linked-redirected"); + #[cfg(unix)] + let made = |target: &Path, link: &Path| std::os::unix::fs::symlink(target, link).is_ok(); + #[cfg(windows)] + let made = |target: &Path, link: &Path| std::os::windows::fs::symlink_dir(target, link).is_ok(); + #[cfg(not(any(unix, windows)))] + let made = |_: &Path, _: &Path| false; + let (first, second, via) = (base.join("outside/first"), base.join("outside/second"), base.join("outside/via")); + for dir in [&first, &second] { + std::fs::create_dir_all(dir).unwrap(); + std::fs::write(dir.join("a.svg"), "").unwrap(); + } + // Windows needs Developer Mode or elevation to make links: nothing to test without them. + if !made(&first, &via) { + eprintln!("skipped: symbolic links can't be made here"); + let _ = std::fs::remove_dir_all(base); + return; + } + let (doc, elsewhere) = (s(via.join("a.svg")), s(second.join("a.svg"))); + let gate = ScriptGate { + read: ScriptScope::default(), + write: ScriptScope::default(), + documents: vec![], + linked: ScriptGate::real_files([doc.clone()]), + also: None, + }; + assert!(gate.check(&doc, Access::Read).is_ok(), "read through the linked file"); + std::fs::remove_dir(&via).or_else(|_| std::fs::remove_file(&via)).unwrap(); + assert!(made(&second, &via)); + for (path, access) in [(&doc, Access::Read), (&doc, Access::Write), (&elsewhere, Access::Read), (&elsewhere, Access::Write)] { + assert!(gate.check(path, access).is_err(), "{path} {access:?}"); + } + let _ = std::fs::remove_dir_all(base); + } + + /// A link to a linked file read through the gate counts only while it leads to that file. + #[cfg(unix)] + #[test] + fn a_gate_refuses_a_link_that_now_leads_elsewhere() { + let (base, _) = folders("linked-moved"); + let (secret, other, link) = (base.join("outside/secret.svg"), base.join("outside/other.svg"), base.join("outside/link.svg")); + std::fs::write(&other, "").unwrap(); + std::os::unix::fs::symlink(&secret, &link).unwrap(); + let linked = ScriptGate::real_files([s(link.clone())]); + let gate = ScriptGate { read: ScriptScope::default(), write: ScriptScope::default(), documents: vec![], linked, also: None }; + assert!(gate.check(&s(link.clone()), Access::Read).is_ok() && gate.check(&s(secret.clone()), Access::Read).is_ok()); + std::fs::remove_file(&link).unwrap(); + std::os::unix::fs::symlink(&other, &link).unwrap(); + assert!(gate.check(&s(link.clone()), Access::Read).is_err(), "the link leads to another file now"); + assert!(gate.check(&s(other), Access::Read).is_err()); + let _ = std::fs::remove_dir_all(base); + } + #[test] fn network_paths_are_told_by_name() { for p in [r"\\server\share\x.svg", "//server/share/x.svg", r"\\?\UNC\server\share\x.svg", r"\\?\unc\server\share"] { diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index dffc5cdb65..33ede81772 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -10,6 +10,9 @@ pub struct Interaction { pub preview: Option<(String, Value)>, /// A replaced or canceled preview restores these new-art paints from before the interaction. pub(crate) paint: vectorcraft_tools::PaintDefaults, + /// A preview of the interaction gave `defaultsOnly: true`: every later preview and a cancel put + /// `paint` back, whichever preview is the latest. + pub(crate) used_defaults_only: bool, /// An accepted batch preview uses these final paints after changing the document color mode. pub(crate) preview_paint: Option, /// Conversion of new-art paints waits until a color-mode preview is accepted. diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b0b2fd53b3..3ca9435cc8 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -107,6 +107,19 @@ pub struct Session { /// The selection tool chosen last (Selection, Direct Selection or Group Selection): the one Cmd /// lends the other tools. None until one is chosen. pub(crate) last_selection_tool: Option<&'static str>, + /// Direct Selection or Group Selection, whichever was chosen last: the one Cmd lends the + /// Selection tool. None until one is chosen. + pub(crate) last_part_selection_tool: Option<&'static str>, + /// The selection tool Cmd lent the last press, which also takes the double-click or + /// triple-click that follows it, with the uid of the document and the id of the tool it was + /// lent from: a follow-up in another document, after a tool switch (also one back to the same + /// tool) or after the tool starts afresh is not lent. None when the press was not lent. + pub(crate) press_lent: Option<(Option, &'static str, &'static str)>, + /// The selection tool a Cmd press would borrow at the pointer, as [`Session::hover_tool_at`] + /// or [`Session::cursor`] last found it with Cmd held (None inside when it found none), with + /// the document state, active tool and keys it was found for. None when it was last asked + /// without Cmd. + pub(crate) hover_lent: Option<(tooling::HoverKey, Option<&'static str>)>, pub(crate) last_view: ViewInfo, /// The selection tools' measurements for the active document as it is: a pointer move or a /// cursor asked for again over an unchanged document and selection measures nothing again. @@ -235,6 +248,11 @@ pub struct Session { /// The running top-level query command changed the selection and is journaled like any other /// command ([`Session::journal_query`]). journal_query: bool, + /// The running top-level command changed only the paint defaults, as the Live Paint Bucket + /// or `defaultsOnly: true` has a paint command do, when new art would have taken this + /// appearance (none: nothing selected): unless a later batch step changes it, the selection's + /// appearance does not replace the defaults afterwards ([`Session::inherit_new_art`]). + pub(crate) defaults_only_ran: Option>, /// From `edit.undoGroup.begin` to `edit.undoGroup.end`: the name of the undo step (`None`: after /// its first edit). Each document opened or created meanwhile opens an undo group of its own /// ([`Session::add_document`]). `None` otherwise. diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 91580248c5..990cbd25c2 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -55,6 +55,12 @@ pub struct Prefs { /// re-mapped by the turn, scale and move that take its old ends to its new ends. Off (the /// default), the handles of a moved anchor move with it and the other handles stay. pub interpolate_control_points: bool, + /// General › Delete Removes Anchor Points and Keeps Paths Joined: the default of the + /// `keepJoined` param of `edit.clear` (the Delete and Backspace keys and Edit › Clear). On, + /// Clear removes the direct-selected anchors of a path as Remove Anchor Points does, refitting + /// the curve around each one, instead of deleting them with their segments. Off (the default), + /// Clear opens the path there. + pub delete_keeps_paths_joined: bool, pub use_precise_cursors: bool, pub show_tool_tips: bool, /// General › Show Tool Cards: with tool tips on, a tool button's tool tip is a card with what the @@ -479,6 +485,7 @@ impl Default for Prefs { corner_radius: 12.0, disable_auto_add_delete: false, interpolate_control_points: false, + delete_keeps_paths_joined: false, use_precise_cursors: false, show_tool_tips: true, show_tool_cards: false, diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 94ef3bdf9e..476fbde5ad 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -54,7 +54,9 @@ //! for, loses the grant before that code runs. A run with nobody to ask gets `null` and //! [`NO_PICKER`]. //! - The commands a script runs with `vc.run` read and write only in the places above and in the -//! files of the open documents ([`crate::file_access::ScriptGate`]). +//! files the person gave the open documents ([`crate::file_access::ScriptGate`]). They also read +//! the files that the documents open when the run began link to, as the person last left those +//! documents and as those links led then. //! - `open('w')` empties the file at once; what a script writes is kept in memory, at most //! [`MAX_FILE_BYTES`] a file, and written when it closes the file or the run ends; a run writes at //! most [`MAX_RUN_BYTES`] in all and ends past that. `write` encodes in the file's encoding (an @@ -462,10 +464,11 @@ impl Disk { } } - /// The gate for a command the script runs: the places it reads and writes now, and the files of - /// the open documents, `documents`. - pub(crate) fn gate(&self, documents: Vec) -> crate::file_access::ScriptGate { - crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, also: None } + /// The gate for a command the script runs: the places it reads and writes now, the files the + /// person gave the open documents, `documents`, and the files it may only read because the documents open when + /// the run began link to them, `linked`. + pub(crate) fn gate(&self, documents: Vec, linked: crate::file_access::LinkedFiles) -> crate::file_access::ScriptGate { + crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, linked, also: None } } /// The files written since this was last asked, to name in the report. @@ -920,8 +923,15 @@ fn read_head(real: &Path, max: usize) -> std::io::Result> { /// that is not well formed is left out. It is read under [`lock_store`]'s lock, so it is read /// between two changes, and none are read when the lock cannot be taken. fn read_store(store: &Path) -> Vec { - let Ok(_lock) = lock_store(store) else { return Vec::new() }; - load_store(store, false).unwrap_or_default() + list_store(store).unwrap_or_default() +} + +/// The grants [`read_store`] reads; none when the grants file is missing, and `Err` when the lock +/// cannot be taken or the file is there but cannot be read, is too large, is not a grants file of +/// this version or holds no list of grants. +fn list_store(store: &Path) -> std::io::Result> { + let _lock = lock_store(store)?; + load_store(store, false) } /// The grants the grants file at `store` holds, to change and write back; none when it is missing, @@ -937,7 +947,8 @@ fn try_read_store(store: &Path) -> std::io::Result> { fn load_store(store: &Path, strict: bool) -> std::io::Result> { let bytes = match read_head(store, MAX_STORE_BYTES) { Ok(bytes) => bytes, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + // A link whose target is missing is there but cannot be read. + Err(e) if e.kind() == std::io::ErrorKind::NotFound && std::fs::symlink_metadata(store).is_err() => return Ok(Vec::new()), Err(e) => return Err(e), }; if bytes.len() > MAX_STORE_BYTES { @@ -955,14 +966,14 @@ fn load_store(store: &Path, strict: bool) -> std::io::Result MAX_STORED_GRANTS || !grants.iter().all(valid) { return Err(std::io::Error::other("the grants file holds a grant that cannot be read")); } return Ok(grants.clone()); } - Ok(v["grants"].as_array().map(|a| a.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()).unwrap_or_default()) + Ok(grants.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()) } /// The number in the name of the next file [`write_store`] writes before it takes the grants file's @@ -1062,9 +1073,9 @@ fn lock_store(_: &Path) -> std::io::Result { } /// The grants the grants file beside the data folder `data_dir` keeps: each script, the SHA-256 of -/// its text, the path and whether it may be written (`script.grants`). -pub(crate) fn stored_grants(data_dir: &Path) -> Vec { - read_store(&data_dir.with_file_name(GRANTS_FILE)) +/// its text, the path and whether it may be written (`script.grants`); as [`list_store`] reads them. +pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result> { + list_store(&data_dir.with_file_name(GRANTS_FILE)) } /// Removes from the grants file beside `data_dir` the grants of the script `script` and of the path diff --git a/crates/engine/src/script/include.rs b/crates/engine/src/script/include.rs index 4223d829ba..a024949a35 100644 --- a/crates/engine/src/script/include.rs +++ b/crates/engine/src/script/include.rs @@ -217,6 +217,15 @@ pub(crate) struct Files { levels: usize, /// The files `$.evalFile` is running, the script first. frames: Vec, + /// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way. + es2015: bool, +} + +/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in +/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as +/// ECMAScript 5.1 with the ExtendScript extensions. +pub(crate) fn es2015_script(path: Option<&str>) -> bool { + path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js")) } /// The output being built: its UTF-16 text, the line it is on, the units since that line began, @@ -311,9 +320,15 @@ impl Files { chain: real.into_iter().collect(), levels: 0, frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }], + es2015: es2015_script(path), } } + /// The options a file of this run is parsed with, preprocessor lines aside. + pub(crate) fn options(&self) -> Options { + Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, ..Options::default() } + } + /// The `JSINCLUDE` folders of this process: absolute folders separated by `;`. pub(crate) fn jsinclude_env() -> Vec { #[cfg(test)] @@ -456,7 +471,7 @@ impl Files { return Ok(()); } let fail = |kind, message: String, line, column| Failure { kind, message, index, file: shown.clone(), line, column }; - let options = Options { preprocessor_lines: true, max_source_units: MAX_TOTAL_BYTES, ..Options::default() }; + let options = Options { preprocessor_lines: true, ..self.options() }; let program = vectorcraft_js::parse_utf16(&units, &options).map_err(|e| fail(FailKind::Syntax, e.message, e.line, e.column))?; let mut cursor = 0usize; for d in &program.directives { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..00d0a3a371 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -799,6 +799,35 @@ struct Host { dollar: dollar::RunState, /// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it. args: RefCell<(Data, u64)>, + /// The documents open when the run began as the person last left them, each with its own file + /// and the file it was read from ([`crate::DocState::as_person_left`], + /// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files + /// they link to from them ([`Host::linked`]). + run_docs: RefCell>, + /// The files the documents open when the run began link to as the person left them + /// ([`crate::file_access::ScriptGate::linked`]). + linked: std::cell::OnceCell, +} + +/// A document open when a run began, with its own file and the file it was read from. +type RunDoc = (Arc, Option, Option); + +impl Host { + /// The files the commands the run runs may read because the documents open when the run began + /// link to them, found once, from those documents as the person left them: a link a script's + /// command added or changed, in this run or an earlier one, and a document it opened, give it + /// no file to read. + fn linked(&self) -> crate::file_access::LinkedFiles { + self.linked + .get_or_init(|| { + let docs = std::mem::take(&mut *self.run_docs.borrow_mut()); + let files = docs.iter().flat_map(|(d, path, from)| { + crate::cmd::links::files_linked(d, crate::cmd::links::LinkBase::of_files(path.as_deref(), from.as_deref())) + }); + crate::file_access::ScriptGate::real_files(files.collect::>()) + }) + .clone() + } } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -1238,9 +1267,19 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value let before: Vec<(u64, Arc, u64)> = if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() }; crate::file_access::start_recording_writes(); - // The command reads and writes only where the script's own files may, and the open documents' files. - let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect()); + // The command reads and writes only where the script's own files may, and the files the person gave + // the open documents; it also reads the files the documents open when the run began link to, as the + // person left them. A document a script's command opened gives it no file. + let documents = s.docs.iter().filter_map(|d| d.as_person_left().and_then(|(_, path, _)| path.map(str::to_string))).collect(); + let gate = host.disk.borrow().gate(documents, host.linked()); + let was: Vec<(u64, RunDoc)> = s.docs.iter().map(|d| (d.uid, (d.doc.clone(), d.path.clone(), d.links_from.clone()))).collect(); let r = crate::file_access::with_script_gate(gate, || s.execute(id, params)); + // What the command opened, changed or gave another file is not as the person left it. + for st in &mut s.docs { + let prior = was.iter().find(|(uid, _)| *uid == st.uid); + st.note_script_command(prior.map(|(_, (doc, path, from))| (doc, path, from))); + } + drop(was); // A file a command wrote before it failed is on disk all the same. let mut written = host.written.borrow_mut(); for path in crate::file_access::finish_recording_writes(r.is_ok()) { @@ -1475,7 +1514,7 @@ fn eval_file(host: &Host, args: Vec) -> std::result::Result 0 { host.placed(error, f.file, f.line, f.column) } else { error } })?; // A file without preprocessor lines is parsed here first, so its syntax error names its place. - let options = vectorcraft_js::Options { max_source_units: include::MAX_TOTAL_BYTES, ..vectorcraft_js::Options::default() }; + let options = host.files.borrow().options(); if let Err(e) = vectorcraft_js::parse(&expanded.source, &options) { host.files.borrow_mut().end_eval(); let (_, file, line, column) = expanded.map.locate(e.line, e.column); @@ -1967,11 +2006,16 @@ impl Session { // A realm made here gets the script extensions, `$` and the dialogs; a kept one has them // from its first run, and they act for the run that calls them. let fresh = realm.is_none(); - let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), ..Options::default() }; + // A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read + // code the way the script does. + let es2015 = include::es2015_script(request.file.as_deref()); + let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, ..Options::default() }; let strict = options.strict; + // A kept engine reads each run's code the way that run's script does. let mut realm = match realm { Some(mut realm) => { realm.set_limits(limits); + realm.set_es2015(es2015); realm } None => { @@ -2040,6 +2084,14 @@ impl Session { eval_strict: Cell::new(None), dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), + run_docs: RefCell::new( + self.docs + .iter() + .filter_map(DocState::as_person_left) + .map(|(doc, path, from)| (doc.clone(), path.map(str::to_string), from.map(str::to_string))) + .collect(), + ), + linked: std::cell::OnceCell::new(), }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { @@ -2065,6 +2117,7 @@ impl Session { Ok(expanded) => { *host.script_map.borrow_mut() = expanded.map; realm.set_strict_writes(expanded.strict == Some(true)); + realm.set_script_name(Some(host.name.to_string())); if fresh { let l = link.clone(); realm.set_source_locator(Rc::new(move |tag, line| match current(&l) { @@ -2073,6 +2126,7 @@ impl Session { })); } (if fresh { realm.add_script_extensions() } else { Ok(()) }) + .and_then(|()| if fresh { realm.add_unit_values() } else { Ok(()) }) .and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) }) .and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) }) .and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) }) diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index c29705c364..d924813def 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -69,6 +69,9 @@ impl Session { selection_at_lend: None, lent_selection: None, last_selection_tool: None, + last_part_selection_tool: None, + press_lent: None, + hover_lent: None, last_view: ViewInfo::default(), preview_memo: Default::default(), depth: 0, @@ -118,6 +121,7 @@ impl Session { journal_note: Default::default(), note_depth: 1, journal_query: false, + defaults_only_ran: None, explicit_undo_group: None, batch_stash: None, batch_steps: None, @@ -210,6 +214,7 @@ impl Session { return; } self.press_type_selection = None; + self.press_lent = None; let view = self.last_view; // The edit the tool computes on another thread and the input held for it belong to the // document being left. The switch goes on whatever they did, as for the deactivation. @@ -416,6 +421,8 @@ impl Session { st.opened_as_tab = old.opened_as_tab; st.revision = old.revision + 1; st.format = old.format; + // What scripts' commands did to the document stays until the person saves it. + st.by_script = old.by_script.clone(); st.save_options = old.save_options.clone(); // The remembered artboard pick follows the artboards it named when the file read back has // the artboards the document had at the save, in the same order and with the same ids (a diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 4dd3309b9d..2504d8984a 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -1,7 +1,8 @@ use super::{ - Arc, Document, EngineError, Interaction, LastTransform, NamedStep, Result, Selection, Session, TOO_DEEP, Value, cmd, deselect_hidden, doc_sane, - objects_in_range, + Arc, Document, EngineError, Interaction, LastTransform, NamedStep, NodeKind, Result, Selection, Session, TOO_DEEP, Value, cmd, deselect_hidden, + doc_sane, objects_in_range, }; +use crate::doc_state::objects_only; impl Session { /// Run `f` on a mutable copy of the active document. Outside an interaction this records one @@ -210,14 +211,32 @@ impl Session { let st = self.doc_mut()?; let before = st.selection.objects.clone(); let new_art = st.selection.new_art.clone(); + let record = if st.selection_record().is_some() { st.selection_record.take() } else { None }; f(&st.doc, &mut st.selection); - st.selection.prune(&st.doc); - // Lock Guides locks the paths made into guides too (#1534), and Lock Slices and Hide - // Slices keep the slices out, whatever selects them. - deselect_hidden(&menu, &st.doc, &mut st.selection); - // The art on a locked artboard can't be selected, whatever selects it, except new art - // that was selected and still is. - st.protect_locked_artboards(&before, &new_art, None); + let added = objects_only(&st.selection) && st.selection.objects.starts_with(&before); + // Objects added to objects this checked in the same document, with Lock Guides as it was + // then and no art on a locked artboard to protect, are checked alone, by the rules `prune` + // and `deselect_hidden` apply to an object. + let settled = record.as_ref().is_some_and(|r| r.settled == Some(menu.guides_locked)) + && st.selection.new_art.is_empty() + && st.doc.new_art.get().is_empty() + && !st.doc.artboards.iter().any(|a| a.locked); + if added && settled { + let doc = &st.doc; + let tail = st.selection.objects.split_off(before.len()); + st.selection.objects.extend(tail.into_iter().filter(|id| { + doc.node(*id).is_some_and(|n| !n.is_ruler_guide() && !(menu.guides_locked && matches!(n.kind, NodeKind::Path { guide: true, .. }))) + })); + } else { + st.selection.prune(&st.doc); + // Lock Guides locks the paths made into guides too (#1534), and Lock Slices and Hide + // Slices keep the slices out, whatever selects them. + deselect_hidden(&menu, &st.doc, &mut st.selection); + // The art on a locked artboard can't be selected, whatever selects it, except new art + // that was selected and still is. + st.protect_locked_artboards(&before, &new_art, None); + } + st.record_selection(record, menu.guides_locked); // Selecting art makes its layer (or sublayer) the current one, as in the Layers panel of // the reference app: new art then goes beside it. if st.selection.objects != before @@ -309,6 +328,7 @@ impl Session { selection: Arc::new(st.selection.clone()), preview: None, paint, + used_defaults_only: false, preview_paint: None, color_mode_paints: None, deferred_color_mode: None, @@ -331,7 +351,8 @@ impl Session { return Err(EngineError::Busy); } // While the Live Paint Bucket is active, paint previews change only the bucket's colors, so - // each preview starts from the colors the interaction began with. + // each preview starts from the colors the interaction began with; so does a preview with + // `defaultsOnly: true`, and one after it. let bucket = self.bucket_paints(); let (paint, restore_paint) = { let menu = self.menu.clone(); @@ -346,9 +367,11 @@ impl Session { st.doc = it.doc.clone(); // A batch, or a preview that changed the new-art paints (a pattern rename), started from // the paints the interaction began with. + it.used_defaults_only |= cmd::asks_defaults_only(params); let restore_paint = bucket || cmd == "command.batch" - || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") + || it.used_defaults_only + || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) || it.color_mode_paints.is_some(); let paint = it.paint.clone(); it.preview_paint = None; @@ -378,6 +401,8 @@ impl Session { let outer = std::mem::replace(&mut self.previewing, true); let r = self.execute(cmd, params); self.previewing = outer; + // A step inside a batch that changed only the defaults counts as well. + let ran_defaults_only = self.defaults_only_ran.is_some(); if let Some(paint) = color_mode_paint { self.paint = paint; } @@ -385,6 +410,7 @@ impl Session { let batch_paint = (r.is_ok() && cmd == "command.batch").then(|| self.paint.clone()); let st = self.doc_mut()?; if let Some(it) = &mut st.interaction { + it.used_defaults_only |= ran_defaults_only; // A failed preview leaves the document at the snapshot, so nothing is left to commit // (not even an earlier successful preview, which the reset above already undid). it.preview = r.is_ok().then(|| (cmd.to_string(), params)); @@ -505,12 +531,18 @@ impl Session { self.decoded_images.empty(); self.pending_paint = None; // While the Live Paint Bucket is active, a previewed color is the bucket's color, which the - // cancel puts back as well. + // cancel puts back as well, as it does a color previewed with `defaultsOnly: true`. let bucket = self.bucket_paints(); + let used_defaults_only = self.active().and_then(|st| st.interaction.as_ref()).is_some_and(|it| it.used_defaults_only); if let Some(paint) = self .active() .and_then(|st| st.interaction.as_ref()) - .filter(|it| bucket || it.preview.as_ref().is_some_and(|(id, _)| id == "command.batch") || it.color_mode_paints.is_some()) + .filter(|it| { + bucket + || it.used_defaults_only + || it.preview.as_ref().is_some_and(|(id, p)| id == "command.batch" || cmd::asks_defaults_only(p)) + || it.color_mode_paints.is_some() + }) .map(|it| it.paint.clone()) { self.paint = paint; @@ -523,8 +555,11 @@ impl Session { // A canceled preview's Assign Profile is undone with it. self.sync_front_profiles(); // With New Art Has Basic Appearance off, new art takes the appearance of the selection as - // the document has it again, not as a preview left it. - self.inherit_new_art(); + // the document has it again, not as a preview left it. An interaction that changed only the + // defaults (`defaultsOnly: true`) leaves the defaults it began with. + if !used_defaults_only { + self.inherit_new_art(); + } Ok(()) } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 9900d61482..a6d2faec6d 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -185,6 +185,7 @@ impl Session { self.journal_note.clear(); self.note_depth = 1; self.journal_query = false; + self.defaults_only_ran = None; self.batch_stash = None; self.batch_steps = None; } @@ -287,8 +288,9 @@ impl Session { } /// Record `key: value` in the running top-level command's journal entry (or its interaction's - /// preview, or its step in a batch) unless its params give `key` (a null gives nothing): a value - /// it resolved from the preferences or the clock. + /// preview, or its step in a batch) unless its params give `key` (a null gives nothing, and a + /// noted `defaultsOnly` replaces the params' own): a value it resolved from the preferences or + /// the clock. pub fn note_journal(&mut self, key: &str, value: Value) { if self.depth == self.note_depth { self.journal_note.insert(key.to_string(), value); @@ -383,10 +385,11 @@ impl Session { let mut note = std::mem::take(&mut self.journal_note); match params { // The params' own values win, except a null: it reads as a key left out, so the - // noted value is the one the command resolved. + // noted value is the one the command resolved. A noted `defaultsOnly` wins too: the + // Live Paint Bucket kept the command to the defaults although the params gave `false`. Value::Object(m) if !note.is_empty() => { for (k, v) in m { - if !v.is_null() || !note.contains_key(k) { + if (!v.is_null() && k != "defaultsOnly") || !note.contains_key(k) { note.insert(k.clone(), v.clone()); } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e524d1c63c..9e22f5034e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -49,6 +49,7 @@ mod curvature_circle; mod cut; mod dashalign; mod dcs; +mod delete_keeps_joined; mod distort; mod docsetup; mod document_close; @@ -123,6 +124,7 @@ mod outlineobject; pub(super) mod outlinestroke; mod overprint; mod package; +mod paintopacity; mod paintproxy; mod panelcmds; mod paragraphs; diff --git a/crates/engine/src/tests/assets_3d.rs b/crates/engine/src/tests/assets_3d.rs index 1a647fb798..05141e2cb9 100644 --- a/crates/engine/src/tests/assets_3d.rs +++ b/crates/engine/src/tests/assets_3d.rs @@ -301,8 +301,9 @@ fn export_3d_paints_mapped_graphics_on_their_caps_in_every_format() { assert!(is_red(pixel(back, at(20.0), 64)) && is_blue(pixel(back, 64, 64)), "{:?}", pixel(back, 64, 64)); // The USDA's front cap shows the front picture through st, up from the picture's bottom. let usda = String::from_utf8(out[0].1.clone()).unwrap(); - assert_eq!(usda.matches("primvars:st").count(), 2); + assert_eq!(usda.matches("UsdUVTexture").count(), 2); assert_eq!(usda.matches("def Mesh").count(), 3, "the walls, the front cap and the back cap"); + assert_eq!(usda.matches("texCoord2f[] primvars:st").count(), 3, "every mesh carries texture coordinates"); // glTF holds both pictures, and a cap's coordinates stay inside its picture. let (mut s, _) = mapped("gltf"); let out = files(&run(&mut s, "assets.export3D", json!({}))); @@ -354,7 +355,7 @@ fn export_3d_paints_graphics_mapped_onto_a_revolves_side_in_every_format() { let middle = (150.0 * scale) as u32; assert!(is_red(pixel(picture, 256, middle)) && is_blue(pixel(picture, 10, 10)), "{:?}", pixel(picture, 256, middle)); let usda = String::from_utf8(out[0].1.clone()).unwrap(); - assert_eq!((usda.matches("def Mesh").count(), usda.matches("primvars:st").count()), (1, 1), "the side is the only face"); + assert_eq!((usda.matches("def Mesh").count(), usda.matches("UsdUVTexture").count()), (1, 1), "the side is the only face"); // Moved 50 pt around the axis, the graphic moves as far across the picture. let (mut s, _) = revolved("usda", json!({}), 50.0); let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 512}))); @@ -381,7 +382,8 @@ fn a_partial_revolve_keeps_its_cut_sides_plain_beside_its_textured_side() { let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::>(), ["Ball.usda", "Ball-texture-1.png"]); let usda = String::from_utf8(out[0].1.clone()).unwrap(); - assert_eq!((usda.matches("def Mesh").count(), usda.matches("primvars:st").count()), (2, 1), "the cut sides and the side"); + assert_eq!((usda.matches("def Mesh").count(), usda.matches("UsdUVTexture").count()), (2, 1), "the cut sides and the side"); + assert_eq!(usda.matches("texCoord2f[] primvars:st").count(), 2, "the plain cut sides keep their own texture coordinates"); let d = &s.doc().unwrap().doc; let id = d.asset(asset).unwrap().nodes[0].0; // Without its graphics the surface is one plain mesh, as before. @@ -476,7 +478,11 @@ fn export_3d_keeps_flat_colors_without_graphics_and_refuses_bad_texture_sizes() let out = files(&run(&mut s, "assets.export3D", json!({"textureSize": 128}))); assert_eq!(out.iter().map(|(n, _)| n.as_str()).collect::>(), ["Box.obj", "Box.mtl"]); let obj = String::from_utf8(out[0].1.clone()).unwrap(); - assert!(!obj.contains("vt ") && obj.lines().filter(|l| l.starts_with("g ")).count() == 1); + assert!(!out[1].1.windows(6).any(|w| w == b"map_Kd") && obj.lines().filter(|l| l.starts_with("g ")).count() == 1); + // The plain mesh still carries a texture coordinate, 0 to 1, for every corner. + let count = |p: &str| obj.lines().filter(|l| l.starts_with(p)).count(); + assert!(count("vt ") > 0 && count("vt ") == count("v ")); + assert!(obj.lines().filter_map(|l| l.strip_prefix("vt ")).flat_map(|l| l.split(' ')).all(|v| (0.0..=1.0).contains(&v.parse::().unwrap()))); } #[test] diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 32a9db4b21..22560e5568 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3331,6 +3331,182 @@ fn live_paint_bucket_paint_and_stroke_commands_leave_the_selection_unpainted() { assert!(failed.is_empty(), "{failed:#?}"); } +/// A paint or stroke command that the Live Paint Bucket kept to its own colors is journaled with +/// `defaultsOnly: true`, also when its params gave `false`. Replaying the entry with the Selection +/// tool active changes the same defaults and leaves the selection's paint as it was, also with New +/// Art Has Basic Appearance off. Every command that fails is listed. +#[test] +fn live_paint_bucket_commands_replay_from_the_journal_with_another_tool() { + let blue = Color::from_hex("#0000ff").unwrap(); + // A Live Paint group and a rectangle, both selected, a library with a fill color, a radial + // gradient as the default fill and a 2 pt default weight. + let setup = |s: &mut Session, basic: bool| { + s.execute("appearance.setNewArtBasic", &json!({"on": basic})).unwrap(); + let g = live(s); + let art = rect(s, 300.0, 300.0, 40.0, 40.0); + s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [art.0]})).unwrap(); + let lib = s.execute("library.create", &json!({})).unwrap()["id"].as_str().unwrap().to_string(); + s.execute("select.set", &json!({"ids": [art.0]})).unwrap(); + let item = s.execute("library.add", &json!({"library": lib, "kind": "fillColor"})).unwrap()["name"].as_str().unwrap().to_string(); + s.execute("select.set", &json!({"ids": [g.0, art.0]})).unwrap(); + s.execute("paint.setFill", &json!({"gradient": {"kind": "radial"}, "defaultsOnly": true})).unwrap(); + s.paint.stroke_width = 2.0; + s.last_solid = blue; + (g, art, lib, item) + }; + let cases: Vec<(&str, Value)> = vec![ + ("paint.setFill", json!({"color": "#00ffff"})), + ("paint.setFill", json!({"color": "#00ffff", "defaultsOnly": false})), + ("paint.setStroke", json!({"color": "#00ffff"})), + ("paint.none", json!({})), + ("paint.swap", json!({})), + ("paint.default", json!({})), + ("paint.lastColor", json!({"stroke": false})), + ("paint.lastGradient", json!({"stroke": true})), + ("paint.invert", json!({"stroke": false})), + ("paint.complement", json!({"stroke": false})), + ("paint.sampleColor", json!({"color": "#00ffff", "stroke": true})), + ("paint.sampleColor", json!({"color": "#00ffff", "stroke": false, "stop": 0})), + ("paint.editGradient", json!({"stroke": false, "angle": 45})), + ("gradient.presets.apply", json!({"name": "vignette"})), + ("stroke.set", json!({"weight": 5})), + ("stroke.weightUp", json!({})), + ("stroke.weightDown", json!({})), + ("stroke.setAdvanced", json!({"arrowScale": [150, 200]})), + ("swatch.library.add", json!({"library": "web-safe-216", "names": ["#FF6600"], "apply": "fill"})), + ("library.use", json!({"kind": "fillColor"})), + ]; + let mut failed = vec![]; + for basic in [true, false] { + for (cmd, params) in &cases { + let mut params = params.clone(); + let mut a = session(); + let (_, _, lib, item) = setup(&mut a, basic); + if *cmd == "library.use" { + params["library"] = json!(lib); + params["item"] = json!(item); + } + a.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + let start = a.journal.len(); + if let Err(e) = a.execute(cmd, ¶ms) { + failed.push(format!("{cmd} {params} (basic {basic}): {e}")); + continue; + } + let Some((id, recorded)) = a.journal.since(start).last().cloned() else { + failed.push(format!("{cmd} {params} (basic {basic}): not journaled")); + continue; + }; + if recorded.get("defaultsOnly") != Some(&json!(true)) { + failed.push(format!("{cmd} {params} (basic {basic}): the journal entry {recorded} does not keep the change to the defaults")); + } + let mut b = session(); + let (g, art, _, _) = setup(&mut b, basic); + let (group, painted) = (node(&b, g), node(&b, art)); + if let Err(e) = b.replay(&id, &recorded) { + failed.push(format!("{cmd} {params} (basic {basic}): the replay failed: {e}")); + continue; + } + if node(&b, g) != group || node(&b, art) != painted { + failed.push(format!("{cmd} {params} (basic {basic}): the replay painted the selection")); + } + if (&b.paint.fill, &b.paint.stroke, b.paint.stroke_width, b.new_art_stroke()) + != (&a.paint.fill, &a.paint.stroke, a.paint.stroke_width, a.new_art_stroke()) + { + failed.push(format!("{cmd} {params} (basic {basic}): the replay left other defaults")); + } + } + } + assert!(failed.is_empty(), "{failed:#?}"); + // In a batch with New Art Has Basic Appearance off, a selection change after a `defaultsOnly` + // step still gives new art the new selection's appearance; without one, the defaults stay. + let cyan = Paint::solid(Color::from_hex("#00ffff").unwrap()); + let set_cyan = json!({"command": "paint.setFill", "params": {"color": "#00ffff", "defaultsOnly": true}}); + let mut s = session(); + let (_, art, ..) = setup(&mut s, false); + s.execute("command.batch", &json!({"commands": [set_cyan.clone()]})).unwrap(); + assert_eq!(s.paint.fill, cyan, "the defaults keep the batch's fill"); + s.execute("paint.setFill", &json!({"color": "#ff0000", "defaultsOnly": true})).unwrap(); + s.execute("command.batch", &json!({"commands": [set_cyan.clone(), {"command": "select.key", "params": {"id": art.0}}]})).unwrap(); + assert_eq!(s.paint.fill, cyan, "a new key object leaves the objects new art takes its appearance from"); + s.execute("command.batch", &json!({"commands": [set_cyan.clone(), {"command": "select.set", "params": {"ids": [art.0]}}]})).unwrap(); + assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#00ff00").unwrap()), "new art takes the newly selected fill"); + // A later step that changes the selected object's appearance gives new art that appearance. + s.execute("command.batch", &json!({"commands": [set_cyan, {"command": "transparency.set", "params": {"opacity": 40, "ids": [art.0]}}]})).unwrap(); + let green = Paint::solid(Color::from_hex("#00ff00").unwrap()); + assert_eq!((&s.paint.fill, s.paint.opacity), (&green, 0.4), "new art takes the selection's new opacity, and its fill"); + // `defaultsOnly: true` with the Selection tool: a canceled preview puts the defaults back, and + // each preview starts from the defaults the interaction began with. + let mut s = session(); + let (g, art, ..) = setup(&mut s, true); + let (group, painted, fill) = (node(&s, g), node(&s, art), s.paint.fill.clone()); + s.begin_interaction("Fill Color").unwrap(); + s.preview("paint.setFill", &json!({"color": "#123456", "defaultsOnly": true})).unwrap(); + assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#123456").unwrap())); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, fill, "the canceled color is not kept"); + s.begin_interaction("Stroke Weight").unwrap(); + for _ in 0..3 { + s.preview("stroke.weightUp", &json!({"defaultsOnly": true})).unwrap(); + } + assert_eq!(s.paint.stroke_width, 3.0, "each preview starts from 2 pt"); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.stroke_width, 2.0); + // A preview with `defaultsOnly: true` after one that set the defaults with the selection + // starts from the defaults the interaction began with too. + s.begin_interaction("Stroke Weight").unwrap(); + s.preview("stroke.set", &json!({"weight": 7})).unwrap(); + assert_eq!(s.paint.stroke_width, 7.0); + s.preview("paint.setFill", &json!({"color": "#123456", "defaultsOnly": true})).unwrap(); + assert_eq!(s.paint.stroke_width, 2.0, "the discarded preview's weight is not kept"); + s.cancel_interaction().unwrap(); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (fill.clone(), 2.0)); + assert_eq!((node(&s, g), node(&s, art)), (group, painted), "the selection keeps its paint"); + // A later preview without `defaultsOnly` leaves the interaction one that changed the defaults: + // canceling puts them back. + s.begin_interaction("Stroke Weight").unwrap(); + s.preview("stroke.weightUp", &json!({"defaultsOnly": true})).unwrap(); + s.preview("stroke.set", &json!({"weight": 7})).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.stroke_width, 2.0, "the canceled interaction's weight is not kept"); + // With New Art Has Basic Appearance off and an object selected, canceling such an interaction + // keeps the defaults it began with, not the selection's appearance. + let mut s = session(); + let (_, art, ..) = setup(&mut s, false); + s.execute("paint.setFill", &json!({"color": "#ff0000", "defaultsOnly": true})).unwrap(); + let (red, selected) = (s.paint.fill.clone(), node(&s, art)); + s.begin_interaction("Fill Color").unwrap(); + s.preview("paint.setFill", &json!({"color": "#00ffff", "defaultsOnly": true})).unwrap(); + s.preview("stroke.set", &json!({"weight": 7})).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (red, 2.0), "the defaults the interaction began with stay"); + assert_eq!(node(&s, art), selected, "the selection keeps its paint"); + // The same when the defaults-only step was inside a batch that a later preview replaced. + s.begin_interaction("Fill Color").unwrap(); + let step = json!({"command": "paint.setFill", "params": {"color": "#00ffff", "defaultsOnly": true}}); + s.preview("command.batch", &json!({"commands": [step]})).unwrap(); + s.preview("stroke.set", &json!({"weight": 7})).unwrap(); + s.cancel_interaction().unwrap(); + assert_eq!(s.paint.fill, Paint::solid(Color::from_hex("#ff0000").unwrap()), "a batch's defaults-only step is put back"); + // `defaultsOnly` is a bool, and names no objects or brush. + let (g, ..) = setup(&mut s, true); + for (cmd, params) in [ + ("paint.none", json!({"defaultsOnly": true, "ids": [g.0]})), + ("paint.none", json!({"defaultsOnly": true, "id": g.0})), + ("paint.none", json!({"defaultsOnly": true, "item": null})), + ("paint.sampleColor", json!({"color": "#00ffff", "defaultsOnly": true, "id": g.0})), + ("paint.sampleColor", json!({"color": "#00ffff", "defaultsOnly": true, "item": null})), + ("paint.setFill", json!({"color": "#00ffff", "defaultsOnly": "yes"})), + ("paint.setFill", json!({"color": "#00ffff", "defaultsOnly": true, "ids": [g.0]})), + ("stroke.set", json!({"weight": 3, "defaultsOnly": true, "item": 0})), + ("paint.sampleColor", json!({"color": "#00ffff", "defaultsOnly": true, "ids": [g.0]})), + ("paint.none", json!({"defaultsOnly": 1})), + ("stroke.setAdvanced", json!({"brush": null, "defaultsOnly": true})), + ("stroke.setAdvanced", json!({"brush": "3 pt. Round", "defaultsOnly": true})), + ] { + assert!(s.execute(cmd, ¶ms).is_err(), "{cmd} {params}"); + } +} + /// `paint.editGradient` with an `aspect` and no object to edit (the Live Paint Bucket's gradient, /// nothing selected, or a fill edit of a Live Paint group without faces) is an error that leaves the default gradient as it was, since a gradient /// fitted to each object has no aspect of its own. Named objects still take the aspect. diff --git a/crates/engine/src/tests/colorize.rs b/crates/engine/src/tests/colorize.rs index 5a108d1695..672bb4b561 100644 --- a/crates/engine/src/tests/colorize.rs +++ b/crates/engine/src/tests/colorize.rs @@ -707,6 +707,140 @@ fn a_color_image_takes_a_fill_item_as_before() { assert!(s.doc().unwrap().doc.node(id).unwrap().appearance.fill().is_some(), "a fill item, as before"); } +#[test] +fn overprint_fill_makes_a_colorized_images_color_overprint() { + let mut s = session(); + let id = image(&mut s, "gray", gray(false)); + let overprints = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().colorize_overprints(); + // Before the image is colorized it has no fill to overprint. + let r = s.execute("object.setOverprint", &json!({"fill": true})).unwrap(); + assert_eq!(r["changed"], 0); + s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); + let r = s.execute("object.setOverprint", &json!({"fill": true})).unwrap(); + assert_eq!(r["changed"], 1); + assert!(overprints(&s)); + assert_eq!(s.execute("attributes.info", &json!({})).unwrap()["overprintFill"], true); + // A second time nothing changes, and no undo step is recorded. + let r = s.execute("object.setOverprint", &json!({"fill": true})).unwrap(); + assert_eq!(r["changed"], 0); + + // Native files keep it. + let d = &s.doc().unwrap().doc; + let back = vectorcraft_format::load(&vectorcraft_format::save(d, false)).unwrap(); + assert!(back.node(id).unwrap().colorize_overprints()); + + // EPS turns overprinting on for the image's ink. + let out = s.execute("document.exportEps", &json!({"previewFormat": "none", "useArtboards": false})).unwrap(); + let bytes = vectorcraft_format::base64_decode(out["dataBase64"].as_str().unwrap()).unwrap(); + let ps = String::from_utf8_lossy(&bytes); + let (Some(on), Some(mask)) = (ps.find("true op"), ps.find("imagemask")) else { panic!("{ps}") }; + assert!(on < mask, "overprint is on before the image is drawn"); + + // A legacy .ai file writes the image mask with its fill overprint, which opens again. + let r = s.execute("file.saveCopy", &json!({"format": "ai", "aiVersion": "7"})).unwrap(); + let mut t = Session::new(); + t.execute("document.open", &json!({"name": "t.ai", "dataBase64": r["dataBase64"]})).unwrap(); + let mut opened = vec![]; + t.doc().unwrap().doc.walk(|n| { + if matches!(n.kind, NodeKind::Image(_)) { + opened.push(n.colorize_overprints()); + } + }); + assert_eq!(opened, [true]); + + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!overprints(&s), "undo makes it knock out again"); + assert_eq!(s.execute("attributes.info", &json!({})).unwrap()["overprintFill"], false); + + // Taking the color off drops its overprint, so a new color knocks out. + s.execute("object.setOverprint", &json!({"fill": true})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + assert!(!s.doc().unwrap().doc.node(id).unwrap().extras().colorize_overprint); + s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); + assert!(!overprints(&s), "a new color starts knocking out"); +} + +/// Overprint Black and Print Ink Fixes' Remove White Overprint treat a colorized image's color as +/// its fill. +#[test] +fn overprint_black_and_print_fixes_reach_a_colorized_images_color() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200, "colorMode": "cmyk"})).unwrap(); + let id = image(&mut s, "gray", gray(false)); + let overprints = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().colorize_overprints(); + s.execute("paint.setFill", &json!({"color": {"c": 0, "m": 0, "y": 0, "k": 100}})).unwrap(); + let v = s.execute("edit.colors.overprintBlack", &json!({})).unwrap(); + assert!(overprints(&s), "a black image overprints: {v}"); + s.execute("paint.setFill", &json!({"color": {"c": 0, "m": 0, "y": 0, "k": 0}})).unwrap(); + assert!(overprints(&s), "a new color keeps the flag"); + let v = s.execute("addon.color.printFixes", &json!({"removeWhiteOverprint": true})).unwrap(); + assert_eq!(v["whiteOverprintRemoved"], 1, "{v}"); + assert!(!overprints(&s), "white knocks out again"); + // A white spot ink is an ink: Remove White Overprint leaves its overprint. + s.execute("swatch.new", &json!({"name": "Opaque White", "color": {"c": 0, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Opaque White"})).unwrap(); + s.execute("object.setOverprint", &json!({"fill": true})).unwrap(); + assert!(overprints(&s), "the spot white overprints"); + let v = s.execute("addon.color.printFixes", &json!({"removeWhiteOverprint": true})).unwrap(); + assert_eq!(v["whiteOverprintRemoved"], 0, "{v}"); + assert!(overprints(&s), "the spot white keeps overprinting"); +} + +/// A flattening for a file that writes colorized images in their ink (EPS) keeps the image, and +/// without Preserve Overprints its color knocks out again, as fills do; with it, the color keeps +/// overprinting. +#[test] +fn flattening_without_preserve_overprints_drops_a_colorized_images_overprint() { + let mut s = session(); + image(&mut s, "gray", gray(false)); + s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); + s.execute("object.setOverprint", &json!({"fill": true})).unwrap(); + // A translucent square elsewhere gives the flattener something to flatten. + let square = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("transparency.set", &json!({"ids": [square], "opacity": 50})).unwrap(); + let overprints = |preserve: bool| { + let mut options = crate::cmd::flatten::FlattenOptions::preset("low").unwrap(); + (options.keeps_colorize, options.preserve_overprints) = (true, preserve); + let flat = crate::cmd::flatten::flatten_document(&s.doc().unwrap().doc, &options).unwrap().unwrap(); + let mut found = vec![]; + flat.walk(|n| { + if matches!(n.kind, NodeKind::Image(_)) { + found.push(n.colorize_overprints()); + } + }); + found + }; + assert_eq!(overprints(true), [true]); + assert_eq!(overprints(false), [false]); +} + +/// Flattening without Preserve Overprints also clears the overprint an image keeps after its +/// color was removed, so a color given to it later knocks out. +#[test] +fn flattening_without_preserve_overprints_clears_an_uncolored_images_overprint() { + let mut s = session(); + let id = image(&mut s, "gray", gray(false)); + s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap(); + s.execute("object.setOverprint", &json!({"fill": true})).unwrap(); + let square = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("transparency.set", &json!({"ids": [square], "opacity": 50})).unwrap(); + let mut d = (*s.doc().unwrap().doc).clone(); + let Some(n) = d.node_mut(id) else { panic!("the image") }; + n.extras_mut().colorize = None; + assert!(n.extras().colorize_overprint && !n.colorize_overprints(), "the flag outlives the color"); + let mut options = crate::cmd::flatten::FlattenOptions::preset("low").unwrap(); + (options.keeps_colorize, options.preserve_overprints) = (true, false); + let flat = crate::cmd::flatten::flatten_document(&d, &options).unwrap().unwrap(); + let mut found = vec![]; + flat.walk(|n| { + if matches!(n.kind, NodeKind::Image(_)) { + found.push(n.extras().colorize_overprint); + } + }); + assert_eq!(found, [false]); +} + #[test] fn colorized_images_save_and_open_with_their_color() { let mut s = session(); diff --git a/crates/engine/src/tests/delete_keeps_joined.rs b/crates/engine/src/tests/delete_keeps_joined.rs new file mode 100644 index 0000000000..8a0b625e8e --- /dev/null +++ b/crates/engine/src/tests/delete_keeps_joined.rs @@ -0,0 +1,227 @@ +//! General › Delete Removes Anchor Points and Keeps Paths Joined (`deleteKeepsPathsJoined`). With +//! it on, Delete (`edit.clear`) removes the direct-selected anchors of a path as Remove Anchor +//! Points does, without opening the path. Off (the default), Delete removes them with their +//! segments. + +use serde_json::json; +use vectorcraft_geom::{PathData, Point}; + +use super::history; +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn keep_joined(s: &mut Session, on: bool) { + s.execute("prefs.set", &json!({"key": "deleteKeepsPathsJoined", "value": on})).unwrap(); +} + +fn path_of(s: &Session, id: NodeId) -> Option { + s.doc().unwrap().doc.node(id).and_then(|n| n.path_data().cloned()) +} + +fn points(s: &Session, id: NodeId) -> Vec { + path_of(s, id).unwrap().subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p)).collect() +} + +fn create(s: &mut Session, anchors: serde_json::Value, closed: bool) -> NodeId { + NodeId(s.execute("path.create", &json!({ "anchors": anchors, "closed": closed })).unwrap()["id"].as_u64().unwrap()) +} + +fn square(s: &mut Session, x: f64) -> NodeId { + create(s, json!([{"x": x, "y": 100}, {"x": x + 100.0, "y": 100}, {"x": x + 100.0, "y": 200}, {"x": x, "y": 200}]), true) +} + +fn line(s: &mut Session, y: f64) -> NodeId { + create(s, json!([{"x": 100, "y": y}, {"x": 150, "y": y - 20.0}, {"x": 200, "y": y}, {"x": 250, "y": y + 20.0}, {"x": 300, "y": y}]), false) +} + +fn select(s: &mut Session, id: NodeId, anchors: serde_json::Value, mode: &str) { + s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors, "mode": mode})).unwrap(); +} + +fn objects(s: &Session) -> usize { + s.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, |c| c.len())).sum() +} + +#[test] +fn off_by_default_delete_opens_a_closed_path() { + let mut s = session(); + assert!(!s.prefs.delete_keeps_paths_joined); + let id = square(&mut s, 100.0); + select(&mut s, id, json!([[0, 1]]), "set"); + s.execute("edit.clear", &json!({})).unwrap(); + let path = path_of(&s, id).unwrap(); + assert!(!path.subpaths[0].closed, "the path opens where the anchor was"); + assert_eq!(path.subpaths[0].anchors.len(), 3); +} + +#[test] +fn with_the_preference_on_delete_keeps_a_closed_path_closed_and_selects_the_next_anchor() { + let mut s = session(); + keep_joined(&mut s, true); + let id = square(&mut s, 100.0); + select(&mut s, id, json!([[0, 1]]), "set"); + let before = history(&s).0; + s.execute("edit.clear", &json!({})).unwrap(); + assert_eq!(history(&s).0, before + 1, "one undo step"); + let path = path_of(&s, id).unwrap(); + assert_eq!(path.subpaths.len(), 1); + assert!(path.subpaths[0].closed, "the path stays closed"); + assert!(!points(&s, id).contains(&Point::new(200.0, 100.0)), "the selected anchor is gone"); + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects, vec![id], "the path stays selected"); + assert_eq!(st.selection.anchors[&id], [(0, 1)].into(), "the anchor after the removed one is selected"); + // A second Delete goes on along the path. + s.execute("edit.clear", &json!({})).unwrap(); + assert_eq!(points(&s, id), vec![Point::new(100.0, 100.0), Point::new(100.0, 200.0)]); +} + +#[test] +fn an_open_path_loses_an_end_anchor_and_an_interior_anchor_without_splitting() { + let mut s = session(); + keep_joined(&mut s, true); + let id = line(&mut s, 300.0); + select(&mut s, id, json!([[0, 0], [0, 2]]), "set"); + s.execute("edit.clear", &json!({})).unwrap(); + let path = path_of(&s, id).unwrap(); + assert_eq!(path.subpaths.len(), 1, "one piece"); + assert!(!path.subpaths[0].closed); + assert_eq!( + points(&s, id), + vec![Point::new(150.0, 280.0), Point::new(250.0, 320.0), Point::new(300.0, 300.0)], + "the path is shorter at its start" + ); + assert_eq!(objects(&s), 1, "no new object"); + assert_eq!(s.doc().unwrap().selection.anchors[&id], [(0, 1)].into(), "the anchor after the last removed one is selected"); + // Removing the last anchor of an open path selects the one before it. + select(&mut s, id, json!([[0, 2]]), "set"); + s.execute("edit.clear", &json!({})).unwrap(); + assert_eq!(points(&s, id), vec![Point::new(150.0, 280.0), Point::new(250.0, 320.0)], "the path is shorter at its end"); + assert_eq!(s.doc().unwrap().selection.anchors[&id], [(0, 1)].into(), "the new end anchor is selected"); +} + +#[test] +fn a_subpath_left_with_one_anchor_goes_and_the_path_stays_selected_whole() { + let mut s = session(); + keep_joined(&mut s, true); + let id = square(&mut s, 100.0); + let sq = json!({"closed": true, "anchors": [{"x": 100, "y": 100}, {"x": 200, "y": 100}, {"x": 200, "y": 200}, {"x": 100, "y": 200}]}); + let pair = json!({"closed": false, "anchors": [{"x": 300, "y": 100}, {"x": 400, "y": 100}]}); + s.execute("path.setAnchors", &json!({"id": id.0, "subpaths": [sq, pair]})).unwrap(); + select(&mut s, id, json!([[1, 0]]), "set"); + s.execute("edit.clear", &json!({})).unwrap(); + let path = path_of(&s, id).unwrap(); + assert_eq!(path.subpaths.len(), 1, "the subpath left with one anchor goes"); + assert!(path.subpaths[0].closed && path.subpaths[0].anchors.len() == 4, "the other subpath is untouched"); + let st = s.doc().unwrap(); + assert_eq!(st.selection.objects, vec![id], "the path stays selected"); + assert!(st.selection.anchors.get(&id).is_none_or(|a| a.is_empty()), "no anchor is left to go on from"); +} + +#[test] +fn a_path_left_with_fewer_than_two_anchors_is_deleted() { + let mut s = session(); + keep_joined(&mut s, true); + let id = create(&mut s, json!([{"x": 100, "y": 100}, {"x": 200, "y": 100}]), false); + let other = square(&mut s, 400.0); + select(&mut s, id, json!([[0, 1]]), "set"); + select(&mut s, other, json!([[0, 0]]), "add"); + s.execute("edit.clear", &json!({})).unwrap(); + assert!(path_of(&s, id).is_none(), "a single anchor is no path"); + assert!(path_of(&s, other).unwrap().subpaths[0].closed, "the other path keeps its other anchors joined"); + assert_eq!(s.doc().unwrap().selection.objects, vec![other]); +} + +#[test] +fn several_paths_and_an_object_selected_whole_change_in_one_undo_step() { + let mut s = session(); + keep_joined(&mut s, true); + let (a, b, whole) = (square(&mut s, 100.0), line(&mut s, 400.0), square(&mut s, 500.0)); + select(&mut s, a, json!([[0, 0]]), "set"); + select(&mut s, b, json!([[0, 1], [0, 3]]), "add"); + s.execute("select.add", &json!({"ids": [whole.0]})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let before = history(&s).0; + s.execute("edit.clear", &json!({})).unwrap(); + assert_eq!(history(&s).0, before + 1, "one undo step"); + assert!(path_of(&s, whole).is_none(), "the object selected whole is deleted"); + assert!(path_of(&s, a).unwrap().subpaths[0].closed); + assert_eq!(path_of(&s, a).unwrap().subpaths[0].anchors.len(), 3); + assert_eq!(points(&s, b), vec![Point::new(100.0, 400.0), Point::new(200.0, 400.0), Point::new(300.0, 400.0)]); + let st = s.doc().unwrap(); + assert!(st.selection.anchors.contains_key(&a) && st.selection.anchors.contains_key(&b), "both paths keep an anchor selected"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, doc, "Undo restores every path"); +} + +#[test] +fn a_compound_path_keeps_its_members_and_loses_one_left_with_no_segment() { + let mut s = session(); + keep_joined(&mut s, true); + let (outer, inner) = (square(&mut s, 100.0), create(&mut s, json!([{"x": 130, "y": 150}, {"x": 170, "y": 150}]), false)); + s.execute("select.set", &json!({"ids": [outer.0, inner.0]})).unwrap(); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + select(&mut s, outer, json!([[0, 2]]), "set"); + select(&mut s, inner, json!([[0, 0]]), "add"); + s.execute("edit.clear", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.node(inner).is_none(), "the member left with one anchor goes"); + assert_eq!(d.parent_of(outer), Some(compound), "the other member stays in the compound path"); + assert!(path_of(&s, outer).unwrap().subpaths[0].closed); + assert_eq!(path_of(&s, outer).unwrap().subpaths[0].anchors.len(), 3); +} + +#[test] +fn a_selected_segment_is_still_cut() { + let mut s = session(); + keep_joined(&mut s, true); + let id = square(&mut s, 100.0); + s.execute("select.segments", &json!({"id": id.0, "segments": [[0, 0]]})).unwrap(); + s.execute("edit.clear", &json!({})).unwrap(); + let path = path_of(&s, id).unwrap(); + assert!(!path.subpaths[0].closed, "the segment's connection is removed"); + assert_eq!(path.subpaths[0].anchors.len(), 4, "every anchor stays"); +} + +#[test] +fn the_keep_joined_param_overrides_the_preference_and_must_be_a_boolean() { + let mut s = session(); + let id = square(&mut s, 100.0); + select(&mut s, id, json!([[0, 1]]), "set"); + assert!(s.execute("edit.clear", &json!({"keepJoined": "yes"})).is_err()); + assert_eq!(path_of(&s, id).unwrap().subpaths[0].anchors.len(), 4, "a refused call changes nothing"); + s.execute("edit.clear", &json!({"keepJoined": true})).unwrap(); + assert!(path_of(&s, id).unwrap().subpaths[0].closed); + keep_joined(&mut s, true); + s.execute("edit.clear", &json!({"keepJoined": false})).unwrap(); + assert!(!path_of(&s, id).unwrap().subpaths[0].closed, "false opens the path with the preference on"); +} + +#[test] +fn a_replay_removes_anchors_as_the_recorded_step_did() { + let mut s = session(); + keep_joined(&mut s, true); + let id = square(&mut s, 100.0); + select(&mut s, id, json!([[0, 1]]), "set"); + let start = s.journal.len(); + s.execute("edit.clear", &json!({})).unwrap(); + let removed = path_of(&s, id); + assert!(removed.as_ref().is_some_and(|p| p.subpaths[0].closed), "the path stays closed"); + let (cmd, params) = s.journal.since(start).last().cloned().unwrap(); + assert_eq!(params["keepJoined"], json!(true), "{cmd}: journaled"); + s.execute("edit.undo", &json!({})).unwrap(); + keep_joined(&mut s, false); + select(&mut s, id, json!([[0, 1]]), "set"); + s.replay(&cmd, ¶ms).unwrap(); + assert_eq!(path_of(&s, id), removed); + // A step saved before the preference existed has no `keepJoined` and still opens the path. + s.execute("edit.undo", &json!({})).unwrap(); + keep_joined(&mut s, true); + select(&mut s, id, json!([[0, 1]]), "set"); + s.replay("edit.clear", &json!({})).unwrap(); + assert!(!path_of(&s, id).unwrap().subpaths[0].closed); +} diff --git a/crates/engine/src/tests/docsetup.rs b/crates/engine/src/tests/docsetup.rs index 0fdb189d67..01fc0dbff7 100644 --- a/crates/engine/src/tests/docsetup.rs +++ b/crates/engine/src/tests/docsetup.rs @@ -482,6 +482,13 @@ fn discard_white_overprint_keeps_white_overprints_in_overprint_preview() { s.execute("document.setup", &json!({"discardWhiteOverprint": false})).unwrap(); let [r, g, b, _] = centre(&s); assert!(r > 200 && g < 60 && b < 60, "a white overprint vanishes: {:?}", [r, g, b]); + // A white spot ink is an ink: it overprints with the option on too. + s.execute("document.setup", &json!({"discardWhiteOverprint": true})).unwrap(); + s.execute("swatch.new", &json!({"name": "Opaque White", "color": {"c": 0, "m": 0, "y": 0, "k": 0}, "spot": true})).unwrap(); + s.execute("select.set", &json!({"ids": [white]})).unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Opaque White"})).unwrap(); + let [r, g, b, _] = centre(&s); + assert!(r > 200 && g < 60 && b < 60, "the spot white overprints: {:?}", [r, g, b]); } #[test] diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index cf84900fe9..25f954dc4b 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -2306,15 +2306,25 @@ fn a_smooth_drag_that_comes_back_to_a_segment_smooths_where_it_comes_back() { assert!(gap < 0.5, "{between:?} is {gap} pt off the smoothed path"); } -/// A click on a curve 100,000 pt long, between the places a fixed number of samples along it would -/// look at, still finds the curve under it. +/// A click on the sharp crest of a curve 100,000 pt wide finds the curve under it, although the crest +/// lies halfway between two of 65 evenly spaced places along the curve and more than the click's 12 pt +/// reach from each of them, so a search that looked only at those places would miss it. #[test] fn a_smooth_drag_finds_a_very_long_curve_under_it() { use kurbo::ParamCurve; let mut s = session(); - let anchors = [json!({"x": 0.0, "y": 0.0, "out": [30000.0, -9000.0]}), json!({"x": 100000.0, "y": 0.0, "in": [70000.0, -9000.0]})]; + // The crest is a cusp at t0: the control points are chosen so that the curve's velocity is 0 there. + let (t0, wide): (f64, f64) = (32.5 / 64.0, 1.0e5); + let (d0, d2) = ((wide, -wide), (wide, wide)); + let d1 = ((1.0 - t0).powi(2) * d0.0 + t0 * t0 * d2.0, (1.0 - t0).powi(2) * d0.1 + t0 * t0 * d2.1); + let d1 = (-d1.0 / (2.0 * t0 * (1.0 - t0)), -d1.1 / (2.0 * t0 * (1.0 - t0))); + let (p1, p2) = (d0, (d0.0 + d1.0, d0.1 + d1.1)); + let anchors = [json!({"x": 0.0, "y": 0.0, "out": [p1.0, p1.1]}), json!({"x": p2.0 + d2.0, "y": p2.1 + d2.1, "in": [p2.0, p2.1]})]; let id = smooth_test_path(&mut s, &anchors, false); - let at = path(&s, id).subpaths[0].segment(0).eval(0.5 + 0.5 / 1024.0); + let curve = path(&s, id).subpaths[0].segment(0); + let at = curve.eval(t0); + let nearest_place = (0..=64).map(|k| curve.eval(f64::from(k) / 64.0).distance(at)).fold(f64::INFINITY, f64::min); + assert!(nearest_place > 12.0, "the nearest of 65 places is {nearest_place} pt from the click"); assert_eq!(smooth_pass_ids(&mut s, &[at]), json!([id.0])); } @@ -2329,9 +2339,9 @@ fn a_smooth_click_that_only_just_reaches_a_segment_smooths_it() { assert_ne!(path(&s, id), before); } -/// A drag that runs along a very long curve first and then crosses a second curve away from its -/// middle, with both of its anchors out of reach, smooths the second curve too: each curve in reach -/// gets the same share of the search, so the long one does not use it all. +/// A drag that runs along a very long curve first and then crosses a second curve at the peak in +/// its middle, with both of its anchors out of reach, smooths the second curve too: each curve in +/// reach gets the same share of the search, so the long one does not use it all. #[test] fn a_long_curve_searched_first_leaves_the_next_curve_its_share() { let mut s = session(); @@ -2342,7 +2352,7 @@ fn a_long_curve_searched_first_leaves_the_next_curve_its_share() { ); let next = smooth_test_path( &mut s, - &[json!({"x": 100100.0, "y": -100.0, "out": [100130.0, 200.0]}), json!({"x": 100100.0, "y": 900.0, "in": [100130.0, 600.0]})], + &[json!({"x": 100050.0, "y": 75.0, "out": [100150.0, -25.0]}), json!({"x": 100250.0, "y": 75.0, "in": [100150.0, -25.0]})], false, ); s.execute("select.set", &json!({"ids": [long.0, next.0]})).unwrap(); @@ -2372,14 +2382,14 @@ fn smoothing_smooths_an_open_two_anchor_path() { assert_eq!((a[0].p, a[a.len() - 1].p), (Point::new(100.0, 200.0), Point::new(200.0, 200.0)), "the ends stay"); } -/// A closed path of two anchors is smoothed along the middle of one side and stays closed. +/// A closed path of two anchors is smoothed at the peak in the middle of one side and stays closed. #[test] fn smoothing_smooths_a_closed_two_anchor_path() { use kurbo::ParamCurve; let mut s = session(); let anchors = [ - json!({"x": 100.0, "y": 300.0, "in": [100.0, 400.0], "out": [100.0, 200.0]}), - json!({"x": 300.0, "y": 300.0, "in": [300.0, 160.0], "out": [300.0, 440.0]}), + json!({"x": 100.0, "y": 300.0, "in": [100.0, 400.0], "out": [200.0, 150.0]}), + json!({"x": 300.0, "y": 300.0, "in": [200.0, 150.0], "out": [300.0, 440.0]}), ]; let id = smooth_test_path(&mut s, &anchors, true); let before = path(&s, id); @@ -2405,6 +2415,76 @@ fn smoothing_leaves_paths_out_of_reach_and_straight_segments_alone() { assert_eq!(path(&s, line), before); } +/// Whether `id` is still a Live Shape. +fn smooth_test_live(s: &Session, id: NodeId) -> bool { + matches!(s.doc().unwrap().doc.node(id).unwrap().kind, NodeKind::Path { live: Some(_), .. }) +} + +/// Smooth drags over a clean ellipse, again and again and at any Fidelity, change nothing: the +/// ellipse has nothing to smooth, so no pass adds anchors to it, leaves it rougher, adds an undo step +/// or takes its Live Shape away. Each returns no ids and counts of 0, as a drag that reaches no path +/// does. +#[test] +fn smooth_drags_over_a_clean_ellipse_change_nothing() { + for fidelity in [0.05, 0.5, 2.5, 10.0] { + let mut s = session(); + let id = NodeId(s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 120})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let before = path(&s, id); + let undo = s.doc().unwrap().history.undo.len(); + let pts: Vec<_> = smooth_drag_along(100.0, 160.0, 240.0).iter().map(|p| json!([p.x, p.y])).collect(); + for pass in 1..=4 { + let r = s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": fidelity})).unwrap(); + assert_eq!(r, json!({"ids": [], "before": 0, "after": 0}), "Fidelity {fidelity}, pass {pass}"); + assert_eq!(path(&s, id), before, "Fidelity {fidelity}, pass {pass}: {} anchors", path(&s, id).anchor_count()); + assert!(smooth_test_live(&s, id), "Fidelity {fidelity}, pass {pass}: still a Live Shape"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "Fidelity {fidelity}, pass {pass}: no undo step"); + } + } +} + +/// A Smooth drag over a clean ellipse and a jagged line selected together smooths the line only: the +/// result names the line and counts its anchors alone, the ellipse stays as it was and a Live Shape, +/// and one undo brings the line back. +#[test] +fn a_smooth_drag_over_an_ellipse_and_a_jagged_line_changes_only_the_line() { + let mut s = session(); + let ellipse = NodeId(s.execute("shape.ellipse", &json!({"x": 100, "y": 100, "width": 200, "height": 120})).unwrap()["id"].as_u64().unwrap()); + let mut seed = 11u64; + let anchors: Vec<_> = (0..=50).map(|i| json!({"x": 320.0 + 5.0 * f64::from(i), "y": 100.0 + smooth_noise(&mut seed)})).collect(); + let line = smooth_test_path(&mut s, &anchors, false); + s.execute("select.set", &json!({"ids": [ellipse.0, line.0]})).unwrap(); + let (oval, jagged) = (path(&s, ellipse), path(&s, line)); + let pts: Vec<_> = smooth_drag_along(100.0, 160.0, 580.0).iter().map(|p| json!([p.x, p.y])).collect(); + let r = s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 2.5})).unwrap(); + let smoothed = path(&s, line); + assert!(smoothed.anchor_count() < jagged.anchor_count(), "the line is smoothed: {} anchors", smoothed.anchor_count()); + assert_eq!(r, json!({"ids": [line.0], "before": jagged.anchor_count(), "after": smoothed.anchor_count()})); + assert_eq!(path(&s, ellipse), oval); + assert!(smooth_test_live(&s, ellipse), "the ellipse is still a Live Shape"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((path(&s, line), path(&s, ellipse)), (jagged, oval)); +} + +/// A Smooth drag at the lowest Fidelity still smooths a jagged line: it turns less and has fewer +/// anchors after each of three drags. +#[test] +fn a_smooth_drag_at_the_lowest_fidelity_still_smooths_a_jagged_line() { + let mut s = session(); + let mut seed = 11u64; + let anchors: Vec<_> = (0..=60).map(|i| json!({"x": 100.0 + 5.0 * f64::from(i), "y": 200.0 + smooth_noise(&mut seed)})).collect(); + let id = smooth_test_path(&mut s, &anchors, false); + let pts: Vec<_> = smooth_drag_along(200.0, 90.0, 410.0).iter().map(|p| json!([p.x, p.y])).collect(); + let mut before = path(&s, id); + for pass in 1..=3 { + s.execute("path.smoothRegion", &json!({"points": pts, "radius": 12, "fidelity": 0.05})).unwrap(); + let after = path(&s, id); + assert!(after.anchor_count() < before.anchor_count(), "pass {pass}: {} -> {} anchors", before.anchor_count(), after.anchor_count()); + assert!(total_turning(&after) < total_turning(&before), "pass {pass}: turning {} -> {}", total_turning(&before), total_turning(&after)); + before = after; + } +} + /// The turn, in degrees, of `sp` at each of its anchors: round a closed path, and 0 at an open /// path's first and last anchors. fn smooth_anchor_turns(sp: &vectorcraft_geom::SubPath) -> Vec { @@ -4780,6 +4860,460 @@ fn cmd_alt_lends_group_selection_while_direct_selection_is_active() { s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 80.0).with_mods(cmd_alt), v).unwrap(); } +#[test] +fn cmd_lends_the_selection_tool_direct_selection_or_group_selection_chosen_last() { + // Cmd held with the Selection tool: Direct Selection takes the press until the release, so a + // Cmd-click picks one path inside a group where a plain click picks the group. + let (none, cmd) = (Mods::default(), Mods { cmd: true, ..Mods::default() }); + let v = view(); + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + assert_eq!(s.lent_tool_id(&none), None); + assert_eq!(s.lent_tool_id(&cmd), Some("directSelection")); + assert_eq!(s.shown_tool_id(&cmd), "directSelection"); + assert_eq!(s.shown_tool_id(&none), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 150.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 150.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(a) && !picked.contains(group), "the Cmd-click picks the path, not its group"); + s.execute("select.none", &json!({})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 150.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 150.0), v).unwrap(); + assert!(s.active().unwrap().selection.contains(group), "a plain click picks the group"); + // Cmd pressed once a drag is under way lends nothing: the pointer and the named tool stay. + s.pointer(&PointerEvent::new(PointerKind::Down, 600.0, 500.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 650.0, 550.0), v).unwrap(); + assert_eq!(s.cursor(Point::new(650.0, 550.0), cmd, v), s.cursor(Point::new(650.0, 550.0), none, v)); + assert_eq!(s.shown_tool_id(&cmd), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 650.0, 550.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + // Group Selection lends the Selection tool, and once chosen, is what the Selection tool borrows. + s.select_tool("groupSelection", v).unwrap(); + assert_eq!(s.lent_tool_id(&cmd), Some("selection")); + s.select_tool("selection", v).unwrap(); + assert_eq!(s.lent_tool_id(&cmd), Some("groupSelection")); + s.select_tool("directSelection", v).unwrap(); + s.select_tool("selection", v).unwrap(); + assert_eq!(s.lent_tool_id(&cmd), Some("directSelection")); +} + +#[test] +fn a_cmd_double_click_goes_to_the_tool_the_clicks_went_to() { + // With the Selection tool, Cmd-clicks go to Direct Selection, and so does the double-click + // after them: it does not isolate the group as the Selection tool's double-click would. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + s.pointer(&PointerEvent::new(kind, 150.0, 150.0).with_mods(cmd), v).unwrap(); + } + assert_eq!(s.tool_id(), "selection"); + assert_eq!(s.doc().unwrap().isolation, None, "Direct Selection's double-click does not isolate the group"); + // With Group Selection chosen last, the second click selects the group, and the double-click + // still goes to Group Selection, as both clicks did. + s.select_tool("groupSelection", v).unwrap(); + s.select_tool("selection", v).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + s.pointer(&PointerEvent::new(kind, 150.0, 150.0).with_mods(cmd), v).unwrap(); + } + assert_eq!(s.doc().unwrap().isolation, None, "Group Selection's double-click does not isolate the group"); + s.execute("select.none", &json!({})).unwrap(); + // A plain double-click is the Selection tool's: it isolates the group. + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + s.pointer(&PointerEvent::new(kind, 150.0, 150.0), v).unwrap(); + } + assert!(s.doc().unwrap().isolation.is_some()); +} + +#[test] +fn a_cmd_double_click_after_a_tool_switch_goes_to_the_new_tool() { + // With the Selection tool, a Cmd-click on type goes to Direct Selection, and so does the + // Cmd double-click after it, which edits the type. Once another tool is chosen, the + // double-click is that tool's: Group Selection's does not edit the type. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let id = NodeId(s.execute("text.create", &json!({"x": 100, "y": 200, "size": 48, "text": "Type"})).unwrap()["id"].as_u64().unwrap()); + let c = s.doc().unwrap().doc.node(id).unwrap().geometric_bounds().unwrap().center(); + let clicks = |s: &mut Session, then: Option<&str>| { + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, c.x, c.y).with_mods(cmd), v).unwrap(); + } + if let Some(tool) = then { + s.select_tool(tool, v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, c.x, c.y).with_mods(cmd), v).unwrap() + }; + assert_eq!(clicks(&mut s, None), [UiRequest::SwitchTool("type".into())], "Direct Selection's double-click edits the type"); + assert_eq!(clicks(&mut s, Some("groupSelection")), [], "Group Selection's double-click does not"); + assert_eq!(s.tool_id(), "groupSelection"); +} + +#[test] +fn a_cmd_double_click_after_switching_away_and_back_goes_to_the_active_tool() { + // A Cmd-click with the Selection tool goes to Direct Selection. After a switch to another tool + // and back to the Selection tool, or a fresh start of the tool (another view of the document), + // the Cmd double-click is the Selection tool's: it isolates the group. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 100.0, 100.0); + let b = rect(&mut s, 300.0, 100.0, 100.0, 100.0); + s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap(); + for reset in [false, true] { + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 150.0, 150.0).with_mods(cmd), v).unwrap(); + } + if reset { + s.reset_tool(); + } else { + s.select_tool("rectangle", v).unwrap(); + s.select_tool("selection", v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 150.0, 150.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + assert!(s.doc().unwrap().isolation.is_some(), "the Selection tool's double-click isolates the group (reset: {reset})"); + s.execute("object.exitIsolation", &json!({})).unwrap(); + } +} + +#[test] +fn a_cmd_press_on_a_selected_object_keeps_select_behind() { + // Over a selected object, a Cmd-click with the Selection tool selects the object behind it; + // with Select Behind off, Direct Selection takes the press there too. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + // The canvas shows the marks of the tool a press at the pointer takes, and the status bar and + // the help bar name it. + s.cursor(Point::new(200.0, 200.0), cmd, v); + assert_eq!(s.hover_tool_id(&cmd), "selection"); + assert_eq!(s.shown_tool_id(&cmd), "selection", "the press selects behind: nothing is lent"); + s.cursor(Point::new(500.0, 500.0), cmd, v); + assert_eq!(s.hover_tool_id(&cmd), "directSelection"); + assert_eq!(s.shown_tool_id(&cmd), "directSelection"); + // The bounding box's top middle handle, on the middle of the top segment: the press is lent. + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 150.0)), &cmd, v), "directSelection", "on a box handle"); + // Turning Select Behind off changes what the bars name over the selection. + s.cursor(Point::new(200.0, 200.0), cmd, v); + s.prefs.ctrl_click_selects_behind = false; + assert_eq!(s.shown_tool_id(&cmd), "directSelection"); + s.prefs.ctrl_click_selects_behind = true; + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); + // On a selected object's anchor, Direct Selection takes the press. + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 250.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 250.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.prefs.ctrl_click_selects_behind = false; + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); +} + +#[test] +fn a_cmd_press_on_a_wide_strokes_outer_half_selects_behind() { + // Without Use Preview Bounds the bounding box leaves out the outer half of a wide stroke, which + // the Selection tool still hits: a Cmd press there selects the object behind. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + assert!(!s.prefs.use_preview_bounds); + let back = rect(&mut s, 50.0, 50.0, 300.0, 300.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.execute("stroke.set", &json!({"ids": [front.0], "weight": 40})).unwrap(); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + // 15 pt outside the path, on its stroke. + let at = Point::new(200.0, 135.0); + assert_eq!(s.hover_tool_at(Some(at), &cmd, v), "selection", "the press selects behind"); + s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, at.x, at.y).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); +} + +#[test] +fn a_cmd_press_on_a_lone_selected_object_is_lent() { + // With nothing behind the selected object, there is nothing to select behind: Direct Selection + // takes the press. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let lone = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [lone.0]})).unwrap(); + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); +} + +#[test] +fn a_layer_effect_that_moves_art_moves_where_a_cmd_press_selects_behind() { + // A layer effect draws the selected object 250 pt to the right of its path, over the object + // behind it: a Cmd press where it is drawn selects behind. A drop shadow there is not hit, so + // the press is lent. Outline view hits the path where it is, and Preview afterwards still finds + // the moved art. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let outline = ViewInfo { outline: true, ..view() }; + let drawn = Point::new(450.0, 200.0); + // On both rectangles' top edges, which Outline view hits, away from the box's handles. + let path = Point::new(170.0, 150.0); + for effect in ["distort.transform", "stylize.dropShadow"] { + let mut s = session(); + let back = rect(&mut s, 50.0, 150.0, 700.0, 300.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + let layer = s.doc().unwrap().doc.layers[0].id; + let params = if effect == "distort.transform" { json!({"moveH": 250}) } else { json!({"x": 250, "y": 0, "blur": 0}) }; + s.execute("effect.apply", &json!({"effect": effect, "params": params, "ids": [layer.0], "item": null})).unwrap(); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + // The back rectangle is drawn moved too, so it is under both points. + if effect == "distort.transform" { + assert_eq!(s.hover_tool_at(Some(path), &cmd, outline), "selection", "Outline view: on the path"); + assert_eq!(s.hover_tool_at(Some(drawn), &cmd, v), "selection", "Preview: where the effect draws it"); + s.pointer(&PointerEvent::new(PointerKind::Down, drawn.x, drawn.y).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, drawn.x, drawn.y).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); + } else { + assert_eq!(s.hover_tool_at(Some(drawn), &cmd, v), "directSelection", "on the shadow"); + } + } +} + +#[test] +fn repeated_cmd_clicks_select_behind_a_group_whose_member_is_selected() { + // The first Cmd-click on an unselected group lends Direct Selection, which selects the path + // under the pointer. The group holds that selected path, so the next Cmd-click there selects + // the object behind the group. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let a = rect(&mut s, 150.0, 150.0, 40.0, 40.0); + let b = rect(&mut s, 210.0, 150.0, 40.0, 40.0); + let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + s.select_tool("selection", v).unwrap(); + let click = |s: &mut Session| { + s.pointer(&PointerEvent::new(PointerKind::Down, 170.0, 170.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 170.0, 170.0).with_mods(cmd), v).unwrap(); + }; + click(&mut s); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(a) && !picked.contains(group), "the first Cmd-click picks the path"); + assert_eq!(s.hover_tool_at(Some(Point::new(170.0, 170.0)), &cmd, v), "selection", "the next press selects behind"); + click(&mut s); + // Made quickly, the two clicks are also a double-click, which neither isolates the group nor + // changes what the second click selected, also with Cmd let go before it. + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 170.0, 170.0), v).unwrap(); + assert_eq!(s.doc().unwrap().isolation, None); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(a), "the second Cmd-click selects the object behind the group"); +} + +#[test] +fn a_double_click_after_a_selection_change_is_not_kept_for_select_behind() { + // A double-click that follows a Cmd-click selecting behind keeps what it selected, but only + // while the document stays as that click left it. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert!(!s.active().unwrap().selection.contains(front), "the Cmd-click selects behind"); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0), v).unwrap(); + assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other"); +} + +#[test] +fn a_double_click_after_the_pointer_moved_away_is_not_kept_for_select_behind() { + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert!(!s.active().unwrap().selection.contains(front), "the Cmd-click selects behind"); + s.pointer(&PointerEvent::new(PointerKind::Move, 400.0, 400.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 200.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0), v).unwrap(); + assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other"); +} + +#[test] +fn a_double_click_after_a_select_behind_drag_is_not_kept_for_select_behind() { + // A Cmd press that selects behind and then drags is not a click, also when the drag ends where + // it began and moves nothing, so a double-click there is a double-click of its own. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 260.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert!(s.active().unwrap().selection.contains(back), "the Cmd press selects behind"); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0), v).unwrap(); + assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other"); +} + +#[test] +fn a_double_click_after_a_select_behind_press_released_away_is_not_kept_for_select_behind() { + // The automation interface can send the release far from the press with no drag between. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 270.0, 270.0).with_mods(cmd), v).unwrap(); + assert!(s.active().unwrap().selection.contains(back), "the Cmd press selects behind"); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 270.0, 270.0), v).unwrap(); + assert!(s.doc().unwrap().isolation.is_some(), "the double-click isolates as any other"); +} + +#[test] +fn a_double_click_in_the_frame_of_a_select_behind_press_keeps_what_it_selected() { + // The second press and the double-click can come in one frame, before the release. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [back.0]})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::DoubleClick, 200.0, 200.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.doc().unwrap().isolation, None, "the double-click neither isolates nor edits"); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(front) && !picked.contains(back), "the press selects behind, back to the topmost"); +} + +#[test] +fn a_cmd_click_on_an_unselected_member_of_a_group_holding_the_selection_selects_behind() { + // The group counts as selected wherever its art is, not only over its selected member. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 300.0, 200.0); + let a = rect(&mut s, 150.0, 150.0, 40.0, 40.0); + let b = rect(&mut s, 300.0, 150.0, 40.0, 40.0); + s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap(); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(s.hover_tool_at(Some(Point::new(320.0, 170.0)), &cmd, v), "selection", "on the unselected member"); + s.pointer(&PointerEvent::new(PointerKind::Down, 320.0, 170.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 320.0, 170.0).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(b), "the Cmd-click selects the object behind the group"); +} + +#[test] +fn a_cmd_click_on_a_selected_lines_segment_selects_behind() { + // An open, unfilled path is only hit near its segments: a Cmd press there selects the object + // behind it, and a Cmd press on its anchor is Direct Selection's. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + let back = rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = line(&mut s, 150.0, 150.0, 250.0, 250.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + assert_eq!(s.hover_tool_at(Some(Point::new(150.0, 150.0)), &cmd, v), "directSelection", "on its anchor"); + // On the segment, away from the anchors and the bounding box's handles. + s.pointer(&PointerEvent::new(PointerKind::Down, 180.0, 180.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + s.pointer(&PointerEvent::new(PointerKind::Up, 180.0, 180.0).with_mods(cmd), v).unwrap(); + let picked = &s.active().unwrap().selection; + assert!(picked.contains(back) && !picked.contains(front), "the Cmd-click selects the object behind"); +} + +#[test] +fn a_hovers_lend_decision_holds_only_for_the_tool_and_selection_it_was_found_for() { + // While the view moves, the canvas reads the last hover's decision: it does not carry over to + // another tool or another selection. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "selection"); + s.execute("select.none", &json!({})).unwrap(); + assert_eq!(s.hover_tool_id(&cmd), "directSelection", "nothing is selected now"); + assert_eq!(s.hover_tool_at(Some(Point::new(500.0, 500.0)), &cmd, v), "directSelection"); + s.select_tool("rectangle", v).unwrap(); + assert_eq!(s.hover_tool_id(&cmd), s.lent_tool_id(&cmd).unwrap(), "the new tool's lend"); +} + +#[test] +fn the_marks_follow_this_frames_pointer_with_cmd_held() { + // The canvas asks which tool's marks to draw before it asks for the cursor: the answer is for + // the pointer where it is now, and with the pointer off the canvas, the tool Cmd lends. + let cmd = Mods { cmd: true, ..Mods::default() }; + let v = view(); + let mut s = session(); + rect(&mut s, 100.0, 100.0, 200.0, 200.0); + let front = rect(&mut s, 150.0, 150.0, 100.0, 100.0); + s.select_tool("selection", v).unwrap(); + s.execute("select.set", &json!({"ids": [front.0]})).unwrap(); + s.cursor(Point::new(200.0, 200.0), cmd, v); + assert_eq!(s.hover_tool_id(&cmd), "selection"); + assert_eq!(s.hover_tool_at(Some(Point::new(500.0, 500.0)), &cmd, v), "directSelection", "away from the selection"); + assert_eq!(s.hover_tool_at(Some(Point::new(200.0, 200.0)), &cmd, v), "selection", "over the selection"); + assert_eq!(s.hover_tool_at(None, &cmd, v), "directSelection", "off the canvas"); + assert_eq!(s.hover_tool_id(&cmd), "directSelection", "kept while the view moves"); + assert_eq!(s.hover_tool_at(None, &Mods::default(), v), "selection", "without Cmd"); +} + #[test] fn cmd_lends_the_selection_tool_and_its_bounding_box_to_direct_selection() { // #3901: with Direct Selection, Cmd held gives the Selection tool for the press: its cursor, diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index fc1305a0a7..2f88f5acc9 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -1212,6 +1212,26 @@ fn select_part_refuses_hidden_and_locked_objects_of_the_art() { s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1, 1]})).unwrap(); } +#[test] +fn a_cmd_click_with_the_selection_tool_keeps_the_instance_selected_whole() { + // Cmd lends Direct Selection the Selection tool: the press picks one object of a dynamic + // instance, and back with the Selection tool after the release, the instance stays selected, + // whole, as choosing the Selection tool leaves it. + let mut s = session(); + let inst = pair(&mut s, "dynamic"); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + let cmd = Mods { cmd: true, ..Mods::default() }; + s.select_tool("selection", v).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 80.0, 30.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "directSelection"); + assert!(s.doc().unwrap().selection.symbol_part.is_some(), "the lent tool picks the object"); + s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 30.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection"); + let sel = &s.doc().unwrap().selection; + assert_eq!((&sel.objects, &sel.symbol_part), (&vec![inst], &None)); +} + #[test] fn choosing_the_selection_tool_again_picks_the_instance_whole() { let mut s = session(); diff --git a/crates/engine/src/tests/large_edits.rs b/crates/engine/src/tests/large_edits.rs index aa18cef1ec..81d6b3bc65 100644 --- a/crates/engine/src/tests/large_edits.rs +++ b/crates/engine/src/tests/large_edits.rs @@ -1,6 +1,7 @@ //! Commands that remove, insert or copy many objects, and an Alt-drag that copies them, each walk //! the document's tree a few times on one layer of 25,000 to 100,000 objects, and objects in two -//! layers and inside a group keep their order and ids. +//! layers and inside a group keep their order and ids. Selecting objects one at a time looks up +//! only the added ones. use std::sync::Arc; use std::time::Duration; @@ -120,6 +121,44 @@ fn delete_of_100000_objects_takes_few_tree_walks() { undo_gives_back(&mut s, &before); } +#[test] +fn deleting_2000_objects_by_id_one_at_a_time_takes_few_tree_walks() { + // From the top down, from the bottom up, and from the middle out. + let orders: [fn(Vec) -> Vec; 3] = [ + |ids| ids.into_iter().rev().collect(), + |ids| ids, + |ids| { + let middle = ids.len() / 2; + let mut placed: Vec<(usize, NodeId)> = ids.into_iter().enumerate().collect(); + placed.sort_by_key(|(k, _)| k.abs_diff(middle)); + placed.into_iter().map(|(_, id)| id).collect() + }, + ]; + for order in orders { + let mut s = session(2_000, square); + s.execute("guide.add", &json!({"pos": 5.0})).unwrap(); + let doc = &s.doc().unwrap().doc; + let all: Vec = layer(&s, 0).into_iter().filter(|id| !doc.node(*id).unwrap().is_ruler_guide()).collect(); + assert_eq!(all.len(), 2_000); + let (kept, art) = (all[0], all[1..].to_vec()); + s.execute("select.set", &json!({"ids": [kept]})).unwrap(); + let ids = order(art); + let (mut s, steps) = soon(s, "edit.clear", move |s| { + let mut steps = vec![s.doc().unwrap().doc.clone()]; + for id in &ids { + s.execute("edit.clear", &json!({"ids": [id.0]})).unwrap(); + steps.push(s.doc().unwrap().doc.clone()); + } + steps + }); + assert_eq!(layer(&s, 0).len(), 2, "the kept object and the guide"); + assert!(selected(&s, &[kept])); + for before in steps.iter().rev().skip(1).take(3) { + undo_gives_back(&mut s, before); + } + } +} + #[test] fn delete_selection_of_100000_rows_takes_few_tree_walks() { let s = session(100_000, square); @@ -658,3 +697,27 @@ fn copies_of_ids_listed_twice_or_inside_another_listed_id_keep_their_order_and_i assert_eq!(layers(&s), [json!([a, n + 1, n, b, c, [group, d, e, f]]), json!([g, h])]); undo_gives_back(&mut s, &before); } + +/// `select.add` run once for each of `n` objects, from nothing selected → the walks of the tree and +/// the lookups by id it took. +fn add_one_at_a_time(n: usize) -> (u64, u64) { + let mut s = session(n, square); + s.execute("select.none", &json!({})).unwrap(); + let ids = layer(&s, 0); + let (walks, lookups) = (vectorcraft_doc::tree_walks(), vectorcraft_doc::path_lookups()); + for id in &ids { + s.execute("select.add", &json!({"ids": [id.0]})).unwrap(); + } + assert!(selected(&s, &ids)); + (vectorcraft_doc::tree_walks() - walks, vectorcraft_doc::path_lookups() - lookups) +} + +/// Selecting objects one at a time checks and reads only the object each `select.add` adds: twice +/// as many objects take about twice as many lookups, and the tree is not walked for each one. +#[test] +fn selecting_objects_one_at_a_time_looks_up_only_the_added_objects() { + let (walks, lookups) = add_one_at_a_time(1_000); + let (more_walks, more_lookups) = add_one_at_a_time(2_000); + assert!(walks.max(more_walks) <= MOST_TREE_WALKS, "walked the tree {walks} and {more_walks} times"); + assert!(more_lookups <= lookups * 5 / 2, "{lookups} lookups for 1,000 objects, {more_lookups} for 2,000"); +} diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 288f0236d1..96a2aedff8 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -1002,3 +1002,36 @@ fn a_double_click_on_a_corner_widget_with_a_shape_tool_asks_for_the_transform_pa assert!(st.interaction.is_none()); assert_eq!(s.tool_id(), "rectangle"); } + +/// A double-click on a corner widget of a selected live rectangle with the Selection tool asks +/// the frontend for the Transform panel, and leaves the document, its undo history, the +/// selection and the tool as they were; with Direct Selection it still opens Corners. +#[test] +fn a_double_click_on_a_corner_widget_with_the_selection_tool_asks_for_the_transform_panel() { + use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + let (mut s, id) = session(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let v = ViewInfo::default(); + let st = s.doc().unwrap(); + let w = vectorcraft_tools::corners::CornerWidgets::showing(&st.doc, &st.selection, v.zoom, false, true, 180.0).expect("corner widgets show"); + let at = w.visible().next().expect("a widget"); + let (doc, selection, steps) = (st.doc.clone(), st.selection.clone(), st.history.undo.len()); + let double_click = |s: &mut Session, tool: &str| { + s.select_tool(tool, v).unwrap(); + let mut asked = vec![]; + for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] { + asked.extend(s.pointer(&PointerEvent::new(kind, at.x, at.y).with_mods(Mods::default()), v).unwrap()); + } + asked + }; + assert_eq!(double_click(&mut s, "selection"), vec![UiRequest::Panel("transform".into())]); + let st = s.doc().unwrap(); + assert!(*st.doc == *doc, "the document is unchanged"); + assert_eq!(st.selection, selection); + assert_eq!(st.history.undo.len(), steps, "no undo step"); + assert!(st.interaction.is_none()); + assert_eq!(s.tool_id(), "selection"); + // Direct Selection opens Corners for the corner it picked with the first click. + let asked = double_click(&mut s, "directSelection"); + assert!(matches!(asked.as_slice(), [UiRequest::Dialog(k, _)] if k == vectorcraft_tools::corners::DIALOG), "{asked:?}"); +} diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index ef14bbaef9..a23fab2209 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -4621,6 +4621,38 @@ fn locked_guides_lock_guide_paths() { assert_eq!(selected(&s), vec![b]); } +/// A guide path added to the selection after another object stays unselected while Lock Guides is +/// on, and is selected once it is off. +#[test] +fn a_guide_path_added_after_another_object_stays_unselected_while_guides_are_locked() { + let mut s = session(); + let b = rect(&mut s, 20.0, 20.0, 10.0, 10.0); + let g = guide_path(&mut s, 0.0); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + for id in [b, g] { + s.execute("select.add", &json!({"ids": [id.0]})).unwrap(); + } + assert_eq!(selected(&s), vec![b]); + s.execute("view.guides.lock", &json!({"locked": false})).unwrap(); + s.execute("select.add", &json!({"ids": [g.0]})).unwrap(); + assert_eq!(selected(&s), vec![b, g]); +} + +/// An id that names no object and a ruler guide's id, added to a selection after another object, +/// leave the selection as a whole new selection of the same ids would. +#[test] +fn a_missing_object_and_a_ruler_guide_added_after_another_object_stay_unselected() { + let mut s = session(); + let (b, c) = (rect(&mut s, 20.0, 20.0, 10.0, 10.0), rect(&mut s, 40.0, 20.0, 10.0, 10.0)); + s.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap(); + let guide = s.doc().unwrap().doc.ruler_guides()[0].id.unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); + let missing = NodeId(u64::MAX); + s.select(|_, sel| sel.objects.extend([missing, guide, c])).unwrap(); + assert_eq!(selected(&s), vec![b, c]); +} + /// A rectangle at (`x`, 0), 10 pt wide, made into a guide; nothing is selected after. fn guide_path(s: &mut Session, x: f64) -> NodeId { let g = rect(s, x, 0.0, 10.0, 10.0); diff --git a/crates/engine/src/tests/newart.rs b/crates/engine/src/tests/newart.rs index 583a5f43d8..b139ee5927 100644 --- a/crates/engine/src/tests/newart.rs +++ b/crates/engine/src/tests/newart.rs @@ -192,6 +192,47 @@ fn a_paint_the_selected_objects_do_not_share_stays_as_it_was() { assert_eq!((s.paint.stroke.clone(), s.paint.stroke_width), (node(&s, a).appearance.stroke_paint(), 5.0), "the strokes are shared"); } +fn add(s: &mut Session, id: NodeId) { + run(s, "select.add", json!({"ids": [id.0]})); +} + +/// Objects added one at a time are compared with the objects already selected: a fill and weight +/// they all share loads, one they don't stays as it was. +#[test] +fn objects_added_one_at_a_time_load_only_the_paints_all_selected_objects_share() { + let mut s = session(); + let a = painted(&mut s, 20.0, "#ff0000", "#00ff00", 5.0); + let b = painted(&mut s, 120.0, "#ff0000", "#00ff00", 5.0); + let c = painted(&mut s, 220.0, "#0000ff", "#00ff00", 1.0); + let red = node(&s, a).appearance.fill_paint(); + run(&mut s, "select.none", json!({})); + add(&mut s, a); + (s.paint.fill, s.paint.stroke_width) = (Paint::None, 0.5); + add(&mut s, b); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (red, 5.0), "a and b share them"); + (s.paint.fill, s.paint.stroke_width) = (Paint::None, 0.5); + add(&mut s, c); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.5), "c's differ"); +} + +/// An edit of the selected objects between two additions is read: the objects selected before it +/// are compared as the edit left them. +#[test] +fn an_object_added_after_an_edit_is_compared_with_the_edited_objects() { + let mut s = session(); + let a = painted(&mut s, 20.0, "#ff0000", "#00ff00", 5.0); + let b = painted(&mut s, 120.0, "#ff0000", "#00ff00", 5.0); + let c = painted(&mut s, 220.0, "#0000ff", "#00ff00", 5.0); + let blue = node(&s, c).appearance.fill_paint(); + run(&mut s, "select.none", json!({})); + add(&mut s, a); + add(&mut s, b); + run(&mut s, "paint.setFill", json!({"color": "#0000ff", "ids": [a.0, b.0]})); + s.paint.fill = Paint::None; + add(&mut s, c); + assert_eq!(s.paint.fill, blue, "a, b and c are all blue now"); +} + #[test] fn art_without_paint_leaves_the_proxies_as_they_were() { let mut s = session(); diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index c6699190b6..53838c9bd7 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -532,6 +532,102 @@ fn rearrange_that_moves_no_artboard_records_no_undo_step() { assert_eq!(history(&s), before); } +/// Rearrange with `indices` lays out only those artboards, in document order whatever order they +/// are listed in, with the grid's top-left at `at`: their art and guides go along, and the other +/// artboards, their art and their guides stay where they are, all in one undo step. +#[test] +fn rearrange_lays_out_only_the_listed_artboards() { + let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 4})); + let before = boards(&s); + let art: Vec = before + .iter() + .map(|r| { + NodeId( + s.execute("shape.rectangle", &json!({"x": r.x0 + 10.0, "y": r.y0 + 10.0, "width": 10, "height": 10})).unwrap()["id"] + .as_u64() + .unwrap(), + ) + }) + .collect(); + for i in [0, 1] { + s.execute("guide.add", &json!({"vertical": true, "pos": before[i].x0 + 5.0, "artboard": i})).unwrap(); + } + let undo = s.doc().unwrap().history.undo.len(); + let p = json!({"indices": [3, 1], "layout": "row", "spacing": 10, "at": [500, 400]}); + let r = s.execute("artboard.rearrange", &p).unwrap(); + assert_eq!(r, json!({"artboards": 4, "indices": [1, 3], "moved": 2, "rows": 1, "columns": 2})); + let after = boards(&s); + assert_eq!((after[0], after[2]), (before[0], before[2]), "the artboards not listed stay"); + assert_eq!((after[1], after[3]), (Rect::new(500.0, 400.0, 600.0, 450.0), Rect::new(610.0, 400.0, 710.0, 450.0))); + let d = &s.doc().unwrap().doc; + for (id, r) in art.iter().zip(&after) { + let b = d.node(*id).unwrap().geometric_bounds().unwrap(); + assert_eq!((b.x0, b.y0), (r.x0 + 10.0, r.y0 + 10.0), "the art is on its artboard"); + } + let guides: Vec = d.ruler_guides().iter().map(|g| g.pos).collect(); + assert_eq!(guides, [before[0].x0 + 5.0, 505.0]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(boards(&s), before); +} + +/// Without `at`, the grid of the listed artboards starts at the first one's top-left; one listed +/// artboard is laid out alone; a listed locked artboard stays and keeps its cell; when every listed +/// artboard is locked, nothing moves, no undo step is recorded and `moved` is 0. +#[test] +fn rearrange_of_listed_artboards_starts_at_the_first_and_keeps_locked_ones() { + let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 4, "artboardLayout": {"layout": "row", "spacing": 20}})); + let before = boards(&s); + // Artboards 1 and 3 in one column, from artboard 1's corner. + let r = s.execute("artboard.rearrange", &json!({"indices": [1, 3], "layout": "column", "spacing": 10})).unwrap(); + assert_eq!(r["moved"], 1); + let after = boards(&s); + assert_eq!(after[1], before[1]); + assert_eq!(after[3], Rect::new(before[1].x0, before[1].y1 + 10.0, before[1].x1, before[1].y1 + 60.0)); + // One artboard goes to `at`. + s.execute("artboard.rearrange", &json!({"indices": [2], "at": [-300, -200]})).unwrap(); + assert_eq!(boards(&s)[2], Rect::new(-300.0, -200.0, -200.0, -150.0)); + // Artboard 0 locked keeps its place and its cell: artboard 2 goes to the second cell from 0's. + s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap(); + let r = s.execute("artboard.rearrange", &json!({"indices": [0, 2], "layout": "row", "spacing": 5, "at": [1000, 0]})).unwrap(); + assert_eq!(r["moved"], 1); + assert_eq!((boards(&s)[0], boards(&s)[2]), (before[0], Rect::new(1105.0, 0.0, 1205.0, 50.0))); + // Every listed artboard locked: nothing moves. + let placed = boards(&s); + let undo = s.doc().unwrap().history.undo.len(); + let r = s.execute("artboard.rearrange", &json!({"indices": [0], "at": [3000, 3000]})).unwrap(); + assert_eq!(r, json!({"artboards": 4, "indices": [0], "moved": 0, "rows": 1, "columns": 1})); + assert_eq!((boards(&s), s.doc().unwrap().history.undo.len()), (placed, undo)); +} + +/// Rearrange refuses `indices` that are not a non-empty list of artboards, and an `at` that is not +/// [x, y], before anything moves, and leaves the document as it was when `at` would put an +/// artboard past the canvas; a listed index given twice counts once. +#[test] +fn rearrange_refuses_bad_indices_and_at() { + let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 3})); + let before = (boards(&s), s.doc().unwrap().history.undo.len()); + for (p, msg) in [ + (json!({"indices": []}), "invalid parameters for `artboard.rearrange`: `indices` must be a non-empty list of artboard indices"), + (json!({"indices": 1}), "invalid parameters for `artboard.rearrange`: `indices` must be a list of artboard indices"), + (json!({"indices": [1.5]}), "invalid parameters for `artboard.rearrange`: `indices` must contain whole numbers"), + (json!({"indices": [-1]}), "invalid parameters for `artboard.rearrange`: `indices` must contain whole numbers"), + (json!({"indices": ["1"]}), "invalid parameters for `artboard.rearrange`: `indices` must contain whole numbers"), + (json!({"indices": [0, 3]}), "no such artboard"), + (json!({"indices": [0, 1], "at": [1]}), "invalid parameters for `artboard.rearrange`: `at` must be [x, y]"), + (json!({"indices": [0, 1], "at": "0,0"}), "invalid parameters for `artboard.rearrange`: `at` must be [x, y]"), + (json!({"at": [0, "1"]}), "invalid parameters for `artboard.rearrange`: `at` must be [x, y]"), + (json!({"indices": [0], "at": [1e20, 0]}), "result would exceed the canvas (coordinates out of range)"), + (json!({"at": [0, -4.000001e6]}), "result would exceed the canvas (coordinates out of range)"), + ] { + let err = s.execute("artboard.rearrange", &p).unwrap_err().to_string(); + assert_eq!(err, msg, "{p}"); + assert_eq!((boards(&s), s.doc().unwrap().history.undo.len()), before, "{p}"); + } + let r = s.execute("artboard.rearrange", &json!({"indices": [2, 2], "at": [0, 500]})).unwrap(); + assert_eq!((r["indices"].clone(), boards(&s)[2]), (json!([2]), Rect::new(0.0, 500.0, 100.0, 550.0))); +} + /// A session whose New Document profiles are in a fresh folder for test `name` (not made yet). fn with_profiles(name: &str) -> (Session, std::path::PathBuf) { let dir = std::env::temp_dir().join(format!("vc-newdoc-profiles-{name}-{}", std::process::id())); diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index 9474973adb..344b5e436e 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -792,7 +792,7 @@ fn the_document_info_report_has_every_category() { assert!(text.contains(&format!("\n{h}\n")), "{h}: {text}"); } assert!(text.contains("Images: 3") && text.contains("Source Sans 3 Regular: built in; embedding allowed"), "{text}"); - assert!(text.contains("red.png: 600 × 300 px — ") && text.contains("Color Mode: RGB") && text.contains("\nSwatches: "), "{text}"); + assert!(text.contains("red.png: PNG; 600 × 300 px; 72 ppi — ") && text.contains("Color Mode: RGB") && text.contains("\nSwatches: "), "{text}"); let fonts = run(&mut s, "document.info", json!({"format": "text", "category": "fonts"}))["text"].as_str().unwrap().to_string(); assert!(fonts.contains("FONTS") && !fonts.contains("OBJECTS"), "{fonts}"); let i = run(&mut s, "document.info", json!({"category": "linkedImages"})); @@ -802,7 +802,7 @@ fn the_document_info_report_has_every_category() { // embedded one with no file. let linked: Vec = i["imageObjects"].as_array().unwrap().iter().filter(|o| o["linked"] == true).cloned().collect(); for (o, r) in linked.iter().zip(i["sections"][0]["rows"].as_array().unwrap()) { - let shown = format!("{} × {} px — {}", o["width"], o["height"], o["file"].as_str().unwrap()); + let shown = format!("PNG; {} × {} px; 72 ppi — {}", o["width"], o["height"], o["file"].as_str().unwrap()); assert_eq!((&o["name"], shown.as_str()), (&r[0], r[1].as_str().unwrap())); } assert_eq!(linked.len(), 2); diff --git a/crates/engine/src/tests/paintopacity.rs b/crates/engine/src/tests/paintopacity.rs new file mode 100644 index 0000000000..c2e80f983a --- /dev/null +++ b/crates/engine/src/tests/paintopacity.rs @@ -0,0 +1,485 @@ +//! `opacity` on `paint.setFill` and `paint.setStroke`: the opacity of the fill or stroke item the +//! paint goes to, and `fillOpacity` and `strokeOpacity` on `paint.proxies`. + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Node, NodeKind}; +use vectorcraft_tools::{PointerEvent, PointerKind}; + +use crate::tooling::ViewInfo; +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + let r = s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 100, "height": 50})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +fn text(s: &mut Session) -> NodeId { + let r = s.execute("text.create", &json!({"x": 10, "y": 150, "text": "Hi"})).unwrap(); + NodeId(r["id"].as_u64().unwrap()) +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).unwrap().clone() +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn fill_opacity(s: &Session, id: NodeId) -> f32 { + node(s, id).appearance.fill().unwrap().opacity +} + +fn undo_labels(s: &Session) -> Vec { + s.doc().unwrap().history.undo.iter().map(|e| e.label.clone()).collect() +} + +fn proxies(s: &mut Session) -> Value { + s.execute("paint.proxies", &json!({})).unwrap() +} + +/// `paint.setFill {opacity}` alone sets the opacity of the selected object's top fill item, as one +/// undo step named Opacity, and leaves its paint, its stroke and the object's own opacity as they +/// were; `paint.setStroke {opacity}` does the same for the top stroke, and `paint.proxies` answers +/// both. +#[test] +fn opacity_alone_sets_the_fill_or_stroke_item() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + let before = node(&s, id); + let undo = undo_labels(&s).len(); + s.execute("paint.setFill", &json!({"opacity": 40})).unwrap(); + let n = node(&s, id); + assert!((fill_opacity(&s, id) - 0.4).abs() < 1e-6); + assert_eq!(n.appearance.fill_paint(), before.appearance.fill_paint()); + assert_eq!(n.appearance.stroke().unwrap().opacity, 1.0); + assert_eq!(n.opacity, 1.0); + let labels = undo_labels(&s); + assert_eq!((labels.len(), labels.last().map(String::as_str)), (undo + 1, Some("Opacity"))); + assert_eq!(proxies(&mut s)["fillOpacity"], 40.0); + assert_eq!(proxies(&mut s)["strokeOpacity"], 100.0); + // The defaults for new art keep their paint. + assert_eq!(s.paint.fill, Paint::solid(Color::WHITE)); + + s.execute("paint.setStroke", &json!({"opacity": 25})).unwrap(); + assert!((node(&s, id).appearance.stroke().unwrap().opacity - 0.25).abs() < 1e-6); + assert!((fill_opacity(&s, id) - 0.4).abs() < 1e-6); + assert_eq!(proxies(&mut s)["strokeOpacity"], 25.0); +} + +/// A selected group stands for its contents: every member's fill takes the opacity, as one undo step. +#[test] +fn a_group_sets_every_member_in_one_step() { + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + select(&mut s, &[a, b]); + s.execute("object.group", &json!({})).unwrap(); + let undo = undo_labels(&s).len(); + s.execute("paint.setFill", &json!({"opacity": 60})).unwrap(); + assert!((fill_opacity(&s, a) - 0.6).abs() < 1e-6 && (fill_opacity(&s, b) - 0.6).abs() < 1e-6); + assert_eq!(undo_labels(&s).len(), undo + 1); +} + +/// A group with a fill of its own: without an active Appearance row, `paint.proxies` answers the +/// opacity of the contents' fills, which `paint.setFill {opacity}` sets, not the group's own fill. +#[test] +fn a_group_with_its_own_fill_answers_for_its_contents() { + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + select(&mut s, &[a, b]); + s.execute("object.group", &json!({})).unwrap(); + let g = s.doc().unwrap().selection.subjects()[0]; + select(&mut s, &[g]); + s.execute("appearance.addFill", &json!({})).unwrap(); + let own = node(&s, g).appearance.items.iter().position(|it| it.is_fill()).unwrap(); + s.execute("paint.setFill", &json!({"item": own, "opacity": 30})).unwrap(); + select(&mut s, &[g]); + assert_eq!(proxies(&mut s)["fillOpacity"], 100.0); + s.execute("paint.setFill", &json!({"opacity": 60})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 60.0); + assert!((node(&s, g).appearance.items[own].opacity() - 0.3).abs() < 1e-6, "the group's own fill keeps its opacity"); +} + +/// A targeted layer without an active Appearance row: `paint.proxies` answers the opacity of the +/// layer's editable art, which `paint.setFill {opacity}` sets, not that of a locked object before it. +#[test] +fn a_targeted_layer_answers_for_its_editable_art() { + let mut s = session(); + let (locked, open) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + s.execute("paint.setFill", &json!({"ids": [locked.0], "opacity": 20})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [open.0], "opacity": 80})).unwrap(); + s.execute("object.lock", &json!({"ids": [locked.0]})).unwrap(); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("layer.target", &json!({"id": layer.0})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 80.0); + s.execute("paint.setFill", &json!({"opacity": 40})).unwrap(); + assert!((fill_opacity(&s, open) - 0.4).abs() < 1e-6); + assert!((fill_opacity(&s, locked) - 0.2).abs() < 1e-6, "the locked object keeps its opacity"); + assert_eq!(proxies(&mut s)["fillOpacity"], 40.0); +} + +/// With the Appearance panel's lower fill row active, that row takes the opacity and the top fill +/// keeps its own. +#[test] +fn the_active_appearance_row_takes_the_opacity() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + s.execute("appearance.addFill", &json!({})).unwrap(); // [Fill, Stroke, Fill] + s.execute("appearance.setActiveItem", &json!({"index": 0})).unwrap(); + s.execute("paint.setFill", &json!({"opacity": 30})).unwrap(); + let ap = node(&s, id).appearance; + assert!((ap.items[0].opacity() - 0.3).abs() < 1e-6); + assert_eq!(ap.items[2].opacity(), 1.0); + assert_eq!(proxies(&mut s)["fillOpacity"], 30.0); +} + +/// With a path of a compound path selected and its fill row active, the command edits the compound +/// path's fill, and `paint.proxies` answers that fill's opacity, not the member's own. +#[test] +fn an_active_row_of_a_compound_member_answers_for_its_compound() { + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + select(&mut s, &[a, b]); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [compound.0], "opacity": 40})).unwrap(); + // A fill row of the member's own, at 100%. + s.execute("appearance.addFill", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(fill_opacity(&s, a), 1.0); + select(&mut s, &[a]); + let row = node(&s, a).appearance.items.iter().position(|it| it.is_fill()).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": row})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 40.0); + s.execute("paint.setFill", &json!({"opacity": 70})).unwrap(); + assert!((fill_opacity(&s, compound) - 0.7).abs() < 1e-6); + assert_eq!(proxies(&mut s)["fillOpacity"], 70.0); + + // A fill row of the member's at an index that is not a fill in the compound path: the command + // edits the compound path's top fill, which the proxy answers. + s.execute("appearance.addFill", &json!({"ids": [a.0]})).unwrap(); + let (member, outer) = (node(&s, a).appearance, node(&s, compound).appearance); + let row = (0..member.items.len()).find(|i| member.items[*i].is_fill() && !outer.items.get(*i).is_some_and(|it| it.is_fill())).unwrap(); + select(&mut s, &[a]); + s.execute("appearance.setActiveItem", &json!({"index": row})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 70.0); + s.execute("paint.setFill", &json!({"opacity": 20})).unwrap(); + assert!((fill_opacity(&s, compound) - 0.2).abs() < 1e-6); + assert_eq!(proxies(&mut s)["fillOpacity"], 20.0); +} + +/// A color and an opacity change together in one undo step, and the same call again records no +/// step. +#[test] +fn color_and_opacity_are_one_step_and_a_repeat_records_none() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + let undo = undo_labels(&s).len(); + let p = json!({"color": "#ff0000", "opacity": 50}); + s.execute("paint.setFill", &p).unwrap(); + assert_eq!(node(&s, id).appearance.fill_paint(), Paint::solid(Color::rgb8(255, 0, 0))); + assert!((fill_opacity(&s, id) - 0.5).abs() < 1e-6); + assert_eq!(undo_labels(&s).len(), undo + 1); + assert_eq!(undo_labels(&s).last().map(String::as_str), Some("Fill Color")); + s.execute("paint.setFill", &p).unwrap(); + s.execute("paint.setFill", &json!({"opacity": 50})).unwrap(); + assert_eq!(undo_labels(&s).len(), undo + 1); +} + +/// Bad values, nothing selected, and characters selected with the Type tool answer errors and leave +/// the document and the defaults for new art as they were. +#[test] +fn errors_leave_the_document_and_defaults_alone() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + for bad in [json!(101), json!(-1), json!("50"), json!(true)] { + let e = s.execute("paint.setFill", &json!({"opacity": bad})).unwrap_err(); + assert!(e.to_string().contains("`opacity` must be a number from 0 to 100"), "{bad}: {e}"); + } + let e = s.execute("paint.setFill", &json!({})).unwrap_err(); + assert!(e.to_string().contains("give color, none, swatch, gradient or opacity"), "{e}"); + // An opacity alone places no gradient across the selection. + let doc = s.doc().unwrap().doc.clone(); + for (span, says) in [(json!("selection"), "give `gradient`"), (json!("all"), "span must be \"object\" or \"selection\"")] { + let e = s.execute("paint.setFill", &json!({"opacity": 40, "span": span})).unwrap_err(); + assert!(e.to_string().contains(says), "{span}: {e}"); + } + assert_eq!(*s.doc().unwrap().doc, *doc); + s.execute("paint.setFill", &json!({"opacity": 40, "span": "object"})).unwrap(); + assert!((fill_opacity(&s, id) - 0.4).abs() < 1e-6); + s.execute("select.none", &json!({})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + for p in [json!({"opacity": 40}), json!({"color": "#ff0000", "opacity": 40})] { + let e = s.execute("paint.setFill", &p).unwrap_err(); + assert!(e.to_string().contains("select objects or give ids"), "{p}: {e}"); + } + assert_eq!(s.paint.fill, Paint::solid(Color::WHITE)); + assert_eq!(*s.doc().unwrap().doc, *doc); + + // Characters selected with the Type tool. + let v = ViewInfo::default(); + s.select_tool("type", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 50.0, 250.0), v).unwrap(); + } + s.tool_text("Sample", v).unwrap(); + s.set_tool_option("select", &json!({"start": 0, "end": 3})); + let doc = s.doc().unwrap().doc.clone(); + for p in [json!({"opacity": 40}), json!({"color": "#ff0000", "opacity": 40})] { + let e = s.execute("paint.setFill", &p).unwrap_err(); + assert!(e.to_string().contains("type characters have no opacity of their own"), "{p}: {e}"); + } + assert_eq!(*s.doc().unwrap().doc, *doc); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); +} + +/// Select characters of `t` with the Type tool. +fn select_characters(s: &mut Session, t: NodeId) { + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": t.0, "anchor": 0, "caret": 2})); +} + +/// While the Type tool has characters selected, `paint.proxies` answers no opacity even when the +/// type object has a fill row of its own that the Appearance panel has active, since +/// `paint.setFill {opacity}` would give the opacity to the characters. +#[test] +fn with_characters_selected_the_proxy_answers_no_opacity() { + let mut s = session(); + let t = text(&mut s); + select(&mut s, &[t]); + s.execute("appearance.addFill", &json!({})).unwrap(); + let row = node(&s, t).appearance.items.iter().position(|it| it.is_fill()).unwrap(); + s.execute("appearance.setActiveItem", &json!({"index": row})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 100.0, "the type object's own fill row"); + select_characters(&mut s, t); + let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err(); + assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}"); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); +} + +/// While the Type tool has characters selected, an object named by `id` takes the opacity and the +/// paint, and the characters keep theirs. +#[test] +fn with_characters_selected_an_id_takes_the_opacity() { + let mut s = session(); + let r = rect(&mut s, 10.0); + let t = text(&mut s); + select(&mut s, &[t]); + select_characters(&mut s, t); + let before = node(&s, t); + s.execute("paint.setFill", &json!({"id": r.0, "opacity": 40})).unwrap(); + assert!((fill_opacity(&s, r) - 0.4).abs() < 1e-6); + s.execute("paint.setStroke", &json!({"id": r.0, "color": "#ff0000", "opacity": 30})).unwrap(); + let stroke = node(&s, r).appearance.stroke().unwrap().clone(); + assert!((stroke.opacity - 0.3).abs() < 1e-6); + assert_eq!(stroke.paint, Paint::solid(Color::rgb8(255, 0, 0))); + assert_eq!(node(&s, t), before, "the characters keep their paint"); +} + +/// A type object whose characters take the paint is left alone beside a rectangle that takes the +/// opacity, with no error; alone, it answers the characters error. +#[test] +fn type_beside_other_art_is_left_alone() { + let mut s = session(); + let r = rect(&mut s, 10.0); + let t = text(&mut s); + let runs = |s: &Session| match &node(s, t).kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("not type"), + }; + let before = (node(&s, t), runs(&s)); + select(&mut s, &[r, t]); + let out = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap(); + assert_eq!(out["objects"], 1, "only the rectangle took the opacity"); + assert!((fill_opacity(&s, r) - 0.4).abs() < 1e-6); + assert_eq!((node(&s, t), runs(&s)), before); + select(&mut s, &[t]); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); + let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err(); + assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}"); + assert_eq!((node(&s, t), runs(&s)), before); +} + +/// A color with an opacity on type alone answers the characters error and takes the color back too. +#[test] +fn type_alone_takes_back_the_paint_given_with_an_opacity() { + let mut s = session(); + let t = text(&mut s); + select(&mut s, &[t]); + let doc = s.doc().unwrap().doc.clone(); + let undo = undo_labels(&s).len(); + let e = s.execute("paint.setFill", &json!({"color": "#ff0000", "opacity": 40})).unwrap_err(); + assert!(e.to_string().contains("type characters have no opacity of their own"), "{e}"); + assert_eq!(*s.doc().unwrap().doc, *doc); + assert_eq!(undo_labels(&s).len(), undo); + assert_eq!(s.paint.fill, Paint::solid(Color::WHITE), "the defaults keep their paint"); +} + +/// An opacity that no target takes (the only selected object has no fill item) is an error, with or +/// without a paint, and leaves the document as it was; `paint.proxies` answers null for it, and +/// beside an object with a fill item it answers that object's opacity. +#[test] +fn an_opacity_no_target_takes_is_an_error() { + let mut s = session(); + let (a, b) = (rect(&mut s, 10.0), rect(&mut s, 200.0)); + select(&mut s, &[a]); + s.execute("appearance.removeItem", &json!({"index": 0})).unwrap(); + assert!(node(&s, a).appearance.fill().is_none()); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); + let doc = s.doc().unwrap().doc.clone(); + let e = s.execute("paint.setFill", &json!({"opacity": 40})).unwrap_err(); + assert!(e.to_string().contains("no target has that fill or stroke to take the opacity"), "{e}"); + assert_eq!(*s.doc().unwrap().doc, *doc); + // A paint given with the opacity creates the fill, which takes the opacity. + s.execute("paint.setFill", &json!({"color": "#ff0000", "opacity": 40})).unwrap(); + assert!((fill_opacity(&s, a) - 0.4).abs() < 1e-6); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(*s.doc().unwrap().doc, *doc); + + select(&mut s, &[b]); + s.execute("paint.setFill", &json!({"opacity": 70})).unwrap(); + select(&mut s, &[a, b]); + assert_eq!(proxies(&mut s)["fillOpacity"], 70.0, "the first selected object with a fill item answers"); + let out = s.execute("paint.setFill", &json!({"opacity": 20})).unwrap(); + assert_eq!(out["objects"], 1, "the object without a fill item is not counted"); + assert!((fill_opacity(&s, b) - 0.2).abs() < 1e-6); + assert!(node(&s, a).appearance.fill().is_none()); +} + +/// An object selected in a dynamic symbol instance has no opacity of its own: `opacity` is an error +/// that leaves the document alone, and `paint.proxies` answers null. +#[test] +fn an_object_in_a_symbol_instance_refuses_an_opacity() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + let inst = s.execute("symbol.new", &json!({"name": "One", "ids": [id.0], "type": "dynamic"})).unwrap()["id"].clone(); + s.execute("symbol.instance.selectPart", &json!({"id": inst, "path": []})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + for p in [json!({"opacity": 40}), json!({"color": "#ff0000", "opacity": 40})] { + let e = s.execute("paint.setFill", &p).unwrap_err(); + assert!(e.to_string().contains("an object selected in a symbol instance has no fill or stroke opacity of its own"), "{p}: {e}"); + } + assert_eq!(*s.doc().unwrap().doc, *doc); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); +} + +/// A gradient mesh point picked with the Mesh tool takes a fill opacity itself, and the proxy shows +/// it; the object's fill item and the other points stay as they were. +#[test] +fn a_picked_mesh_point_takes_the_fill_opacity() { + let mut s = session(); + let m = rect(&mut s, 10.0); + select(&mut s, &[m]); + s.execute("object.mesh.create", &json!({"rows": 2, "cols": 2})).unwrap(); + select(&mut s, &[m]); + let v = ViewInfo::default(); + let NodeKind::Mesh(g) = &node(&s, m).kind else { panic!("not a mesh") }; + let q = g.points[4].p; + s.select_tool("mesh", v).unwrap(); + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, q.x, q.y), v).unwrap(); + } + s.execute("paint.setFill", &json!({"opacity": 30})).unwrap(); + let NodeKind::Mesh(g) = &node(&s, m).kind else { panic!("not a mesh") }; + let o: Vec = g.points.iter().map(|p| p.opacity).collect(); + assert!((o[4] - 0.3).abs() < 1e-6, "{o:?}"); + assert!(o.iter().enumerate().all(|(i, a)| i == 4 || *a == 1.0), "{o:?}"); + assert_eq!(proxies(&mut s)["fillOpacity"], 30.0); +} + +/// A null `id` or `ids` names no object, so while the Type tool has characters selected the paint +/// goes to those characters only, and the rest of the type keeps its paint. +#[test] +fn a_null_id_leaves_the_paint_to_the_selected_characters() { + for key in ["id", "ids"] { + let mut s = session(); + let t = text(&mut s); + select(&mut s, &[t]); + s.select_tool("type", ViewInfo::default()).unwrap(); + s.set_tool_option("textSelection", &json!({"editing": t.0, "anchor": 0, "caret": 1})); + s.execute("paint.setFill", &json!({"color": "#ff0000", key: null})).unwrap(); + let NodeKind::Text(tx) = &node(&s, t).kind else { panic!("not type") }; + let fills: Vec = tx.runs.iter().map(|r| r.style.fill.clone()).collect(); + assert_eq!(fills.first(), Some(&Paint::solid(Color::rgb8(255, 0, 0))), "{key}: {fills:?}"); + assert!(fills.len() > 1 && fills[1..].iter().all(|f| *f != Paint::solid(Color::rgb8(255, 0, 0))), "{key}: {fills:?}"); + let e = s.execute("paint.setFill", &json!({"opacity": 40, key: null})).unwrap_err(); + assert!(e.to_string().contains("type characters have no opacity of their own"), "{key}: {e}"); + } +} + +/// A selected Live Paint group stands for its faces in a fill opacity and for its edges in a stroke +/// opacity, and `paint.proxies` answers from those same parts. +#[test] +fn a_live_paint_group_answers_from_the_parts_it_sets() { + let mut s = session(); + let id = rect(&mut s, 10.0); + s.execute("livePaint.make", &json!({"ids": [id.0]})).unwrap(); + let g = s.doc().unwrap().selection.objects[0]; + select(&mut s, &[g]); + s.execute("paint.setStroke", &json!({"opacity": 30})).unwrap(); + assert_eq!(proxies(&mut s)["strokeOpacity"], 30.0); + s.execute("paint.setFill", &json!({"opacity": 40})).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 40.0); + assert_eq!(proxies(&mut s)["strokeOpacity"], 30.0); +} + +/// While the Live Paint Bucket is the active tool, a fill or stroke chosen goes to the bucket, so +/// `paint.proxies` answers no opacity for the selection and an opacity is an error that leaves the +/// document as it was. +#[test] +fn the_live_paint_bucket_answers_no_opacity() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + assert_eq!(proxies(&mut s)["fillOpacity"], 100.0); + s.select_tool("livePaintBucket", ViewInfo::default()).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); + assert_eq!(proxies(&mut s)["strokeOpacity"], Value::Null); + let doc = s.doc().unwrap().doc.clone(); + assert!(s.execute("paint.setFill", &json!({"opacity": 40})).is_err()); + assert_eq!(*s.doc().unwrap().doc, *doc); +} + +/// The Eyedropper armed to sample into the Live Paint Bucket's gradient works for the bucket, so +/// the proxies answer no opacity for the selection then too, as they show no paint of its own. +#[test] +fn the_eyedropper_armed_for_the_bucket_answers_no_opacity() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + s.select_tool("eyedropper", ViewInfo::default()).unwrap(); + assert_eq!(proxies(&mut s)["fillOpacity"], 100.0, "the Eyedropper alone shows the selection's"); + s.set_tool_option("stop", &json!("livePaintBucket")); + assert!(s.bucket_paints()); + assert_eq!(proxies(&mut s)["fillOpacity"], Value::Null); + assert_eq!(proxies(&mut s)["strokeOpacity"], Value::Null); +} + +/// A `swatch` that is no name does not turn a request into an opacity alone: it is an error and +/// leaves the document as it was. +#[test] +fn a_swatch_that_is_no_name_is_refused_with_an_opacity() { + let mut s = session(); + let id = rect(&mut s, 10.0); + select(&mut s, &[id]); + let doc = s.doc().unwrap().doc.clone(); + for cmd in ["paint.setFill", "paint.setStroke"] { + for swatch in [json!(5), json!(true), json!(["a"]), json!({})] { + assert!(s.execute(cmd, &json!({"swatch": swatch, "opacity": 40})).is_err(), "{cmd} {swatch}"); + } + // A null swatch names none, so the opacity goes alone. + s.execute(cmd, &json!({"swatch": null, "opacity": 40})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(*s.doc().unwrap().doc, *doc); +} diff --git a/crates/engine/src/tests/panelcmds.rs b/crates/engine/src/tests/panelcmds.rs index 7d2675e938..0e4bdf0ab9 100644 --- a/crates/engine/src/tests/panelcmds.rs +++ b/crates/engine/src/tests/panelcmds.rs @@ -967,6 +967,21 @@ fn a_locked_artboard_protects_the_art_on_it() { assert!(!tile.is_empty() && !tile.contains(&a), "{tile:?}"); } +/// Art on a locked artboard stays unselected when `select.add` adds it after another object. +#[test] +fn art_on_a_locked_artboard_added_after_another_object_stays_unselected() { + let mut s = session(); + let a = rect(&mut s); + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 200, "height": 200})).unwrap(); + let b = NodeId(s.execute("shape.rectangle", &json!({"x": 1010, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + for id in [a, b] { + s.execute("select.add", &json!({"ids": [id.0]})).unwrap(); + } + assert_eq!(s.doc().unwrap().selection.objects, [a]); +} + /// New art on a locked artboard stays selected and editable until the selection leaves it: a /// second Pen click goes on the path the first one started, and pasted art moves. Once another /// object is clicked, a click, a marquee, `select.set` and Select All pass over that art. Undo, in diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index a498049cc3..69fc4dcf78 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -182,6 +182,136 @@ fn filters_make_guides_and_locked_objects_left_unselected() { assert_eq!(st.history.undo.len(), undo + 1); } +/// A compound path handed back with its path as it was keeps its members, hidden and locked ones +/// included. A changed path replaces its members, and is refused while a member is hidden, locked, +/// a guide or not a path, as is turning it into a plain path. +#[test] +fn a_filter_keeps_or_replaces_a_compound_path_s_members_whole() { + use std::sync::Arc; + use vectorcraft_doc::{Appearance, Node, NodeKind}; + use vectorcraft_geom::FillRule; + let mut s = session(); + let compound_of = |s: &mut Session, members: Vec| { + let mut id = NodeId(0); + s.edit("Set up", |d, _| { + let n = Node::new(d.alloc_id(), NodeKind::Compound { children: members.into_iter().map(Arc::new).collect(), rule: FillRule::NonZero }); + let layer = d.layers[0].id; + id = d.insert(Some(layer), usize::MAX, n).unwrap(); + Ok(()) + }) + .unwrap(); + id + }; + let members = |s: &Session, id: NodeId| match &node(s, id).kind { + NodeKind::Compound { children, .. } => children.iter().map(|c| (c.id, c.visible, c.locked, c.path_data().cloned())).collect::>(), + _ => Vec::new(), + }; + let new_ids = |s: &mut Session| s.edit("Set up", |d, _| Ok([d.alloc_id(), d.alloc_id(), d.alloc_id(), d.alloc_id()])).unwrap(); + let [a, b, c, d] = new_ids(&mut s); + let [g, h, i, j] = new_ids(&mut s); + let hidden = |id: NodeId, x: f64| { + let mut n = Node::path(id, square_at(x), Appearance::default()); + n.visible = false; + n + }; + let locked = |id: NodeId, x: f64| { + let mut n = Node::path(id, square_at(x), Appearance::default()); + n.locked = true; + n + }; + // A member with an empty subpath, which plug-in output can't hold, still counts as handed back. + let empty = Node::path(g, PathData::single(SubPath::polyline(&[], false)), Appearance::default()); + let kept = compound_of(&mut s, vec![hidden(a, 40.0), locked(b, 80.0), empty]); + let plain = + compound_of(&mut s, vec![Node::path(c, square_at(120.0), Appearance::default()), Node::path(d, square_at(160.0), Appearance::default())]); + let was = members(&s, kept); + install_wat(&mut s, &tpl::module(&tpl::manifest("test.engine.compound.echo", "filter", "{}"), tpl::ECHO, "", 1)); + run(&mut s, "plugin.run", json!({"id": "test.engine.compound.echo", "ids": [kept.0]})); + assert_eq!(members(&s, kept), was, "handed back as it was, the members stay as they were"); + // New geometry for a compound with a hidden or a locked member, or the same geometry as a plain + // path, is refused, and the document is left alone. + let mut moved = square_at(200.0); + moved.subpaths.extend(square_at(240.0).subpaths); + let reshape = |id: &str, target: NodeId, extra: Value| { + let mut o = json!({"id": target.0, "path": moved.clone()}); + o.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + tpl::returning(&tpl::manifest(id, "filter", "{}"), &json!({ "objects": [o] }).to_string()) + }; + let hidden_only = compound_of(&mut s, vec![hidden(h, 360.0)]); + let locked_only = compound_of(&mut s, vec![Node::path(i, square_at(360.0), Appearance::default()), locked(j, 380.0)]); + // A member that is itself a compound path, shown and unlocked but holding a hidden member: its + // geometry isn't in the input, so a new path or a plain path would drop it. + let [k, l, m, _] = new_ids(&mut s); + let inner = Node::new(k, NodeKind::Compound { children: vec![Arc::new(hidden(l, 400.0))], rule: FillRule::NonZero }); + let nested = compound_of(&mut s, vec![Node::path(m, square_at(440.0), Appearance::default()), inner]); + let was_nested = node(&s, nested).clone(); + run(&mut s, "plugin.run", json!({"id": "test.engine.compound.echo", "ids": [nested.0]})); + assert_eq!(node(&s, nested).kind, was_nested.kind, "handed back as it was, a nested compound member stays"); + let flagged = "a hidden, locked or guide member"; + for (target, why) in [(hidden_only, flagged), (locked_only, flagged), (nested, "a member that isn't a path")] { + install_wat(&mut s, &reshape("test.engine.compound.reshape", target, json!({}))); + let flatten = tpl::returning( + &tpl::manifest("test.engine.compound.flatten", "filter", "{}"), + &json!({"objects": [{"id": target.0, "type": "path"}]}).to_string(), + ); + install_wat(&mut s, &flatten); + let before = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + for id in ["test.engine.compound.reshape", "test.engine.compound.flatten"] { + let e = s.execute("plugin.run", &json!({"id": id, "ids": [target.0]})).unwrap_err().to_string(); + assert!(e.contains(&format!("compound path {} has {why}", target.0)), "{id}: {e}"); + assert_eq!((s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()), before, "{id}"); + } + } + // Without such members, new geometry replaces the members: one per subpath, in the old members' places. + install_wat(&mut s, &reshape("test.engine.compound.reshape", plain, json!({}))); + run(&mut s, "plugin.run", json!({"id": "test.engine.compound.reshape", "ids": [plain.0]})); + let now = members(&s, plain); + assert_eq!(now.iter().map(|m| m.3.clone()).collect::>(), [Some(square_at(200.0)), Some(square_at(240.0))]); + assert!(now.iter().all(|m| m.1 && !m.2), "shown and unlocked members: {now:?}"); + assert_eq!(now.iter().map(|m| m.0).collect::>(), [c, d], "the members keep their places' ids"); + // A guide member is refused the same way, unless the output sets `guide` for the whole object. + let guide_of = |s: &mut Session| { + let [e, f, ..] = new_ids(s); + let mut guide_member = Node::path(e, square_at(280.0), Appearance::default()); + if let NodeKind::Path { guide, .. } = &mut guide_member.kind { + *guide = true; + } + compound_of(s, vec![guide_member, Node::path(f, square_at(320.0), Appearance::default())]) + }; + let guides = |s: &Session, id: NodeId| match &node(s, id).kind { + NodeKind::Compound { children, .. } => children.iter().map(|c| matches!(c.kind, NodeKind::Path { guide: true, .. })).collect::>(), + _ => Vec::new(), + }; + let guide = guide_of(&mut s); + install_wat(&mut s, &reshape("test.engine.compound.reshape", guide, json!({}))); + let err = s.execute("plugin.run", &json!({"id": "test.engine.compound.reshape", "ids": [guide.0]})).unwrap_err().to_string(); + assert!(err.contains("guide member"), "{err}"); + let flatten = tpl::returning( + &tpl::manifest("test.engine.compound.flatten.unflagged", "filter", "{}"), + &json!({"objects": [{"id": guide.0, "type": "path"}]}).to_string(), + ); + install_wat(&mut s, &flatten); + let err = s.execute("plugin.run", &json!({"id": "test.engine.compound.flatten.unflagged", "ids": [guide.0]})).unwrap_err().to_string(); + assert!(err.contains(&format!("compound path {} has {flagged}", guide.0)), "{err}"); + assert_eq!(guides(&s, guide), [true, false], "a refused flatten leaves the guide member as it was"); + for (id, on) in [("test.engine.compound.unguide", false), ("test.engine.compound.reguide", true)] { + let target = guide_of(&mut s); + install_wat(&mut s, &reshape(id, target, json!({ "guide": on }))); + run(&mut s, "plugin.run", json!({"id": id, "ids": [target.0]})); + assert_eq!(members(&s, target).iter().map(|m| m.3.clone()).collect::>(), [Some(square_at(200.0)), Some(square_at(240.0))], "{id}"); + assert_eq!(guides(&s, target), [on, on], "{id}: every new member takes the output's `guide`"); + } + // Turning it into a plain path is allowed the same way when the output sets `guide`. + let target = guide_of(&mut s); + let flatten = tpl::returning( + &tpl::manifest("test.engine.compound.flatten.guide", "filter", "{}"), + &json!({"objects": [{"id": target.0, "type": "path", "guide": true}]}).to_string(), + ); + install_wat(&mut s, &flatten); + run(&mut s, "plugin.run", json!({"id": "test.engine.compound.flatten.guide", "ids": [target.0]})); + assert!(matches!(node(&s, target).kind, NodeKind::Path { guide: true, .. }), "{:?}", node(&s, target).kind); +} + #[test] fn failing_plugins_leave_the_document_and_history_alone() { let mut s = session(); @@ -1808,6 +1938,86 @@ fn filters_keep_their_data_with_the_document() { assert_eq!(data(&s), None); } +/// A filter run whose output changes nothing (an echo) records no undo step, leaves a saved +/// document unmodified and the document as it was, and still selects its objects. One that changes +/// one of the objects records exactly one step, and running it again records none. +#[test] +fn a_filter_run_that_changes_nothing_records_no_undo_step() { + let mut s = session(); + let a = rect(&mut s, 10.0, "#ff0000"); + let b = rect(&mut s, 40.0, "#0000ff"); + let echo = "test.engine.noop.echo"; + install_wat(&mut s, &tpl::module(&tpl::manifest(echo, "filter", "{}"), tpl::ECHO, "", 1)); + run(&mut s, "select.none", json!({})); + s.doc_mut().unwrap().mark_saved(); + let (doc, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let r = run(&mut s, "plugin.run", json!({"id": echo, "ids": [a.0, b.0]})); + assert_eq!(r["ids"], json!([a.0, b.0])); + let st = s.doc().unwrap(); + assert!(std::sync::Arc::ptr_eq(&st.doc, &doc), "the document stays as it was"); + assert_eq!((st.history.undo.len(), st.is_dirty()), (undo, false), "no undo step; still saved"); + assert_eq!(st.selection.objects, [a, b], "its objects are selected"); + // Renaming one object of the two is one undo step. + let renamer = "test.engine.noop.renamer"; + let renamed = json!({"objects": [{"id": a.0, "name": "Renamed"}, {"id": b.0}]}); + install_wat(&mut s, &tpl::returning(&tpl::manifest(renamer, "filter", "{}"), &renamed.to_string())); + run(&mut s, "plugin.run", json!({"id": renamer, "ids": [a.0, b.0]})); + let st = s.doc().unwrap(); + assert_eq!((st.history.undo.len(), st.is_dirty()), (undo + 1, true)); + assert_eq!(node(&s, a).name.as_deref(), Some("Renamed")); + // Run again, it renames nothing: no second step. + run(&mut s, "plugin.run", json!({"id": renamer, "ids": [a.0, b.0]})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + for id in [echo, renamer] { + run(&mut s, "plugin.remove", json!({"id": id})); + } +} + +/// A filter that writes the data it already keeps with the document records no undo step; writing +/// other data, or removing it, records one, and removing data it does not keep records none. +#[test] +fn a_filter_that_keeps_the_same_data_records_no_undo_step() { + let mut s = session(); + let id = rect(&mut s, 10.0, "#ff0000"); + let pid = "test.engine.noop.data"; + let keep = |s: &mut Session, data: Value| { + let out = json!({"objects": [{"id": id.0}], "documentData": data}); + install_wat(s, &tpl::returning(&tpl::manifest(pid, "filter", "{}"), &out.to_string())); + run(s, "plugin.run", json!({"id": pid, "ids": [id.0]})); + s.doc().unwrap().history.undo.len() + }; + let undo = s.doc().unwrap().history.undo.len(); + assert_eq!(keep(&mut s, json!({"pen": 2})), undo + 1); + assert_eq!(keep(&mut s, json!({"pen": 2})), undo + 1, "the same data: no step"); + assert_eq!(keep(&mut s, json!({"pen": 3})), undo + 2); + assert_eq!(keep(&mut s, Value::Null), undo + 3, "removed"); + assert_eq!(keep(&mut s, Value::Null), undo + 3, "nothing kept to remove: no step"); + assert_eq!(s.doc().unwrap().doc.plugin_data(pid), None); + run(&mut s, "plugin.remove", json!({"id": pid})); +} + +/// A plug-in command whose run changes nothing records no undo step, and so does a filter or a +/// command that may call commands and hands back what it is given. +#[test] +fn a_plugin_command_that_changes_nothing_records_no_undo_step() { + let mut s = session(); + rect(&mut s, 10.0, "#ff0000"); + run(&mut s, "select.all", json!({})); + let undo = s.doc().unwrap().history.undo.len(); + let id = "test.engine.noop.cmds"; + install_wat(&mut s, &grower(id)); + run(&mut s, &format!("plugin.{id}.tidy"), json!({})); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "tidy hands back its input"); + run(&mut s, "plugin.remove", json!({"id": id})); + let calling = "test.engine.noop.calling"; + install_echo_calling(&mut s, calling, r#"[{"id":"same","label":"Same"}]"#); + run(&mut s, &format!("plugin.{calling}.same"), json!({})); + run(&mut s, "plugin.run", json!({"id": calling})); + assert!(!s.in_interaction()); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "an echo that may call commands"); + run(&mut s, "plugin.remove", json!({"id": calling})); +} + #[test] fn plugin_management_commands() { let _folder = PREFS_FOLDER.lock().unwrap_or_else(|e| e.into_inner()); @@ -2017,6 +2227,23 @@ fn a_heavy_filter_installs_once_the_user_agrees() { assert!(install(&mut s, DESATURATE).get("budget").is_none()); } +/// A module that carries its manifest in a `vc_manifest` custom section is inspected and installed +/// without any of its code running: its start function traps and its `vc_manifest` export loops. +#[test] +fn a_plugin_with_a_manifest_section_installs_without_running() { + let mut s = session(); + let id = "test.engine.section"; + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","version":"1","kind":"filter","abi":1}}"#); + let extra = r#"(func (export "vc_manifest") (result i64) (loop $l (br $l)) (i64.const 0)) (func $trap unreachable) (start $trap)"#; + let data = vectorcraft_format::base64_encode(&wat::parse_str(tpl::sectioned(&manifest, tpl::ECHO, extra, 1)).unwrap()); + let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": data})); + assert_eq!(inspected["id"], id); + assert!(vectorcraft_plugins::registry::get(id).is_none(), "inspecting installs nothing"); + assert_eq!(run(&mut s, "plugin.install", json!({"dataBase64": data}))["id"], id); + assert!(vectorcraft_plugins::registry::get(id).is_some()); + run(&mut s, "plugin.remove", json!({"id": id})); +} + #[test] fn invalid_install_flags_are_refused() { let mut s = session(); @@ -4733,6 +4960,82 @@ fn plugin_commands_are_registered_run_and_removed() { assert!(s.execute(grow, &json!({})).is_err(), "removed, it no longer runs"); } +/// At API level 2 a command's `menu` lists it in that menu with its plug-in's name after its +/// label, and `plugin.list` gives its `menu` with `after` escaped. A command whose label reads like +/// a built-in command of that menu, or like a command a plug-in with a lower id places there, +/// stays in its plug-in's submenu, and `plugin.list` marks it `placed: false`. Replaced by a module +/// whose command has no `menu`, a command is back in its submenu. +#[test] +fn placed_plugin_commands_are_listed_in_their_menu() { + let mut s = session(); + let placing = |id: &str, name: &str, commands: &str| { + let manifest = format!(r#"{{"id":"{id}","name":"{name}","api":2,"version":"1","kind":"filter","commands":{commands}}}"#); + tpl::returning(&manifest, r#"{"objects":[]}"#) + }; + let (ant, bee, cat) = ("test.engine.place.ant", "test.engine.place.bee", "test.engine.place.cat"); + let low = |id: &str| crate::cmd::plugin::command_id(id, "low"); + let menu_of = |s: &Session, command: &str| listed(s, command).map(|c| c.menu.iter().map(|m| m.to_string()).collect::>()); + let in_select = json!([{"id": "low", "label": "Low Area", "menu": {"path": ["Select"], "after": "\u{202E}Inverse"}}]).to_string(); + let in_select = in_select.as_str(); + + let info = install_wat(&mut s, &placing(ant, "Tidy", in_select)); + let menu = &info["commands"][0]["menu"]; + assert_eq!(menu["path"], json!(["Select"])); + assert!(menu["after"].as_str().is_some_and(|a| a.ends_with("Inverse") && !a.contains('\u{202E}')), "escaped: {menu}"); + assert!(menu.get("placed").is_none(), "{menu}"); + let c = listed(&s, &low(ant)).expect("listed"); + assert_eq!((c.label, menu_of(&s, &low(ant))), ("Low Area (Tidy)", Some(vec!["Select".to_string()]))); + + // Another plug-in of the same name placing the same label at the same spot stays in its submenu. + let info = install_wat(&mut s, &placing(bee, "Tidy", in_select)); + assert_eq!(info["commands"][0]["menu"]["placed"], json!(false)); + assert_eq!(listed(&s, &low(bee)).map(|c| c.label), Some("Low Area")); + assert_eq!(menu_of(&s, &low(bee)), Some(vec!["Object".into(), "Plug-ins".into(), "Tidy".into()])); + assert_eq!(menu_of(&s, &low(ant)), Some(vec!["Select".to_string()])); + + // `Paste (in Place)` reads like Edit's Paste in Place; Keep is placed. + let edit = r#"[{"id":"paste","label":"Paste","menu":{"path":["Edit"]}},{"id":"keep","label":"Keep","menu":{"path":["Edit"]}}]"#; + let info = install_wat(&mut s, &placing(cat, "in Place", edit)); + assert_eq!(info["commands"][0]["menu"]["placed"], json!(false)); + assert!(info["commands"][1]["menu"].get("placed").is_none()); + let paste = crate::cmd::plugin::command_id(cat, "paste"); + assert_eq!(menu_of(&s, &paste), Some(vec!["Object".into(), "Plug-ins".into(), "in Place".into()])); + assert_eq!(menu_of(&s, &crate::cmd::plugin::command_id(cat, "keep")), Some(vec!["Edit".to_string()])); + // `Stop Global (Edit)` reads like the other label of Select's Start Global Edit. + let dog = "test.engine.place.dog"; + let info = install_wat(&mut s, &placing(dog, "Edit", r#"[{"id":"stop","label":"Stop Global","menu":{"path":["Select"]}}]"#)); + assert_eq!(info["commands"][0]["menu"]["placed"], json!(false)); + run(&mut s, "plugin.remove", json!({"id": dog})); + // Object's Show All has one label, so `Hide (All)` is placed beside it. + let all = "test.engine.place.all"; + let info = install_wat(&mut s, &placing(all, "All", r#"[{"id":"hide","label":"Hide","menu":{"path":["Object"]}}]"#)); + assert!(info["commands"][0]["menu"].get("placed").is_none(), "{}", info["commands"][0]); + assert_eq!(menu_of(&s, &crate::cmd::plugin::command_id(all, "hide")), Some(vec!["Object".to_string()])); + run(&mut s, "plugin.remove", json!({"id": all})); + // `Hide (Edges)` reads like the desktop app's View › Hide Edges, with or without the desktop app. + let edges = "test.engine.place.edges"; + let info = install_wat(&mut s, &placing(edges, "Edges", r#"[{"id":"hide","label":"Hide","menu":{"path":["View"]}}]"#)); + assert_eq!(info["commands"][0]["menu"]["placed"], json!(false)); + run(&mut s, "plugin.remove", json!({"id": edges})); + // Inspecting a plug-in that is not installed reports what installing it gives: of two commands + // with one label at one spot, the second stays in its submenu. + let twice = r#"[{"id":"a","label":"Low","menu":{"path":["Select"]}},{"id":"b","label":"Low","menu":{"path":["Select"]}}]"#; + let data = vectorcraft_format::base64_encode(&wat::parse_str(placing("test.engine.place.eel", "Eel", twice)).unwrap()); + let inspected = run(&mut s, "plugin.inspect", json!({"dataBase64": data})); + assert!(inspected["commands"][0]["menu"].get("placed").is_none(), "{inspected}"); + assert_eq!(inspected["commands"][1]["menu"]["placed"], json!(false), "{inspected}"); + + // Replaced by a module whose command has no `menu`, Ant's command is back in its submenu and + // Bee's takes the spot. + install_wat(&mut s, &placing(ant, "Tidy", r#"[{"id":"low","label":"Low Area"}]"#)); + assert_eq!(menu_of(&s, &low(ant)), Some(vec!["Object".into(), "Plug-ins".into(), "Tidy".into()])); + assert_eq!(menu_of(&s, &low(bee)), Some(vec!["Select".to_string()])); + for id in [ant, bee, cat] { + run(&mut s, "plugin.remove", json!({"id": id})); + } + assert!(listed(&s, &low(bee)).is_none()); +} + /// A command run is journaled like any other, so an action records it with its parameters and /// plays it back. #[test] @@ -5461,13 +5764,12 @@ fn deferred_move(s: &mut Session) -> NodeId { r } -/// The rectangle a run named `label` during [`deferred_move`] left: moved, with the interaction -/// ended and the move an undo step of its own before the run's. -fn assert_moved_once(s: &Session, r: NodeId, label: &str) { +/// The rectangle a run that hands back what it is given left during [`deferred_move`]: moved, with +/// the interaction ended and the move the last undo step, since the run changed nothing. +fn assert_moved_once(s: &Session, r: NodeId) { assert!(!s.in_interaction()); assert_eq!(node(s, r).geometric_bounds().unwrap().x0, 17.0, "the filter was given the moved rectangle"); - let labels: Vec<&str> = s.doc().unwrap().history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect(); - assert_eq!(labels, [label, "Move"]); + assert_eq!(s.doc().unwrap().history.undo.last().map(|e| e.label.as_str()), Some("Move")); } /// With Real-time Drawing off, `plugin.run` of a filter that calls commands during a drag applies @@ -5479,7 +5781,7 @@ fn a_filter_that_calls_commands_is_given_a_deferred_move() { install_echo_calling(&mut s, id, "[]"); let r = deferred_move(&mut s); run(&mut s, "plugin.run", json!({"id": id})); - assert_moved_once(&s, r, &format!("Test {id}")); + assert_moved_once(&s, r); run(&mut s, "plugin.remove", json!({"id": id})); } @@ -5492,6 +5794,6 @@ fn a_plugin_command_that_calls_commands_is_given_a_deferred_move() { install_echo_calling(&mut s, id, r#"[{"id":"same","label":"Same"}]"#); let r = deferred_move(&mut s); run(&mut s, &format!("plugin.{id}.same"), json!({})); - assert_moved_once(&s, r, "Same"); + assert_moved_once(&s, r); run(&mut s, "plugin.remove", json!({"id": id})); } diff --git a/crates/engine/src/tests/printps.rs b/crates/engine/src/tests/printps.rs index ad83ade900..a5e97f3e04 100644 --- a/crates/engine/src/tests/printps.rs +++ b/crates/engine/src/tests/printps.rs @@ -125,3 +125,33 @@ fn type_that_does_not_fit_its_frame_is_named_when_its_artboard_prints() { let (_, v) = print_ps(&mut s, json!({"settings": {"artboards": "range", "range": "1"}})); assert_eq!(over(&v), 0, "{v}"); } + +/// Graphics › Fonts reaches the PostScript output: Subset (the default) sends each page the +/// glyphs it shows, None names the printer's font and sends none, Complete sends every glyph once +/// before the first page. PDF output notes that it embeds subsets. +#[test] +fn the_fonts_setting_chooses_how_type_is_sent() { + let mut s = session(1); + s.execute("text.create", &json!({"x": 20, "y": 100, "text": "Ab", "size": 24})).unwrap(); + assert_eq!(s.execute("print.setup", &json!({})).unwrap()["settings"]["graphics"]["fonts"], "subset"); + let fonts = |s: &mut Session, f: &str| print_ps(s, json!({"settings": {"graphics": {"fonts": f}}})); + let (ps, _) = print_ps(&mut s, json!({})); + let page = ps.split("%%Page: ").nth(1).unwrap(); + assert_eq!(page.matches("/FontType 3 def").count(), 1, "{ps}"); + assert_eq!(page.matches("> show").count(), 2, "{page}"); + assert_eq!(dsc(&ps, "DocumentSuppliedResources"), ["font VCft0.0"]); + let (ps, v) = fonts(&mut s, "none"); + assert!(!ps.contains("FontType") && !ps.contains("%%BeginResource"), "{ps}"); + assert_eq!(dsc(&ps, "DocumentNeededResources").len(), 1, "{ps}"); + assert!(v["warnings"].to_string().contains("the printer needs the font"), "{v}"); + let (ps, _) = fonts(&mut s, "complete"); + let (head, pages) = ps.split_once("%%EndSetup").unwrap(); + assert!(head.contains("/FontType 3 def") && !pages.contains("FontType") && pages.contains("> show"), "{ps}"); + let (ps, _) = fonts(&mut s, "subset"); + assert_eq!(ps.split("%%Page: ").nth(1).unwrap().matches("/FontType 3 def").count(), 1); + // PDF output embeds subsets whatever the setting, and says so. + for (f, noted) in [("none", true), ("subset", false), ("complete", true)] { + let v = s.execute("file.print", &json!({"settings": {"graphics": {"fonts": f}}})).unwrap(); + assert_eq!(v["warnings"].to_string().contains("PDF print embeds subsets"), noted, "{f}: {v}"); + } +} diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index 754dda7e42..d9945fa723 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -550,6 +550,18 @@ fn continuous_arc_after_a_line(s: &mut Session, v: ViewInfo) { key(s, ToolKey::AltTap); } +/// Whether the tool shows only the path's points and its length handles (a handle and the line to +/// it from the path's end): no hover preview, label or Smart Guide. +fn only_points(s: &mut Session, v: ViewInfo) -> bool { + let o = s.overlays(v); + let handles: Vec = o.iter().filter_map(|o| if let Overlay::Handle { p, .. } = o { Some(*p) } else { None }).collect(); + o.iter().all(|o| match o { + Overlay::CurvePoint { .. } | Overlay::Handle { .. } => true, + Overlay::Line { b, .. } => handles.contains(b), + _ => false, + }) +} + /// The last point of the path the tool drew (any other path is a two-point line). fn drawn_end(s: &Session) -> Point { let drawn = paths(s).into_iter().find(|(_, p)| p.subpaths[0].anchors.len() >= 3).unwrap(); @@ -710,9 +722,8 @@ fn a_hover_shows_nothing_after_smart_guides_change() { s.pointer(&PointerEvent::new(PointerKind::Move, at.x, at.y), on).unwrap(); let off_anchor = label(&mut s, on).unwrap() - at; assert!(off_anchor.x > 0.0 && (off_anchor.x - off_anchor.y).abs() < 1e-9, "the label sits diagonally off the anchor: {off_anchor:?}"); - let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. })); assert!(!only_points(&mut s, on)); - assert!(only_points(&mut s, off), "only the path's points show"); + assert!(only_points(&mut s, off), "only the path's points and length handles show"); // A click before the pointer moves does not bring the stale hover back. press_in(&mut s, &[(400.0, 300.0)], off); assert_eq!(label(&mut s, off), None, "no label for the stale hover after the click"); @@ -746,7 +757,6 @@ fn a_click_that_adds_nothing_keeps_a_stale_hover_hidden() { s.execute("select.set", &json!({"ids": []})).unwrap(); continuous_arc_after_a_line(&mut s, on); s.pointer(&PointerEvent::new(PointerKind::Move, 200.0, 100.0), on).unwrap(); - let only_points = |s: &mut Session, v: ViewInfo| s.overlays(v).iter().all(|o| matches!(o, Overlay::CurvePoint { .. })); assert!(!only_points(&mut s, on), "the anchor's guide shows"); assert!(only_points(&mut s, off)); let steps = undo_steps(&s); @@ -794,6 +804,33 @@ fn a_hovered_arc_shows_the_protractor_with_the_rubber_band() { } } +/// The two arms of a cross centered on `c` among the overlays. +fn crosses_at(o: &[Overlay], c: Point) -> usize { + o.iter().filter(|o| matches!(o, Overlay::Line { a, b, .. } if a.midpoint(*b).distance(c) < 1e-9)).count() +} + +/// While a half circle from (200, 100) to (300, 100) is dragged, or is the piece the next click +/// adds, the tool shows a cross at its center, (250, 100); while a line is dragged, it shows none. +#[test] +fn an_arc_shows_a_cross_at_its_center() { + let mut s = session(); + quick_pen(&mut s); + let center = pt(250.0, 100.0); + for (action, arms) in [("line", 0), ("sharpArc", 2)] { + key(&mut s, ToolKey::Escape); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "line"})).unwrap(); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": action})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Move, 300.0, 100.0), view()).unwrap(); + assert_eq!(crosses_at(&s.overlays(view()), center), arms, "hovering, {action}"); + s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 150.0), view()).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 100.0), view()).unwrap(); + assert_eq!(crosses_at(&s.overlays(view()), center), arms, "dragging, {action}"); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 100.0), view()).unwrap(); + } +} + /// With Measurement Labels on, hovering after the path's last point shows the distance label /// beside the pointer; with them off, no label shows. #[test] @@ -864,6 +901,467 @@ fn path_quick_pen_refuses_bad_params() { assert_eq!(paths(&s).len(), before.len()); } +/// The handle beyond the end of the path being drawn makes its last line longer, as one undo step, +/// and the next click goes on from the new end. +#[test] +fn dragging_the_end_handle_lengthens_the_last_line() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let undo = undo_steps(&s); + // The handle stands 20 screen points beyond the end, along the line. + press(&mut s, &[(220.0, 100.0), (250.0, 130.0), (280.0, 140.0)]); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(260.0, 100.0)]); + assert_eq!(undo_steps(&s), undo + 1); + click(&mut s, 260.0, 200.0); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(260.0, 100.0), pt(260.0, 200.0)], "the drawing went on"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(200.0, 100.0)); +} + +/// Dragged by its end handle, the last sharp-corner arc goes on around its circle and stays the +/// last piece, so C still flips it and `[` `]` still change its size. +#[test] +fn a_dragged_last_arc_still_flips() { + let mut s = session(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + click(&mut s, 300.0, 300.0); + let undo = undo_steps(&s); + // The half circle over (200, 300) ends heading down, so its end handle is 20 points below. The + // handle turned a quarter around the center, to (180, 400), takes the end to (200, 400). + press(&mut s, &[(300.0, 320.0), (260.0, 400.0), (180.0, 400.0)]); + let sp = only_path(&s); + assert!(sp.anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6, "three quarters around: {:?}", sp.anchors.last()); + assert_eq!(sp.anchors.len(), 4); + assert_eq!(undo_steps(&s), undo + 1); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view())); + key(&mut s, ToolKey::Letter('c')); + let flipped = only_path(&s); + assert_ne!(flipped, sp); + assert!(flipped.anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6); + assert_eq!(undo_steps(&s), undo + 2); + // `]` makes the dragged arc 15° larger: it keeps its ends and gains its own undo step. + key(&mut s, ToolKey::BracketRight); + let larger = only_path(&s); + assert_ne!(larger, flipped); + assert!(larger.anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6); + assert_eq!(undo_steps(&s), undo + 3); +} + +/// Dragged back past its start, the last sharp-corner arc stops at 1°. +#[test] +fn a_dragged_last_arc_keeps_at_least_one_degree() { + let mut s = session(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + click(&mut s, 300.0, 300.0); + // The half circle about (200, 300) runs over the top from (100, 300) to (300, 300); its end + // handle is 20 points below the end. The pointer goes back around the circle from there, past + // the start of the arc. + let (c, r) = (pt(200.0, 300.0), (100.0f64 * 100.0 + 20.0 * 20.0).sqrt()); + let a0 = 20.0f64.atan2(100.0); + let mut pts = vec![(300.0, 320.0)]; + for d in [45.0f64, 90.0, 135.0, 175.0, 185.0] { + let a = a0 - d.to_radians(); + pts.push((c.x + r * a.cos(), c.y + r * a.sin())); + } + press(&mut s, &pts); + let sp = only_path(&s); + let one = 181f64.to_radians(); + let end = pt(200.0 + 100.0 * one.cos(), 300.0 + 100.0 * one.sin()); + assert!(sp.anchors.last().unwrap().p.distance(end) < 1e-6, "{:?}", sp.anchors.last()); + assert_eq!(sp.anchors.first().unwrap().p, pt(100.0, 300.0)); +} + +/// When the last arc goes on around the circle of the arc before it, its end handle still changes +/// the last arc alone, which C then still flips. +#[test] +fn the_end_handle_changes_the_last_arc_on_a_shared_circle() { + let mut s = session(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + click(&mut s, 300.0, 300.0); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "turn", "value": 90})).unwrap(); + // A quarter more around the circle about (200, 300), ending heading left. + click(&mut s, 200.0, 400.0); + let r = 100.0 * std::f64::consts::FRAC_1_SQRT_2; + let to = pt(200.0 - r, 300.0 + r); + // The handle at (180, 400) turned 45° more around the center takes the end there with it. + let (sin, cos) = std::f64::consts::FRAC_PI_4.sin_cos(); + let (hx, hy) = (-20.0, 100.0); + let pointer = (200.0 + hx * cos - hy * sin, 300.0 + hx * sin + hy * cos); + press(&mut s, &[(180.0, 400.0), (170.0, 400.0), pointer]); + let sp = only_path(&s); + assert!(sp.anchors.last().unwrap().p.distance(to) < 1e-6, "135° from (300, 300): {:?}", sp.anchors.last()); + assert!(sp.anchors.get(2).unwrap().p.distance(pt(300.0, 300.0)) < 1e-9, "the first arc stays"); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view())); +} + +/// Once another path is selected while one was being drawn, the selected path shows its handles. +#[test] +fn another_selected_path_shows_its_handles() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let r = s.execute("shape.line", &json!({"x1": 300, "y1": 300, "x2": 400, "y2": 300})).unwrap(); + s.execute("select.set", &json!({"ids": [r["id"]]})).unwrap(); + let handle = + |s: &mut Session| s.overlays(view()).iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Handle { p, .. } if *p == pt(420.0, 300.0))); + assert!(handle(&mut s)); + assert_eq!(s.cursor(pt(420.0, 300.0), Mods::default(), view()), vectorcraft_tools::Cursor::Move); +} + +/// A selected path that is not being drawn shows its handles: the one before its start makes the +/// first arc shorter around its circle. Escape during a drag takes the drag back. +#[test] +fn the_start_handle_of_a_selected_path_shortens_its_arc() { + let mut s = session(); + let r = s + .execute("path.quickPen", &json!({"start": [100, 100], "pieces": [{"x": 200, "y": 100, "action": "sharpArc"}, {"x": 300, "y": 100}]})) + .unwrap(); + s.execute("select.set", &json!({"ids": [r["id"]]})).unwrap(); + quick_pen(&mut s); + let undo = undo_steps(&s); + let before = only_path(&s); + // The half circle leaves (100, 100) heading up, so its start handle is 20 points below. + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 120.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 150.0, 70.0), v).unwrap(); + assert_ne!(only_path(&s), before, "previewed"); + key(&mut s, ToolKey::Escape); + s.pointer(&PointerEvent::new(PointerKind::Up, 150.0, 70.0), v).unwrap(); + assert_eq!(only_path(&s), before, "taken back"); + assert_eq!(undo_steps(&s), undo); + // The handle turned a quarter around the center, to (130, 50), takes the start to the top of + // the circle: the arc is a quarter from there to (200, 100). + press(&mut s, &[(100.0, 120.0), (130.0, 50.0)]); + let sp = only_path(&s); + assert!(sp.anchors.first().unwrap().p.distance(pt(150.0, 50.0)) < 1e-6, "{:?}", sp.anchors.first()); + assert_eq!(sp.anchors.len(), 3); + assert_eq!(undo_steps(&s), undo + 1); +} + +/// A click on a length handle that does not drag is an ordinary click: while drawing it adds a +/// point there, and with no path being drawn it starts a new path. +#[test] +fn a_click_on_a_handle_adds_a_point() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let undo = undo_steps(&s); + click(&mut s, 220.0, 100.0); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(220.0, 100.0)]); + assert_eq!(undo_steps(&s), undo + 1); + // After Escape the path stays selected with its handles; a click on one starts a new path. + key(&mut s, ToolKey::Escape); + assert_eq!(s.cursor(pt(240.0, 100.0), Mods::default(), view()), vectorcraft_tools::Cursor::Move); + click(&mut s, 240.0, 100.0); + assert_eq!(paths(&s).len(), 2); +} + +/// During a length drag the tool shows the handle and no preview of a next piece to where the +/// pointer was before the press. +#[test] +fn a_length_drag_shows_no_next_piece() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Move, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 100.0), v).unwrap(); + let o = s.overlays(v); + assert!(o.iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Handle { .. }))); + assert!(!o.iter().any(|o| matches!(o, vectorcraft_tools::Overlay::Path { .. } | vectorcraft_tools::Overlay::Measure { .. })), "{o:?}"); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(260.0, 100.0)); +} + +/// A press on a length handle clears the Smart Guides of the hover before it, so none show during +/// the drag. +#[test] +fn a_length_drag_shows_no_smart_guide() { + let mut s = session(); + s.execute("shape.line", &json!({"x1": 220, "y1": 100, "x2": 220, "y2": 300})).unwrap(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let on = ViewInfo { smart_guides: true, ..Default::default() }; + // The end handle stands on the other line's anchor, so the hover there shows its guide. + s.pointer(&PointerEvent::new(PointerKind::Move, 220.0, 100.0), on).unwrap(); + assert!(!only_points(&mut s, on), "the anchor's guide shows"); + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), on).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 140.0), on).unwrap(); + assert!(only_points(&mut s, on), "no guide during the drag: {:?}", s.overlays(on)); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 140.0), on).unwrap(); + let drawn = paths(&s).into_iter().find(|(_, p)| p.subpaths[0].anchors.first().is_some_and(|a| a.p == pt(100.0, 100.0))).unwrap(); + assert_eq!(drawn.1.subpaths[0].anchors.last().unwrap().p, pt(260.0, 100.0)); +} + +/// A length drag that would take the path past the canvas leaves it where the drag last put it, +/// and the drawing goes on from there. +#[test] +fn a_length_drag_stays_on_the_canvas() { + let mut s = session(); + quick_pen(&mut s); + let x = vectorcraft_doc::MAX_COORD - 1000.0; + click(&mut s, x, 100.0); + click(&mut s, x + 500.0, 100.0); + let undo = undo_steps(&s); + let before = only_path(&s); + // The end handle is at x + 520; a drag to x + 2000 would put the end at x + 1980, past the canvas. + press(&mut s, &[(x + 520.0, 100.0), (x + 2000.0, 100.0)]); + assert_eq!(only_path(&s), before); + assert_eq!(undo_steps(&s), undo); + press(&mut s, &[(x + 520.0, 100.0), (x + 820.0, 100.0)]); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(x + 800.0, 100.0)); + assert_eq!(undo_steps(&s), undo + 1); + click(&mut s, x + 800.0, 200.0); + assert_eq!(only_path(&s).anchors.len(), 3, "the drawing went on"); +} + +/// A length drag across a line, or out along it and back, leaves its length as it was: it changes +/// nothing and records no undo step, on the path being drawn and on a selected path. +#[test] +fn a_length_drag_that_keeps_the_length_records_no_undo_step() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let undo = undo_steps(&s); + let before = only_path(&s); + // The end handle is at (220, 100); the first drag goes straight down from it, the second out + // along the line and back. + for drag in [[(220.0, 100.0), (220.0, 160.0), (220.0, 160.0)], [(220.0, 100.0), (260.0, 100.0), (220.0, 100.0)]] { + press(&mut s, &drag); + assert_eq!(only_path(&s), before, "{drag:?}"); + assert_eq!(undo_steps(&s), undo, "{drag:?}"); + } + key(&mut s, ToolKey::Escape); + let undo = undo_steps(&s); + for drag in [[(220.0, 100.0), (220.0, 160.0), (220.0, 160.0)], [(220.0, 100.0), (260.0, 100.0), (220.0, 100.0)]] { + press(&mut s, &drag); + assert_eq!(only_path(&s), before, "{drag:?}"); + assert_eq!(undo_steps(&s), undo, "{drag:?}"); + } +} + +/// The paths of a selected compound path show length handles, also after a drag selected the +/// compound again. +#[test] +fn a_compound_path_shows_the_length_handles_of_its_paths() { + let mut s = session(); + let a = s.execute("path.quickPen", &json!({"start": [100, 100], "pieces": [{"x": 200, "y": 100}]})).unwrap(); + let b = s.execute("path.quickPen", &json!({"start": [100, 300], "pieces": [{"x": 200, "y": 300}]})).unwrap(); + s.execute("select.set", &json!({"ids": [a["id"], b["id"]]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + quick_pen(&mut s); + press(&mut s, &[(220.0, 100.0), (250.0, 100.0), (280.0, 100.0)]); + press(&mut s, &[(220.0, 300.0), (250.0, 300.0), (270.0, 300.0)]); + let mut ends: Vec = paths(&s).iter().filter_map(|(_, pd)| pd.subpaths[0].anchors.last().map(|a| a.p)).collect(); + ends.sort_by(|p, q| p.y.total_cmp(&q.y)); + assert_eq!(ends, [pt(260.0, 100.0), pt(250.0, 300.0)]); +} + +/// An edit made outside the tool during a length press ends the press: a later drag does not +/// preview from the path as the press found it, and so does not undo the edit. +#[test] +fn an_outside_edit_during_a_length_press_is_kept() { + // The edit comes before the first drag event, or after the drag began. + for began in [false, true] { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + let id = paths(&s)[0].0.0; + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + if began { + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 100.0), v).unwrap(); + } + s.execute("path.quickPenLength", &json!({"id": id, "length": 40})).unwrap(); + let edited = only_path(&s); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s), edited, "began: {began}"); + } + // Escape after the edit takes the drag back without taking the edit back. + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + let id = paths(&s)[0].0.0; + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 100.0), v).unwrap(); + s.execute("path.quickPenLength", &json!({"id": id, "length": 40})).unwrap(); + let edited = only_path(&s); + key(&mut s, ToolKey::Escape); + s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s), edited, "escape"); +} + +/// C and `[` `]` wait for a length drag to end: they neither add an undo step of their own nor +/// change the arc the drag is changing. +#[test] +fn piece_keys_do_nothing_during_a_length_drag() { + let mut s = session(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + click(&mut s, 300.0, 300.0); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 320.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 260.0, 400.0), v).unwrap(); + let during = only_path(&s); + for k in [ToolKey::Letter('c'), ToolKey::BracketRight, ToolKey::BracketLeft] { + assert!(s.tool_claims_key(k, view()), "{k:?} stays with the tool"); + key(&mut s, k); + assert_eq!(only_path(&s), during, "{k:?}"); + } + s.pointer(&PointerEvent::new(PointerKind::Drag, 180.0, 400.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 180.0, 400.0), v).unwrap(); + assert_eq!(undo_steps(&s), undo + 1); + assert!(only_path(&s).anchors.last().unwrap().p.distance(pt(200.0, 400.0)) < 1e-6); +} + +/// Choosing Quick Pen again during a length drag leaves the drawing alone: the drag goes on, ends +/// where the pointer is let go, and the next click goes on drawing the same path. +#[test] +fn choosing_the_tool_again_during_a_length_drag_keeps_the_drawing() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 130.0), v).unwrap(); + quick_pen(&mut s); + s.pointer(&PointerEvent::new(PointerKind::Drag, 280.0, 140.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 140.0), v).unwrap(); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(260.0, 100.0)]); + click(&mut s, 260.0, 200.0); + assert_eq!(paths(&s).len(), 1, "the drawing went on"); + assert_eq!(only_path(&s).anchors.len(), 3); +} + +/// A length drag ends where the pointer is let go, also when no drag event came after the press. +#[test] +fn a_length_drag_ends_at_the_release_point() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 220.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 280.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(260.0, 100.0)); + assert_eq!(undo_steps(&s), undo + 1); + // A press let go away from the handle without a drag event drags too. + s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 320.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(300.0, 100.0)); + assert_eq!(only_path(&s).anchors.len(), 2); + assert_eq!(undo_steps(&s), undo + 2); +} + +/// `path.quickPenLength` refuses a result past the canvas, not only one past the input limit. +#[test] +fn path_quick_pen_length_stays_on_the_canvas() { + let mut s = session(); + let x = vectorcraft_doc::MAX_COORD - 500_000.0; + let r = s.execute("path.quickPen", &json!({"start": [x, 0], "pieces": [{"x": x + 10.0, "y": 0}]})).unwrap(); + let id = r["id"].as_u64().unwrap(); + let before = only_path(&s); + let undo = undo_steps(&s); + let e = s.execute("path.quickPenLength", &json!({"id": id, "length": 1_000_000})).unwrap_err().to_string(); + assert!(e.contains("would exceed the canvas"), "{e}"); + assert_eq!(only_path(&s), before); + assert_eq!(undo_steps(&s), undo); + s.execute("path.quickPenLength", &json!({"id": id, "length": 400_000})).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(x + 400_000.0, 0.0)); +} + +/// Dragged by the start handle while the path is being drawn, the first line changes and the last +/// sharp-corner arc stays the last piece, so C still flips it. +#[test] +fn the_start_handle_keeps_the_last_arc_a_piece() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 300.0); + click(&mut s, 200.0, 300.0); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 400.0, 300.0); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view())); + let undo = undo_steps(&s); + // The line leaves (100, 300) heading left, seen from the start, so its handle is 20 points left. + press(&mut s, &[(80.0, 300.0), (60.0, 300.0), (50.0, 300.0)]); + let sp = only_path(&s); + assert_eq!(sp.anchors.first().unwrap().p, pt(70.0, 300.0)); + assert_eq!(undo_steps(&s), undo + 1); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view()), "the last arc is still a piece"); + key(&mut s, ToolKey::Letter('c')); + let flipped = only_path(&s); + assert_ne!(flipped, sp); + assert_eq!(flipped.anchors.first().unwrap().p, pt(70.0, 300.0)); + assert!(flipped.anchors.last().unwrap().p.distance(pt(400.0, 300.0)) < 1e-9); +} + +/// `path.quickPenLength` sets the length of a line or an arc at either end; the same length +/// changes nothing and records no undo step; bad params are refused. +#[test] +fn path_quick_pen_length_sets_an_end() { + let mut s = session(); + let r = s.execute("path.quickPen", &json!({"start": [0, 0], "pieces": [{"x": 100, "y": 0}, {"x": 200, "y": 0, "action": "sharpArc"}]})).unwrap(); + let id = r["id"].as_u64().unwrap(); + let r = s.execute("path.quickPenLength", &json!({"id": id, "end": "start", "length": 40})).unwrap(); + assert_eq!((r["kind"].as_str(), r["length"].as_f64()), (Some("line"), Some(40.0))); + assert_eq!(only_path(&s).anchors.first().unwrap().p, pt(60.0, 0.0)); + let undo = undo_steps(&s); + let r = s.execute("path.quickPenLength", &json!({"id": id, "length": std::f64::consts::PI * 50.0})).unwrap(); + assert_eq!(r["kind"], "arc"); + assert_eq!(undo_steps(&s), undo, "unchanged"); + s.execute("path.quickPenLength", &json!({"id": id, "length": std::f64::consts::PI * 25.0})).unwrap(); + assert!(only_path(&s).anchors.last().unwrap().p.distance(pt(150.0, -50.0)) < 1e-9); + assert_eq!(undo_steps(&s), undo + 1); + let before = paths(&s); + let bad: [Value; 7] = [ + json!({"length": 10}), + json!({"id": id}), + json!({"id": id, "length": "10"}), + json!({"id": id, "length": 0}), + json!({"id": id, "length": 1e7, "end": "start"}), + json!({"id": id, "length": 10, "end": "middle"}), + json!({"id": id, "length": 10, "subpath": 1}), + ]; + for p in bad { + assert!(s.execute("path.quickPenLength", &p).is_err(), "{p}"); + } + let curve = s.execute("shape.line", &json!({"x1": 0, "y1": 300, "x2": 100, "y2": 300})).unwrap(); + s.execute("path.convertAnchor", &json!({"id": curve["id"], "anchor": 1, "to": "smooth", "x": 150, "y": 360})).unwrap(); + assert!(s.execute("path.quickPenLength", &json!({"id": curve["id"], "length": 10})).is_err(), "not a line or an arc"); + s.execute("path.quickPen", &json!({"id": id, "closed": true})).unwrap(); + assert!(s.execute("path.quickPenLength", &json!({"id": id, "length": 10})).is_err(), "closed"); + assert_eq!(paths(&s).len(), before.len() + 1); +} + /// With `id` and `keep`, the points after the first `keep` are replaced by the pieces. #[test] fn path_quick_pen_replaces_the_points_after_keep() { diff --git a/crates/engine/src/tests/recovery.rs b/crates/engine/src/tests/recovery.rs index aa5a7e5ab5..80d993870c 100644 --- a/crates/engine/src/tests/recovery.rs +++ b/crates/engine/src/tests/recovery.rs @@ -1785,3 +1785,70 @@ fn a_crash_between_a_copys_document_and_its_details_keeps_every_image() { assert_eq!(images_of(&s), images, "first copy: {first}"); } } + +/// A crash between writing a copy's document and its details, after a script's command changed +/// the document since the last copy, restores the document as one a script opened. +#[test] +fn a_crash_between_a_copys_document_and_its_details_keeps_a_scripts_change() { + let store = Arc::new(MemoryStore::default()); + let mut s = session_in(&store); + s.execute("file.recovery.save", &json!({})).unwrap(); + let source = "vc.run('shape.ellipse', {x: 80, y: 20, width: 20, height: 20});"; + s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap(); + assert!(s.doc().unwrap().by_script.is_some(), "the script's command changed the document"); + let doc = vectorcraft_doc::Document::clone(&s.doc().unwrap().doc); + s.recovery.set_store(Arc::new(DiesAfterDocument { inner: store.clone(), dead: Default::default() })); + assert!(s.execute("file.recovery.save", &json!({})).is_err(), "the details weren't written"); + drop(s); + let mut s = relaunch(&store); + assert_eq!(restored(s.execute("file.recovery.restore", &json!({})).unwrap()), 1); + let count = |d: &vectorcraft_doc::Document| d.layers.iter().map(|l| l.count()).sum::(); + assert_eq!(count(&s.doc().unwrap().doc), count(&doc), "the new document is in"); + assert!(s.doc().unwrap().by_script.is_some(), "restored as a document a script opened"); +} + +/// A crash while a restore moves a copy into the app's own area leaves no copy that a later +/// restore opens without its details: a script's change is kept. +#[test] +fn a_crash_while_a_copy_is_restored_keeps_a_scripts_change() { + let store = Arc::new(MemoryStore::default()); + let mut s = session_in(&store); + let source = "vc.run('shape.ellipse', {x: 80, y: 20, width: 20, height: 20});"; + s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap(); + s.execute("file.recovery.save", &json!({})).unwrap(); + drop(s); + let mut s = Session::new(); + s.recovery.set_store(Arc::new(DiesAfterDocument { inner: store.clone(), dead: Default::default() })); + let _ = s.execute("file.recovery.restore", &json!({})); + drop(s); + let mut s = relaunch(&store); + assert!(restored(s.execute("file.recovery.restore", &json!({})).unwrap()) >= 1); + for st in s.documents().iter().filter(|st| st.recovered) { + assert!(st.by_script.is_some(), "every restored copy keeps the script's change: {}", st.title()); + } +} + +/// A copy whose details entry is missing or can't be parsed restores as a document a script +/// opened, and so does the copy that restore writes, after a later crash; a valid details entry +/// without the script's mark restores as the person left it. +#[test] +fn a_copy_without_readable_details_restores_as_a_scripts_document() { + let cases: [Option<&[u8]>; 3] = [Some(b"{ not json"), None, Some(b"{}")]; + for details in cases { + let store = Arc::new(MemoryStore::default()); + let mut s = session_in(&store); + let r = s.execute("file.recovery.save", &json!({})).unwrap(); + let entry = format!("{}.json", r["saved"][0]["file"].as_str().unwrap()); + drop(s); + match details { + Some(bytes) => store.write(&entry, bytes).unwrap(), + None => store.remove(&entry).unwrap(), + } + let by_script = details != Some(b"{}".as_slice()); + for round in 1..=2 { + let mut s = relaunch(&store); + assert_eq!(restored(s.execute("file.recovery.restore", &json!({})).unwrap()), 1, "{details:?}, restore {round}"); + assert_eq!(s.doc().unwrap().by_script.is_some(), by_script, "{details:?}, restore {round}"); + } + } +} diff --git a/crates/engine/src/tests/script_dollar.rs b/crates/engine/src/tests/script_dollar.rs index 849d5b9080..cb588abe14 100644 --- a/crates/engine/src/tests/script_dollar.rs +++ b/crates/engine/src/tests/script_dollar.rs @@ -1,5 +1,5 @@ -//! The `$` object's members besides `$.write` and `$.writeln`, the global `localize` and -//! `toSource`, and what of them one run keeps to itself. +//! The `$` object's members besides `$.write` and `$.writeln`, the global `localize`, `toSource` +//! and `UnitValue`, and what of them one run keeps to itself. use std::time::Duration; @@ -63,7 +63,7 @@ fn each_member_has_its_value() { ("$.memCache", json!(0)), ("$.os", json!(os)), ("$.screens.length", json!(0)), - ("$.stack", json!("[global]@t.js:1\n")), + ("$.stack", json!("[t.js]\n[global]@t.js:1\n")), ("$.strict", json!(false)), ("$.version", json!(version)), ("typeof $.getenv + typeof $.setenv + typeof $.sleep", json!("functionfunctionfunction")), @@ -140,6 +140,15 @@ fn to_source_writes_plain_data() { assert!(thrown(&mut s, "toSource(vc)").starts_with("TypeError"), "a host object is not plain data"); } +#[test] +fn unit_values_convert_and_calculate_in_a_run() { + let mut s = Session::new(); + assert_eq!(value(&mut s, "UnitValue('1 in').as('pt')"), json!(72)); + assert_eq!(value(&mut s, "String(new UnitValue(1, 'm') + new UnitValue(10, 'cm'))"), json!("1.1 m")); + assert_eq!(value(&mut s, "[UnitValue(98, 'cm') < UnitValue(1, 'm'), UnitValue(98, 'cm') == 98]"), json!([true, true])); + assert!(thrown(&mut s, "UnitValue(1, 'in').as('furlong')").starts_with("Error")); +} + #[test] fn getenv_reads_only_its_names_and_setenv_changes_only_the_run() { let mut s = Session::new(); @@ -165,10 +174,31 @@ fn getenv_reads_only_its_names_and_setenv_changes_only_the_run() { fn error_line_and_stack_follow_the_running_code() { let mut s = Session::new(); let source = "try { null.x; } catch (e) {}\nfunction where() {\n return [$.line, $.stack, $.error instanceof TypeError];\n}\nvc.log(where());"; - assert_eq!(logged(&mut s, source)[0], json!([3, "[global]@t.js:5\nwhere@t.js:3\n", true])); + assert_eq!(logged(&mut s, source)[0], json!([3, "[t.js]\n[global]@t.js:5\nwhere@t.js:3\n", true])); assert_eq!(value(&mut s, "$.error"), json!(null), "each run starts without one"); } +/// `$.stack`'s first line is the run's name in square brackets, the name `script.run` reports, +/// in a function as at the top level. +#[test] +fn the_stack_starts_with_the_runs_name() { + let mut s = Session::new(); + let first = |s: &mut Session, params: Value| { + let r = s.execute("script.run", ¶ms).unwrap_or_else(|e| panic!("{params}: {e}")); + let line = r["log"][0].as_str().unwrap_or_default().to_string(); + (line, r["name"].clone()) + }; + let top = "vc.log($.stack.split('\\n')[0]);"; + let (line, name) = first(&mut s, json!({"source": top, "name": "Marks.jsx"})); + assert_eq!((line.as_str(), name), ("[Marks.jsx]", json!("Marks.jsx"))); + let inner = "function f() { return $.stack.split('\\n')[0]; }\nvc.log(f());"; + assert_eq!(first(&mut s, json!({"source": inner, "name": "Marks.jsx"})).0, "[Marks.jsx]"); + let (line, name) = first(&mut s, json!({"source": format!("#script \"Named\"\n{top}")})); + assert_eq!((line.as_str(), name), ("[Named]", json!("Named")), "a #script line names the run"); + let (line, name) = first(&mut s, json!({"source": top})); + assert_eq!(format!("[{}]", name.as_str().unwrap_or_default()), line, "a run given no name"); +} + #[test] fn sleep_waits_between_slices_until_its_time_has_passed() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_engines.rs b/crates/engine/src/tests/script_engines.rs index a25b0489ba..9723464bfb 100644 --- a/crates/engine/src/tests/script_engines.rs +++ b/crates/engine/src/tests/script_engines.rs @@ -298,19 +298,23 @@ fn the_line_and_the_stack_of_code_an_earlier_run_kept_are_at_that_runs_files() { }; let r = call(&mut s, "vc.log(fromMain());"); assert_eq!(r[0], 4, "{r}"); - assert_eq!(short_stack(&r[1]), "[global]@caller.js:3\nfromMain@def.jsx:5\nfromInclude@inc.jsxinc:4\n"); - assert_eq!(short_stack(&call(&mut s, "vc.log(fromText());")), "[global]@caller.js:3\nfromText@t.js:4\n"); + assert_eq!( + short_stack(&r[1]), + "[caller.js]\n[global]@caller.js:3\nfromMain@def.jsx:5\nfromInclude@inc.jsxinc:4\n", + "the first line names the run that is calling, not the one that defined the function" + ); + assert_eq!(short_stack(&call(&mut s, "vc.log(fromText());")), "[caller.js]\n[global]@caller.js:3\nfromText@t.js:4\n"); assert_eq!(call(&mut s, "vc.log(eval('\\n\\n$.line'));"), 3); - assert_eq!(call(&mut s, "vc.log(eval('\\n$.stack'));"), "[global]@caller.js:3\n[global]@[eval]:2\n"); + assert_eq!(call(&mut s, "vc.log(eval('\\n$.stack'));"), "[caller.js]\n[global]@caller.js:3\n[global]@[eval]:2\n"); let r = call(&mut s, "vc.log(new Function('\\nreturn $.stack;')());"); - assert_eq!(r, "[global]@caller.js:3\n[anonymous]@[eval]:4\n", "the line of the function source `Function` compiles"); + assert_eq!(r, "[caller.js]\n[global]@caller.js:3\n[anonymous]@[eval]:4\n", "the line of the function source `Function` compiles"); // A map larger than the budget is not kept. TEST_KEPT_MAP_BYTES.with(|b| b.set(Some(1))); let lost = run(&mut s, "#targetengine e\n\n\nfunction lost() {\n return [$.line, $.stack];\n}"); let r = lost.map(|_| call(&mut s, "vc.log(lost());")); TEST_KEPT_MAP_BYTES.with(|b| b.set(None)); let r = r.unwrap(); - assert_eq!(r, json!([0, "[global]@caller.js:3\nlost@[unknown]:0\n"])); + assert_eq!(r, json!([0, "[caller.js]\n[global]@caller.js:3\nlost@[unknown]:0\n"])); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/src/tests/script_include.rs b/crates/engine/src/tests/script_include.rs index cc6756c332..78b0065b46 100644 --- a/crates/engine/src/tests/script_include.rs +++ b/crates/engine/src/tests/script_include.rs @@ -521,12 +521,15 @@ fn script_included_error_has_local_file_and_line() { let _ = std::fs::remove_dir_all(base); } -/// `$.stack`'s text with each frame's file cut to its name: `function@name:line` a line. +/// `$.stack`'s text with each frame's file cut to its name. The first line is the run's name +/// (`[script name]`) and is kept as written; each line after it is `function@name:line`. pub(crate) fn short_stack(stack: &Value) -> String { let stack = stack.as_str().unwrap_or_else(|| panic!("a stack: {stack}")); stack .lines() - .map(|frame| match (frame.split_once('@'), frame.rsplit_once(':')) { + .enumerate() + .map(|(i, frame)| match (frame.split_once('@'), frame.rsplit_once(':')) { + _ if i == 0 => format!("{frame}\n"), (Some((name, _)), Some((place, line))) => { let file = place.split_once('@').map_or(place, |(_, f)| f).rsplit(['/', '\\']).next().unwrap_or_default(); format!("{name}@{file}:{line}\n") @@ -554,12 +557,12 @@ fn script_line_and_stack_are_at_the_line_of_each_file() { let log = run(&base, text).unwrap()["log"].clone(); assert_eq!(log[0], json!([5, 3, 4]), "{log}"); assert_eq!(log[1][0], 3, "{log}"); - assert_eq!(short_stack(&log[1][1]), "[global]@main.jsx:6\nlibWhere@lib.jsxinc:3\n"); - assert_eq!(short_stack(&log[2]), "[global]@main.jsx:7\ndeepStack@deep.jsxinc:5\n"); + assert_eq!(short_stack(&log[1][1]), "[main.jsx]\n[global]@main.jsx:6\nlibWhere@lib.jsxinc:3\n"); + assert_eq!(short_stack(&log[2]), "[main.jsx]\n[global]@main.jsx:7\ndeepStack@deep.jsxinc:5\n"); assert_eq!(log[3][0], 4, "{log}"); - assert_eq!(short_stack(&log[3][1]), "[global]@main.jsx:8\n[global]@ev.jsx:5\nevWhere@ev.jsx:3\nincWhere@inc.jsxinc:4\n"); + assert_eq!(short_stack(&log[3][1]), "[main.jsx]\n[global]@main.jsx:8\n[global]@ev.jsx:5\nevWhere@ev.jsx:3\nincWhere@inc.jsxinc:4\n"); // The file a frame names is the one `$.fileName` gives while that file runs. - let log = run(&base, "vc.log($.stack.slice(9, -3) === $.fileName);").unwrap()["log"].clone(); + let log = run(&base, "vc.log($.stack.split('\\n')[1].slice(9, -2) === $.fileName);").unwrap()["log"].clone(); assert_eq!(log, json!([true])); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 25ccb3bcfb..e5d854850d 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -125,6 +125,22 @@ fn file_names_are_uri_encoded_and_current_relative() { let _ = std::fs::remove_dir_all(base); } +/// `localizedName` of a file and a folder is the name they show, decoded, as `displayName` is, +/// not the encoded `name`. +#[test] +fn file_and_folder_give_their_localized_name() { + let base = folder("localized"); + let log = logged( + &base, + "var f = new File('caf%C3%A9 x.txt'), d = new Folder('n%C3%A9w');\n\ + f.localizedName = 'other';\n\ + vc.log([f.localizedName === f.displayName, f.localizedName === f.name, d.localizedName === d.displayName,\n\ + d.localizedName === d.name, f.localizedName, 'localizedName' in Folder.prototype]);", + ); + assert_eq!(log, json!([[true, false, true, false, "caf\u{e9} x.txt", true]])); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn script_file_without_scope_cannot_probe_home() { let base = folder("home"); @@ -637,7 +653,7 @@ fn a_grants_change_without_its_lock_changes_nothing() { } /// Reading and changing the grants file wait for a lock another handle holds only for a bounded -/// number of tries: then a read gives no grants and a change fails with the file unchanged. A lock +/// number of tries: then a listing and a change fail, with the file unchanged. A lock /// released while it waits is taken. #[test] fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() { @@ -652,7 +668,8 @@ fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() { let waits = std::rc::Rc::new(std::cell::Cell::new(0)); let counted = waits.clone(); WHILE_GRANTS_LOCKED.set(Some(Box::new(move || counted.set(counted.get() + 1)))); - assert_eq!(stored_grants(&data), Vec::::new(), "grants are not read without the lock"); + let listed = stored_grants(&data); + assert_eq!(listed.map_err(|e| e.kind()), Err(std::io::ErrorKind::TimedOut), "grants are not listed without the lock"); assert_eq!(waits.get(), LOCK_TRIES - 1); waits.set(0); let refused = revoke_grants(&data, None, None); @@ -1303,6 +1320,55 @@ fn script_file_grants_file_that_cannot_be_read_is_left_as_it_is() { } } +/// `script.grants` fails on a grants file that is there but cannot be read (another version, not +/// JSON, no list of grants, over the size limit, not a file, or on Unix a link to a missing file), +/// lists none when it is missing, and +/// lists the well-formed grants of one that holds a grant that is not. +#[test] +fn script_grants_fails_on_a_grants_file_that_cannot_be_read() { + let mut big = b"{\"version\": 1, \"grants\": []}".to_vec(); + big.resize((4 << 20) + 1, b' '); + let cases = [ + ("list-newer", br#"{"version": 2, "grants": []}"#.to_vec()), + ("list-broken", b"{ not json".to_vec()), + ("list-nolist", br#"{"version": 1, "grants": {}}"#.to_vec()), + ("list-big", big), + ]; + for (name, held) in cases { + let base = folder(name); + write(&base.join("settings/Script Grants.json"), &held); + let mut s = with_data(&base); + let e = s.execute("script.grants", &json!({})).unwrap_err().to_string(); + assert!(e.contains("the script file permissions could not be read"), "{name}: {e}"); + let _ = std::fs::remove_dir_all(base); + } + let base = folder("list-folder"); + std::fs::create_dir_all(base.join("settings/Script Grants.json")).unwrap(); + let mut s = with_data(&base); + assert!(s.execute("script.grants", &json!({})).is_err(), "a folder in the grants file's place"); + let _ = std::fs::remove_dir_all(base); + #[cfg(unix)] + { + let base = folder("list-dangling"); + std::fs::create_dir_all(base.join("settings")).unwrap(); + std::os::unix::fs::symlink(base.join("gone.json"), base.join("settings/Script Grants.json")).unwrap(); + let mut s = with_data(&base); + assert!(s.execute("script.grants", &json!({})).is_err(), "a link to a missing file in the grants file's place"); + let _ = std::fs::remove_dir_all(base); + } + let base = folder("list-missing"); + let mut s = with_data(&base); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([]), "a missing grants file lists none"); + let _ = std::fs::remove_dir_all(base); + let base = folder("list-mixed"); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false}); + let text = json!({"version": 1, "grants": [grant, {"script": "x"}]}).to_string(); + write(&base.join("settings/Script Grants.json"), text.as_bytes()); + let mut s = with_data(&base); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"].as_array().unwrap().len(), 1); + let _ = std::fs::remove_dir_all(base); +} + /// `copy` of a file over 8 MiB is refused, as opening one is. #[test] fn script_file_copy_is_held_to_the_file_limit() { diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index bf8154f9a7..3cb7dc96af 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -297,6 +297,63 @@ fn files_are_checked_before_they_are_read() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() { + let dir = fresh_folder("es2015"); + let write = |name: &str, text: &str| { + let p = dir.join(name); + std::fs::write(&p, text).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + write("lib.jsxinc", "const k = 2;\nvar twice = n => n * k;\n"); + write("more.jsx", "let m = `m${k}`;\nm;\n"); + let modern = "#include \"lib.jsxinc\"\nlet x = [1, ...[2]];\nvc.log(`${twice(x[1])}`);\nvc.log(eval('let e = 5; e'));\nvc.log(new Function('a = 6', 'return a')());\nvc.log($.evalFile(File($.fileName).parent + '/more.jsx'));\n"; + let r = s.execute("script.run", &path(&write("modern.js", modern))).unwrap(); + assert_eq!(r["log"], json!(["4", 5, 6, "m2"]), "{r}"); + let upper = s.execute("script.run", &path(&write("UPPER.JS", "let u = 1; vc.log(u);"))).unwrap(); + assert_eq!(upper["log"], json!([1]), "{upper}"); + for (name, text) in [("legacy.jsx", "let x = 1;"), ("arrow.jsx", "var f = () => 1;"), ("template.jsx", "vc.log(`t`);")] { + let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{name}: {e}"); + } + // Script text given without a file keeps the ExtendScript language. + assert!(run(&mut s, "const c = 1;").unwrap_err().to_string().contains("SyntaxError")); + // A named engine reads each run the way that run's script does. + s.execute("script.run", &path(&write("first.jsx", "#targetengine kept\nvar kept = 1;"))).unwrap(); + let modern = s.execute("script.run", &path(&write("second.js", "#targetengine kept\nlet k2 = kept + 1;\nvc.log(k2);"))).unwrap(); + assert_eq!(modern["log"], json!([2]), "{modern}"); + let legacy = s.execute("script.run", &path(&write("third.jsx", "#targetengine kept\nvc.log(k2);\nconst c = 1;"))); + assert!(legacy.unwrap_err().to_string().contains("SyntaxError")); + let legacy = s.execute("script.run", &path(&write("fourth.jsx", "#targetengine kept\nvc.log(k2 + kept);"))).unwrap(); + assert_eq!(legacy["log"], json!([3]), "{legacy}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_js_script_reads_optional_chains_and_coalescing_and_a_jsx_script_does_not() { + let dir = fresh_folder("es2020"); + let write = |name: &str, text: &str| { + let p = dir.join(name); + std::fs::write(&p, text).unwrap(); + p.to_string_lossy().into_owned() + }; + let mut s = two_docs(); + let path = |p: &str| json!({"path": p}); + let modern = "var o = { a: { f: function () { return this.n; }, n: 3 } }, none = null;\n\ + vc.log(none?.a.b ?? 'none');\nvc.log(o.a?.f());\nvc.log(0 ?? 1);\nvc.log(eval('none?.[0] ?? 2'));\n"; + let r = s.execute("script.run", &path(&write("modern.js", modern))).unwrap(); + assert_eq!(r["log"], json!(["none", 3, 0, 2]), "{r}"); + for (name, text) in [("chain.jsx", "var o; vc.log(o?.a);"), ("coalesce.jsx", "vc.log(null ?? 1);"), ("mixed.js", "vc.log(1 || 2 ?? 3);")] { + let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string(); + assert!(e.contains("SyntaxError"), "{name}: {e}"); + } + // Script text given without a file keeps the ExtendScript language. + assert!(run(&mut s, "vc.log(null ?? 1);").unwrap_err().to_string().contains("SyntaxError")); + let _ = std::fs::remove_dir_all(&dir); +} + /// A new empty folder for test `name`. fn fresh_folder(name: &str) -> std::path::PathBuf { let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id())); @@ -417,6 +474,178 @@ fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() { let _ = std::fs::remove_dir_all(&dir); } +/// The color at the middle of the PNG at `path`. +fn middle_color(path: &std::path::Path) -> [u8; 3] { + let img = craft_image_codecs::decode(&std::fs::read(path).unwrap()).unwrap(); + let (w, h) = img.dimensions(); + let rgba = img.to_rgba8(); + let i = ((h / 2 * w + w / 2) * 4) as usize; + [rgba[i], rgba[i + 1], rgba[i + 2]] +} + +/// A script's export of a document open when the run began draws the file its image links to, +/// also outside the script's places. A file the script names itself, a link it points at such a +/// file, writing to the linked file and the links of a document the script opens are refused all +/// the same. +#[test] +fn a_scripts_export_reads_the_files_the_documents_open_before_it_link_to() { + use crate::tests_links::{BLUE, RED, near, open, place, png, save, session, write}; + let dir = fresh_folder("gate-links"); + let (inside, art) = (dir.join("in"), dir.join("art")); + std::fs::create_dir_all(&inside).unwrap(); + let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); + let (pic, secret, poster, other) = + (p(art.join("photo.png")), p(art.join("secret.png")), p(art.join("poster.vectorcraft")), p(inside.join("other.vectorcraft"))); + write(&pic, &png(600, 300, RED)); + write(&secret, &png(600, 300, RED)); + let mut s = session(); + place(&mut s, &pic); + save(&mut s, &poster); + s.execute("file.close", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + place(&mut s, &secret); + save(&mut s, &other); + s.execute("file.close", &json!({})).unwrap(); + // The files change after the saves: each document holds only the red preview of its image. + write(&pic, &png(600, 300, BLUE)); + write(&secret, &png(600, 300, BLUE)); + open(&mut s, &poster); + let (first, second) = (inside.join("first.png"), inside.join("second.png")); + let call = |id: &str, params: String| { + format!( + "try {{ var r = vc.run('{id}', {params}); vc.log(r.warnings ? r.warnings.length : 0); }} \ + catch (e) {{ vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }}\n" + ) + }; + let export = |to: &std::path::Path| format!("{{path: {:?}, format: 'png', background: 'white'}}", p(to.to_path_buf())); + let source = [ + call("document.export", export(&first)), + call("file.place", format!("{{path: {secret:?}, at: [200, 150]}}")), + "vc.run('select.all', {});\n".to_string(), + call("links.relink", format!("{{path: {secret:?}}}")), + call("document.export", format!("{{path: {pic:?}, format: 'png'}}")), + call("document.open", format!("{{path: {other:?}}}")), + call("document.export", export(&second)), + ] + .concat(); + let r = run_allowed(&mut s, &inside, &source).unwrap(); + assert_eq!(r["log"], json!([0, "denied", "denied", "denied", 0, 1]), "{r}"); + assert!(near(middle_color(&first), BLUE), "the linked file, not its preview: {:?}", middle_color(&first)); + assert!(near(middle_color(&second), RED), "a document the script opened gets no linked file: {:?}", middle_color(&second)); + assert_eq!(std::fs::read(&pic).unwrap(), png(600, 300, BLUE), "the linked file is not written"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A script line that runs command `id` with `params` and logs `ok`, or `denied` when the gate +/// refuses a file. +fn tried(id: &str, params: &str) -> String { + format!( + "try {{ vc.run('{id}', {params}); vc.log('ok'); }} \ + catch (e) {{ vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }}\n" + ) +} + +/// A document a script opened from a file that only a link let it read is not written in that run +/// or a later one, and gives a later run no access to its file once no document the person left +/// links to it. +#[test] +fn a_document_a_script_opened_from_a_linked_file_stays_read_only_in_later_runs() { + use crate::tests_links::{RED, open, place, png, save, session, write}; + let art = fresh_folder("gate-linked-runs").join("art"); + std::fs::create_dir_all(&art).unwrap(); + let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); + let (pic, inner, poster) = (p(art.join("photo.png")), p(art.join("inner.vectorcraft")), p(art.join("poster.vectorcraft"))); + write(&pic, &png(60, 30, RED)); + let mut s = session(); + place(&mut s, &pic); + save(&mut s, &inner); + s.execute("file.close", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + place(&mut s, &inner); + save(&mut s, &poster); + s.execute("file.close", &json!({})).unwrap(); + open(&mut s, &poster); + let bytes = std::fs::read(&inner).unwrap(); + let opened = run(&mut s, &[tried("document.open", &format!("{{path: {inner:?}}}")), tried("document.save", "{}")].concat()).unwrap(); + assert_eq!(opened["log"], json!(["ok", "denied"]), "{opened}"); + assert_eq!(s.doc().unwrap().path.as_deref(), Some(inner.as_str())); + let mut log = vec![]; + let next = run(&mut s, &tried("document.save", "{}")).unwrap(); + log.push(next["log"][0].clone()); + // The person closes the document that links to it. + let at = s.documents().iter().position(|d| d.path.as_deref() == Some(poster.as_str())).unwrap(); + assert!(s.set_active(at)); + s.execute("file.close", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let later = run(&mut s, &tried("file.place", &format!("{{path: {inner:?}, at: [200, 150]}}"))).unwrap(); + log.push(later["log"][0].clone()); + assert_eq!(log, [json!("denied"), json!("denied")], "a save in the next run, then a read once nothing the person left links to it"); + assert_eq!(std::fs::read(&inner).unwrap(), bytes, "the linked file is as it was"); + let _ = std::fs::remove_dir_all(art.parent().unwrap()); +} + +/// A data set value a script gives a document, and a document a script opens, let no later run +/// read the files they name; once the person saves the document, the files its data sets name are +/// read again. +#[test] +fn what_a_script_adds_to_the_documents_lets_no_later_run_read_more() { + use crate::tests_links::{RED, place, png, session, write}; + let dir = fresh_folder("gate-linked-later"); + let (inside, art) = (dir.join("in"), dir.join("art")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&art).unwrap(); + let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); + let (secret, other, mine) = (p(art.join("secret.png")), p(inside.join("other.vectorcraft")), p(inside.join("mine.vectorcraft"))); + write(&secret, &png(60, 30, RED)); + let mut s = session(); + place(&mut s, &secret); + s.execute("document.save", &json!({"path": other})).unwrap(); + s.execute("file.close", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let read_secret = tried("file.place", &format!("{{path: {secret:?}, at: [200, 150]}}")); + let set = format!( + "vc.run('variable.define', {{name: 'Photo', kind: 'image'}});\nvc.run('dataset.new', {{name: 'X', values: {{Photo: {secret:?}}}}});\n" + ); + run(&mut s, &set).unwrap(); + let mut log = vec![]; + log.push(run(&mut s, &read_secret).unwrap()["log"][0].clone()); + let own = s.active_index().unwrap(); + let r = run_allowed(&mut s, &inside, &tried("document.open", &format!("{{path: {other:?}}}"))).unwrap(); + assert_eq!(r["log"], json!(["ok"]), "{r}"); + log.push(run(&mut s, &read_secret).unwrap()["log"][0].clone()); + assert_eq!(log, [json!("denied"), json!("denied")], "after a data set value, then after a document a script opened"); + assert!(s.set_active(own)); + s.execute("document.save", &json!({"path": mine})).unwrap(); + let saved = run(&mut s, &read_secret).unwrap(); + assert_eq!(saved["log"], json!(["ok"]), "saved by the person: {saved}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A save the person started before a script's command changed the document, and that finishes +/// after it, does not let a later run read the files that change names. +#[test] +fn a_save_started_before_a_scripts_change_lets_no_later_run_read_more() { + use crate::cmd::fileio::{SaveMode, save_job, save_plan}; + use crate::tests_links::{RED, png, session, write}; + let dir = fresh_folder("gate-linked-save"); + let p = |f: std::path::PathBuf| f.to_string_lossy().into_owned(); + let (secret, mine) = (p(dir.join("secret.png")), p(dir.join("mine.vectorcraft"))); + write(&secret, &png(60, 30, RED)); + let mut s = session(); + let uid = s.doc().unwrap().uid; + let plan = save_plan(&s, SaveMode::SaveAs, &json!({"path": mine})).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + let set = format!( + "vc.run('variable.define', {{name: 'Photo', kind: 'image'}});\nvc.run('dataset.new', {{name: 'X', values: {{Photo: {secret:?}}}}});\n" + ); + run(&mut s, &set).unwrap(); + job.write(|_, _| Ok(())).unwrap(); + job.complete(&mut s, uid); + let r = run(&mut s, &tried("file.place", &format!("{{path: {secret:?}, at: [200, 150]}}"))).unwrap(); + assert_eq!(r["log"], json!(["denied"]), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// A command a script runs does not save into the app's own libraries; the same command run /// outside a script does. #[test] diff --git a/crates/engine/src/tests/swatchlib.rs b/crates/engine/src/tests/swatchlib.rs index 5d94eecc69..f72beb71c2 100644 --- a/crates/engine/src/tests/swatchlib.rs +++ b/crates/engine/src/tests/swatchlib.rs @@ -1313,6 +1313,811 @@ fn a_color_a_pattern_brings_leaves_links_to_a_deleted_color_alone() { assert!(doc(&s).swatch("Ink 2").is_none(), "{r}"); } +/// A tint or gradient of a numbered library name ("Ink 2") that a library pattern's art brings +/// keeps that name when the document gives the art's color "Ink" another color, so adding the +/// library's "Ink 2" next finds it. +#[test] +fn a_numbered_tint_or_gradient_a_pattern_brings_keeps_the_librarys_name() { + let tint = json!({"name": "Ink 2", "swatch": "Ink", "tint": 50}); + let gradient = json!({"name": "Ink 2", "gradient": {"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#ffffff"}]}}); + for numbered in [tint, gradient] { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", numbered.clone()); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(doc(&s).swatch("Ink 2").is_some_and(|w| !w.global && !w.spot), "{numbered}: {first}"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!([]), &json!(["Ink 2"])), "{numbered}: {first} {r}"); + } +} + +/// A library pattern swatch that comes in under a numbered name skips the names the library gives +/// its other swatches: adding the library's "Dots 2" next adds it under its own name. +#[test] +fn a_library_pattern_swatchs_copy_skips_the_librarys_other_names() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Squares", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + s.edit("Dots", |d, _| { + let paint = vectorcraft_doc::pattern::pattern_paint("Squares"); + d.swatches.push(vectorcraft_color::Swatch { name: "Dots".into(), paint, global: false, spot: false }); + Ok(()) + }) + .unwrap(); + run(&mut s, "swatch.new", json!({"name": "Dots 2", "color": "#00ff00", "global": true})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Squares.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Dots", "color": "#ff0000"})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Dots"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Dots 2"]})); + assert_eq!(r["added"], json!(["Dots 2"]), "{first} {r}"); + assert!(is_global(&s, "Dots 2", "#00ff00"), "{first} {r}"); +} + +/// A library whose spot color "Ink" shares its name with a global color in a color group: a +/// pattern's art painted with both brings both. A library tint of the spot color, picked before +/// the pattern, links to the document's copy of the spot color the art takes, not to the global +/// color the art brings under a numbered name, whether that color has another paint or the same. +/// The library's own spot "Ink 2" is green, so the document's blue "Ink 2" is not that swatch. +#[test] +fn a_library_tint_is_not_linked_to_a_namesake_of_another_kind_a_pattern_brings() { + for global_color in ["#ff0000", "#0000ff"] { + a_library_tint_skips_a_namesake_the_pattern_brings(global_color); + } +} + +fn a_library_tint_skips_a_namesake_the_pattern_brings(global_color: &str) { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Ink half", "swatch": "Ink", "tint": 50})); + run(&mut s, "swatch.new", json!({"name": "Crimson", "color": global_color, "global": true})); + let blue = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 3, "height": 6}))["id"].clone(); + let red = run(&mut s, "shape.rectangle", json!({"x": 3, "y": 0, "width": 3, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [blue]})); + run(&mut s, "paint.setFill", json!({"swatch": "Crimson", "ids": [red]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [blue, red]})); + run(&mut s, "select.set", json!({"ids": [blue, red]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + // The global color becomes "Ink" in a color group, and the pattern's art links to it by that name. + s.edit("Rename", |d, _| { + let i = d.swatches.iter().position(|w| w.name == "Crimson").unwrap(); + let mut global = d.swatches.remove(i); + global.name = "Ink".into(); + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Reds".into(), swatches: vec![global] }); + let def = d.pattern_mut("Tiles").unwrap(); + for node in &mut def.art { + for it in &mut std::sync::Arc::make_mut(node).appearance.items { + it.paint_mut().map_links(&mut |_, link, _| { + let red = link.as_deref() == Some("Crimson"); + if red { + *link = Some("Ink".into()); + } + red + }); + } + } + Ok(()) + }) + .unwrap(); + let art_links: Vec> = doc(&s).pattern("Tiles").unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect(); + assert_eq!(art_links, [Some("Ink".to_string()), Some("Ink".to_string())]); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff"})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "spot": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink half", "Tiles"]})); + assert_eq!(tint_base(&s, "Ink half").as_deref(), Some("Ink 2"), "{global_color}: {r}"); + assert!(doc(&s).swatch("Ink 2").is_some_and(|w| w.spot), "{global_color}: {r}"); +} + +/// A color of a numbered library name ("Ink 2") that a pattern's art brings comes in under that +/// name when the document does not use it, not as the document's copy of it ("Ink 2 2"), so +/// adding the library's "Ink 2" next finds it. +#[test] +fn a_numbered_color_a_pattern_brings_keeps_its_name_beside_a_copy_of_it() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink 2 2", "color": "#00ff00", "global": true})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(is_global(&s, "Ink 2", "#00ff00"), "{first}"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert_eq!((&r["added"], &r["existing"]), (&json!([]), &json!(["Ink 2"])), "{first} {r}"); +} + +/// A pattern that a library pattern's art is painted with ("Inner"), brought under a numbered name +/// because the document has a swatch "Inner", skips the name "Inner 2" that the library gives a +/// color, as does the swatch that comes with it. +#[test] +fn a_nested_pattern_a_library_pattern_brings_skips_the_librarys_names() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Inner", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Inner", "ids": [tile]})); + run(&mut s, "select.set", json!({"ids": [tile]})); + run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.new", json!({"name": "Inner 2", "color": "#00ff00", "global": true})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Inner", "color": "#ff0000"})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Outer"]})); + assert!(doc(&s).pattern("Inner 2").is_none(), "{first}"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Inner 2"]})); + assert_eq!(r["added"], json!(["Inner 2"]), "{first} {r}"); + assert!(is_global(&s, "Inner 2", "#00ff00"), "{first} {r}"); +} + +/// A library pattern that was pasted into the document with its art linked to the document's +/// copy of a numbered library color ("Ink 2 2" for "Ink 2") is found when it is added from the +/// library, not added again. +#[test] +fn a_pasted_pattern_linked_to_a_copy_of_a_numbered_color_is_found() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink 2", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink 2 2", "color": "#00ff00", "global": true})); + run(&mut s, "edit.paste", json!({})); + assert!(doc(&s).swatch("Ink 2").is_none(), "the paste reused the copy"); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert_eq!(doc(&s).patterns.len(), 1, "{r}"); +} + +/// A library pattern swatch named after its pattern ("Tiles 2") that comes in with a new pattern +/// under a numbered name ("Tiles 2 2"), because the document has another pattern of that name +/// without a swatch, takes the library swatch's name. +#[test] +fn a_new_patterns_swatch_takes_the_library_swatchs_free_name() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [own]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Tiles 2"]})); + assert!(doc(&s).pattern("Tiles 2").is_some(), "the document keeps its pattern"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + assert_eq!(r["added"], json!(["Tiles 2"]), "{r}"); + let paint = doc(&s).swatch("Tiles 2").map(|w| w.paint.clone()); + assert!(matches!(&paint, Some(Paint::Pattern { pattern, .. }) if pattern != "Tiles 2"), "{r} {paint:?}"); + // Added again after its swatch is deleted, it reuses the pattern under the same swatch name. + run(&mut s, "swatch.delete", json!({"names": ["Tiles 2"]})); + let again = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + assert_eq!(again["added"], json!(["Tiles 2"]), "{r} {again}"); + assert_eq!(doc(&s).swatch("Tiles 2").map(|w| w.paint.clone()), paint, "{r} {again}"); +} + +/// A library pattern swatch "Tiles" named after its pattern, added to a document that has another +/// pattern "Tiles" without a swatch, is named after the pattern that comes in ("Tiles 2"), as +/// before numbered names were reserved: only a numbered name is kept for the library swatch. +#[test] +fn a_new_patterns_swatch_of_an_unnumbered_name_is_named_after_its_pattern() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [own]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let added = r["added"].as_array().and_then(|a| a.first()).and_then(|n| n.as_str()).unwrap_or_default().to_string(); + assert_ne!(added, "Tiles", "{r}"); + let paint = doc(&s).swatch(&added).map(|w| w.paint.clone()); + assert!(matches!(&paint, Some(Paint::Pattern { pattern, .. }) if *pattern == added), "{r} {paint:?}"); + assert!(doc(&s).swatch("Tiles").is_none(), "{r}"); +} + +/// A library whose process color "Ink 2" shares its name with a global color in a color group +/// that a pattern's art is painted with: the global color comes in numbered, so adding the +/// library's "Ink 2" next adds the process color under its own name. +#[test] +fn a_numbered_name_is_kept_for_the_library_swatch_it_names() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00"})); + run(&mut s, "swatch.new", json!({"name": "Crimson", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Crimson", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + group_as(&mut s, "Crimson", "Ink 2"); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert_eq!(r["added"], json!(["Ink 2"]), "{first} {r}"); + assert!(doc(&s).swatch("Ink 2").is_some_and(|w| !w.global && !w.spot), "{first} {r}"); +} + +/// A library pattern pasted with Add, whose color came in as "Ink 2" and was then deleted without +/// unlinking the art, is not reused through a new "Ink 2" when the library gives that name another +/// color: adding that color next adds it under its own name. This holds too when the document has +/// a pattern "Ink 2" without a swatch. +#[test] +fn a_pasted_pattern_is_not_reused_by_taking_a_librarys_name() { + for bare in [false, true] { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + if bare { + let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [own]})); + run(&mut s, "object.pattern.make", json!({"name": "Ink 2", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Ink 2"]})); + assert!(doc(&s).pattern("Ink 2").is_some(), "the document keeps its pattern"); + } + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "add"})); + assert!(is_global(&s, "Ink 2", "#0000ff"), "the paste brings the blue color as Ink 2 ({bare})"); + run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false})); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert_eq!(r["added"], json!(["Ink 2"]), "{bare} {first} {r}"); + assert!(is_global(&s, "Ink 2", "#00ff00"), "{bare} {first} {r}"); + } +} + +/// A library pattern painted with two global colors of one paint, "Ink" and "Ink 2", added beside +/// the document's red "Ink" brings them as "Ink 3" and "Ink 2". Adding the pattern again finds it, +/// in either order of the library's colors: "Ink" does not reuse the library's "Ink 2". +#[test] +fn a_color_a_pattern_brings_again_does_not_reuse_a_copy_the_library_names() { + for ink_first in [true, false] { + let mut s = session(); + let names = if ink_first { ["Ink", "Ink 2"] } else { ["Ink 2", "Ink"] }; + for n in names { + run(&mut s, "swatch.new", json!({"name": n, "color": "#0000ff", "global": true})); + } + let mut dots = vec![]; + for (i, n) in ["Ink", "Ink 2"].iter().enumerate() { + let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + dots.push(dot); + } + run(&mut s, "select.set", json!({"ids": dots})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(is_global(&s, "Ink 2", "#0000ff") && is_global(&s, "Ink 3", "#0000ff"), "{ink_first} {first}"); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert_eq!(doc(&s).patterns.len(), 1, "{ink_first} {first} {r}"); + } +} + +/// A library pattern painted with a blue global "Ink" and a green global "Ink 2", added to a +/// document with a red "Ink" and a blue global "Ink 2": the art's "Ink" is the document's "Ink 2", +/// since that is not the library's "Ink 2", and no third copy comes in. +#[test] +fn a_color_a_pattern_brings_reuses_a_copy_that_is_not_the_librarys_namesake() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00", "global": true})); + let mut dots = vec![]; + for (i, n) in ["Ink", "Ink 2"].iter().enumerate() { + let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + dots.push(dot); + } + run(&mut s, "select.set", json!({"ids": dots})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(doc(&s).swatch("Ink 3").is_none(), "{r}"); + assert!(is_global(&s, "Ink 2", "#0000ff") && is_global(&s, "Ink 2 2", "#00ff00"), "{r}"); +} + +/// A library pattern painted with a blue global "Ink", from a library that also has a blue global +/// "Ink 2" the art does not use, added beside the document's red "Ink" after the library's "Ink 2" +/// came in: the art's "Ink" does not reuse the library's "Ink 2" and comes in as "Ink 3". +#[test] +fn a_color_a_pattern_brings_does_not_reuse_another_library_colors_copy() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert!(is_global(&s, "Ink 2", "#0000ff"), "{first}"); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(is_global(&s, "Ink 3", "#0000ff"), "{first} {r}"); + let links: Vec> = doc(&s).pattern("Tiles").unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect(); + assert_eq!(links, vec![Some("Ink 3".to_string())], "{first} {r}"); +} + +/// A library pattern painted with a blue global "Ink", pasted beside the document's red "Ink" and +/// then left without its color "Ink 2" (deleted without unlinking), is not reused by bringing the +/// library's "Ink" back as "Ink 2" when the library has its own blue "Ink 2": the pattern links to +/// another copy. +#[test] +fn a_pasted_pattern_is_not_reused_by_giving_a_librarys_name_to_another_color() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Ink", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "add"})); + assert!(is_global(&s, "Ink 2", "#0000ff"), "the paste brings the blue color as Ink 2"); + run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false})); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let added = r["added"].as_array().and_then(|a| a.first()).and_then(|n| n.as_str()).unwrap_or_default().to_string(); + let pattern = match doc(&s).swatch(&added).map(|w| w.paint.clone()) { + Some(Paint::Pattern { pattern, .. }) => pattern, + p => panic!("{r} {p:?}"), + }; + let links: Vec> = doc(&s).pattern(&pattern).unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect(); + assert!(!links.contains(&Some("Ink 2".to_string())), "{r} {links:?}"); +} + +/// A library pattern painted with two alike gradients of its blue global "Ink", "Ramp 2" and then +/// "Ramp", added beside the document's red "Ink": the color comes in as "Ink 2", and both +/// gradients come in under their own names, linked to it, instead of "Ramp" taking "Ramp 2". +#[test] +fn alike_gradients_a_pattern_brings_keep_their_names_when_their_color_is_renamed() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + let ramp = json!({"stops": [{"offset": 0, "swatch": "Ink"}, {"offset": 1, "color": "#ffffff"}]}); + run(&mut s, "swatch.new", json!({"name": "Ramp 2", "gradient": ramp})); + run(&mut s, "swatch.new", json!({"name": "Ramp", "gradient": ramp})); + let mut dots = vec![]; + for (i, n) in ["Ramp 2", "Ramp"].iter().enumerate() { + let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + dots.push(dot); + } + run(&mut s, "select.set", json!({"ids": dots})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + assert!(is_global(&s, "Ink 2", "#0000ff"), "{r}"); + assert!(doc(&s).swatch("Ramp").is_some() && doc(&s).swatch("Ramp 2").is_some(), "{r}"); +} + +/// A library pattern painted with blue globals "Ink" and "Ink 2", pasted twice beside the +/// document's red "Ink" and blue "Ink 2" (with Add, both fills on "Ink 2"; with Merge, one on the +/// red "Ink"), is found again as the copy that keeps its blue, not the merged one. +#[test] +fn a_pattern_pasted_with_add_and_with_merge_is_found_as_the_copy_with_its_colors() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#0000ff", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + let mut dots = vec![]; + for (i, n) in ["Ink", "Ink 2"].iter().enumerate() { + let dot = run(&mut s, "shape.rectangle", json!({"x": i * 5, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": n, "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + dots.push(dot); + } + run(&mut s, "select.set", json!({"ids": dots})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 12, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": "#ff0000", "global": true})); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#0000ff", "global": true})); + run(&mut s, "edit.paste", json!({"swatchConflict": "add"})); + run(&mut s, "edit.paste", json!({"swatchConflict": "merge"})); + let links = |s: &Session, p: &str| -> Vec> { + doc(s).pattern(p).unwrap().art.iter().map(|n| tint_link(&n.appearance.fill_paint())).collect() + }; + let kept: Vec = doc(&s).patterns.iter().map(|p| p.name.clone()).filter(|p| !links(&s, p).contains(&Some("Ink".into()))).collect(); + assert_eq!((doc(&s).patterns.len(), kept.len()), (2, 1), "one pasted copy keeps the blue color"); + for w in doc(&s).swatches.clone().iter().filter(|w| matches!(w.paint, Paint::Pattern { .. })) { + run(&mut s, "swatch.delete", json!({"names": [w.name]})); + } + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let pattern = match doc(&s).swatch("Tiles").map(|w| w.paint.clone()) { + Some(Paint::Pattern { pattern, .. }) => pattern, + p => panic!("{r} {p:?}"), + }; + assert_eq!((doc(&s).patterns.len(), &pattern), (2, &kept[0]), "{r}"); +} + +/// A library whose color "Tiles 2" shares its name with a pattern swatch in a color group: adding +/// the group gives the pattern swatch another name, so adding the color next adds it under its own. +#[test] +fn a_grouped_pattern_swatch_leaves_a_numbered_name_to_the_librarys_color() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Dots", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.new", json!({"name": "Tiles 2", "color": "#00ff00", "global": true})); + s.edit("Group", |d, _| { + let i = d.swatches.iter().position(|w| w.name == "Dots").unwrap(); + let mut w = d.swatches.remove(i); + w.name = "Tiles 2".into(); + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] }); + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Dots.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Group"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + assert_eq!(r["added"], json!(["Tiles 2"]), "{first} {r}"); + assert!(is_global(&s, "Tiles 2", "#00ff00"), "{first} {r}"); +} + +/// As above, with the grouped swatch named after its pattern "Tiles 2", which the document holds +/// (pasted there) without a swatch: the reused pattern's swatch leaves the name to the color too. +#[test] +fn a_grouped_swatch_of_a_reused_pattern_leaves_a_numbered_name_to_the_librarys_color() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles 2", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "swatch.new", json!({"name": "Bright", "color": "#00ff00", "global": true})); + s.edit("Group", |d, _| { + let i = d.swatches.iter().position(|w| w.name == "Tiles 2").unwrap(); + let w = d.swatches.remove(i); + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] }); + d.swatches.iter_mut().find(|w| w.name == "Bright").unwrap().name = "Tiles 2".into(); + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "edit.paste", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Tiles 2"]})); + assert!(doc(&s).pattern("Tiles 2").is_some() && doc(&s).swatch("Tiles 2").is_none(), "the pasted pattern stays"); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Group"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + assert_eq!(r["added"], json!(["Tiles 2"]), "{first} {r}"); + assert!(is_global(&s, "Tiles 2", "#00ff00"), "{first} {r}"); +} + +/// A pattern "Inner 2" that a library pattern's art is painted with, whose library swatch "Inner 2" +/// places it with an offset, leaves the name to that swatch: adding the library's "Inner 2" next +/// adds it under its own name with its placement. Picked first, "Inner 2" comes in under its own +/// name too. +#[test] +fn a_nested_pattern_leaves_its_name_to_a_library_swatch_that_places_it_otherwise() { + for outer_first in [true, false] { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Inner 2", "ids": [tile]})); + run(&mut s, "select.set", json!({"ids": [tile]})); + run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + let offset = Paint::Pattern { pattern: "Inner 2".into(), xf: kurbo::Affine::translate((3.0, 0.0)) }; + let lib_paint = offset.clone(); + s.edit("Offset", move |d, _| { + d.swatches.iter_mut().find(|w| w.name == "Inner 2").unwrap().paint = lib_paint; + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let picks = if outer_first { ["Outer", "Inner 2"] } else { ["Inner 2", "Outer"] }; + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": [picks[0]]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": [picks[1]]})); + assert_eq!(doc(&s).swatch("Inner 2").map(|w| w.paint.clone()), Some(offset), "{outer_first} {first} {r}"); + assert_eq!(doc(&s).patterns.len(), 2, "{outer_first} {first} {r}"); + } +} + +/// A pattern "Inner 2" that a library pattern's art is painted with, brought under a numbered name +/// because the document has another pattern "Inner 2" without a swatch, comes with a swatch under +/// the library swatch's free name "Inner 2": adding the library's "Inner 2" next finds it. +#[test] +fn a_nested_patterns_swatch_takes_the_library_swatchs_free_name() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Inner 2", "ids": [tile]})); + run(&mut s, "select.set", json!({"ids": [tile]})); + run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let own = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 9, "height": 9}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": [own]})); + run(&mut s, "select.set", json!({"ids": [own]})); + run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 14, "height": 14})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Inner 2"]})); + assert!(doc(&s).pattern("Inner 2").is_some(), "the document keeps its pattern"); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Outer"]})); + let paint = doc(&s).swatch("Inner 2").map(|w| w.paint.clone()); + assert!( + matches!(&paint, Some(Paint::Pattern { pattern, .. }) if pattern != "Inner 2" && doc(&s).pattern(pattern).is_some()), + "{first} {paint:?}" + ); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Inner 2"]})); + assert_eq!(r["added"], json!([]), "{first} {r}"); + assert_eq!(doc(&s).swatch("Inner 2").map(|w| w.paint.clone()), paint, "{first} {r}"); + assert_eq!(doc(&s).patterns.len(), 3, "{first} {r}"); +} + +/// A library with a pattern swatch "Tiles 2" and, in a color group, a swatch of the same name that +/// places the same pattern with an offset: adding the group first leaves the name to the +/// ungrouped swatch, which comes in under it next. +#[test] +fn a_grouped_namesake_of_a_pattern_swatch_leaves_it_the_name() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles 2", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + s.edit("Group", |d, _| { + let offset = Paint::Pattern { pattern: "Tiles 2".into(), xf: kurbo::Affine::translate((3.0, 0.0)) }; + let w = vectorcraft_color::Swatch { name: "Tiles 2".into(), paint: offset, global: false, spot: false }; + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] }); + Ok(()) + }) + .unwrap(); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Group"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + let paint = doc(&s).swatch("Tiles 2").map(|w| w.paint.clone()); + assert!(matches!(&paint, Some(Paint::Pattern { xf, .. }) if *xf == kurbo::Affine::IDENTITY), "{first} {r} {paint:?}"); +} + +/// A pattern "Inner 2" that a library pattern's art is painted with, whose swatch the library +/// deleted before giving the name "Inner 2" to a color, comes in under another name, so adding +/// that color next adds it under its own name. +#[test] +fn a_nested_pattern_does_not_take_a_name_the_library_gives_a_color() { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 4, "height": 4}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Inner 2", "width": 6, "height": 6})); + run(&mut s, "object.pattern.done", json!({})); + let tile = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Inner 2", "ids": [tile]})); + run(&mut s, "select.set", json!({"ids": [tile]})); + run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 12, "height": 12})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.delete", json!({"names": ["Inner 2"]})); + assert!(doc(&s).pattern("Inner 2").is_some(), "the library keeps the pattern"); + run(&mut s, "swatch.new", json!({"name": "Inner 2", "color": "#00ff00", "global": true})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Outer.vectorcraft"}))["library"].clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Outer"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Inner 2"]})); + assert_eq!(r["added"], json!(["Inner 2"]), "{first} {r}"); + assert!(is_global(&s, "Inner 2", "#00ff00"), "{first} {r}"); +} + +/// A library pattern pasted into the document, whose global color "Ink 2" (in a color group) was +/// then deleted without unlinking the art, is not reused by bringing that color back as "Ink 2" +/// when the library also has a process color "Ink 2": adding that color next adds it under its +/// own name. +#[test] +fn a_pasted_pattern_is_not_reused_by_bringing_back_a_librarys_name() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink 2", "color": "#00ff00"})); + run(&mut s, "swatch.new", json!({"name": "Crimson", "color": "#0000ff", "global": true})); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Crimson", "ids": [dot]})); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": [dot]})); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + group_as(&mut s, "Crimson", "Ink 2"); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "edit.paste", json!({})); + assert!(is_global(&s, "Ink 2", "#0000ff"), "the paste brings the global color as Ink 2"); + run(&mut s, "swatch.delete", json!({"names": ["Ink 2"], "unlink": false})); + run(&mut s, "swatch.delete", json!({"names": ["Tiles"]})); + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Ink 2"]})); + assert_eq!(r["added"], json!(["Ink 2"]), "{first} {r}"); + assert!(doc(&s).swatch("Ink 2").is_some_and(|w| !w.global && !w.spot), "{first} {r}"); +} + +/// Move swatch `name` of `s`'s document into a new color group under the name `to`, and link the +/// art of every pattern linked to it to `to`. +fn group_as(s: &mut Session, name: &str, to: &str) { + s.edit("Group", |d, _| { + let i = d.swatches.iter().position(|w| w.name == name).unwrap(); + let mut w = d.swatches.remove(i); + w.name = to.into(); + d.swatch_groups.push(vectorcraft_color::SwatchGroup { name: "Group".into(), swatches: vec![w] }); + for def in &mut d.patterns { + for node in &mut def.art { + for it in &mut std::sync::Arc::make_mut(node).appearance.items { + it.paint_mut().map_links(&mut |_, link, _| { + let hit = link.as_deref() == Some(name); + if hit { + *link = Some(to.into()); + } + hit + }); + } + } + } + Ok(()) + }) + .unwrap(); +} + +/// The swatch paint `p` links to. +fn tint_link(p: &Paint) -> Option { + match p { + Paint::Solid { swatch, .. } => swatch.clone(), + _ => None, + } +} + +/// A library pattern "Tiles" added beside the document's own swatch "Tiles" does not take the name +/// "Tiles 2" that the library gives a color, neither for the pattern nor for its swatch; nor does +/// its swatch when the document holds the pattern as "Tiles 2" (pasted there) without a swatch. +#[test] +fn a_pattern_swatch_named_after_its_numbered_pattern_skips_the_librarys_names() { + for pasted in [false, true] { + let mut s = session(); + let dot = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 6, "height": 6}))["id"].clone(); + run(&mut s, "select.set", json!({"ids": [dot]})); + run(&mut s, "object.pattern.make", json!({"name": "Tiles", "width": 8, "height": 8})); + run(&mut s, "object.pattern.done", json!({})); + run(&mut s, "swatch.new", json!({"name": "Tiles 2", "color": "#00ff00", "global": true})); + let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string(); + let id = run(&mut s, "swatch.library.load", json!({"dataBase64": b64, "name": "Tiles.vectorcraft"}))["library"].clone(); + let r = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 40, "height": 40}))["id"].clone(); + run(&mut s, "paint.setFill", json!({"swatch": "Tiles", "ids": [r]})); + run(&mut s, "select.set", json!({"ids": [r]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + run(&mut s, "swatch.new", json!({"name": "Tiles", "color": "#ff0000"})); + if pasted { + run(&mut s, "edit.paste", json!({})); + assert!(doc(&s).pattern("Tiles 2").is_some(), "the paste numbers the pattern"); + let names: Vec = doc(&s) + .swatches_iter() + .filter(|w| matches!(&w.paint, Paint::Pattern { pattern, .. } if pattern == "Tiles 2")) + .map(|w| w.name.clone()) + .collect(); + run(&mut s, "swatch.delete", json!({"names": names})); + } + let first = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles"]})); + let r = run(&mut s, "swatch.library.add", json!({"library": id, "names": ["Tiles 2"]})); + assert_eq!(r["added"], json!(["Tiles 2"]), "{pasted}: {first} {r}"); + assert!(is_global(&s, "Tiles 2", "#00ff00"), "{pasted}: {first} {r}"); + } +} + /// A library tint added without its global color to a document that has no swatch of the color's /// name brings the color along under its own name. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 1fa5fa8ded..b94baa9233 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -10,6 +10,25 @@ use vectorcraft_tools::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind use crate::{EngineError, Prefs, Result, Session}; +/// What a hover's lend decision holds for ([`Session::hover_tool_at`]). +#[derive(Clone, Copy, PartialEq)] +pub(crate) struct HoverKey { + /// The active document's uid and revision, which moves with the selection. + doc: Option<(u64, u64)>, + tool: &'static str, + mods: Mods, + /// The selection tool and the part selection tool chosen last. + last_tools: (Option<&'static str>, Option<&'static str>), + ctrl_click_selects_behind: bool, + object_selection_by_path_only: bool, + type_selection_by_path_only: bool, + selection_tolerance: f64, + anchor_size: u32, + use_preview_bounds: bool, + type_glyph_bounds: bool, + show_handles_multiple_anchors: bool, +} + /// The tool whose radius is General › Corner Radius. const ROUNDED_RECTANGLE: &str = "roundedRectangle"; @@ -183,6 +202,9 @@ impl Session { if self.tool.id() == id { return Ok(()); } + // A double-click or triple-click after the switch is the new tool's, also when the switch + // comes back to the tool a Cmd press was lent from. + self.press_lent = None; // Sampling type keeps its highlighted characters as the target, and a whole story that // Select All selected. Capture before the Type tool deactivates (which commits typing and // clears its editing state). @@ -208,6 +230,9 @@ impl Session { } if vectorcraft_tools::catalog::is_selection_tool(id) { self.last_selection_tool = Some(self.tool.id()); + if id != "selection" { + self.last_part_selection_tool = Some(self.tool.id()); + } self.select_whole_instance(id); } Ok(()) @@ -251,8 +276,10 @@ impl Session { /// selection tool from other tools (Alt on the lent Direct Selection gesture stays copy/subtract). /// Cmd alone lends Direct Selection the Selection tool, whose bounding box transforms the /// object (#3901; ). + /// Group Selection lends the Selection tool, and the Selection tool lends Direct Selection or + /// Group Selection, whichever was chosen last (Direct Selection until one is). /// Perspective Selection keeps Cmd+Alt drags to copy objects on their perspective plane. - /// None for the other selection tools and the view tools. + /// None for the view tools. fn lent_tool(&self, id: &str, mods: &Mods) -> Option<&'static str> { use vectorcraft_tools::catalog::{edits_anchors, is_selection_tool}; if matches!(id, "hand" | "zoom" | "rotateView") { @@ -261,6 +288,12 @@ impl Session { if id == "directSelection" && mods.cmd { return Some(if mods.alt { "groupSelection" } else { "selection" }); } + if id == "groupSelection" && mods.cmd { + return Some("selection"); + } + if id == "selection" && mods.cmd { + return Some(self.last_part_selection_tool.unwrap_or("directSelection")); + } if id == "perspectiveSelection" && mods.cmd && mods.alt { return None; } @@ -280,15 +313,118 @@ impl Session { self.lent_tool(self.tool.id(), mods) } - /// A press with Cmd held (Ctrl elsewhere) and any other tool than a selection tool: the - /// selection tool [`Self::lent_tool`] takes the gesture, pressing without Cmd (a plain click, - /// not Select Behind). The tool lent to stays as it was, unaware, until the release. → the event - /// for the tool, and the warnings of a preview that keeping the typing applied. - fn lend_selection_tool(&mut self, ev: &PointerEvent) -> Result<(PointerEvent, Vec)> { - if ev.kind != PointerKind::Down || !ev.mods.cmd || self.lender.is_some() { + /// The tool the status bar and the help bar name with `mods` held: the selection tool Cmd + /// lends ([`Self::lent_tool_id`]) while the button is up, Space does not lend a view tool and + /// the active tool is not computing an edit, else the active tool. Over a selected object where + /// a Cmd press selects behind, as the cursor last found it, it names the active tool. + pub fn shown_tool_id(&self, mods: &Mods) -> &'static str { + match self.hovered_lent(mods) { + Some(id) if !mods.space && !self.tool_editing() && !self.pointer_held => id, + _ => self.tool.id(), + } + } + + /// The tool whose marks the canvas shows with `mods` held: the selection tool a Cmd press at + /// the pointer would borrow, as [`Self::hover_tool_at`] or [`Self::cursor`] last found it + /// (before either has, the one [`Self::lent_tool_id`] names), else the active tool. The canvas + /// asks this while the view moves, when it does not hit-test the art under the pointer. + pub fn hover_tool_id(&self, mods: &Mods) -> &'static str { + match self.hovered_lent(mods) { + Some(id) if mods.cmd && !mods.space && self.lender.is_none() && !self.tool_editing() && !self.pointer_held => id, + _ => self.tool.id(), + } + } + + /// The selection tool a Cmd press with `mods` would borrow at the pointer: the one + /// [`Self::hover_tool_at`] or [`Self::cursor`] last found, while the document, the selection, + /// the active tool and the keys are as they were then (none where the press selects behind), + /// else the one [`Self::lent_tool_id`] names. + fn hovered_lent(&self, mods: &Mods) -> Option<&'static str> { + match self.hover_lent { + Some((key, lent)) if key == self.hover_key(mods) => lent, + _ => self.lent_tool_id(mods), + } + } + + /// What a hover's lend decision holds for: the active document's state (its uid and revision, + /// which moves with the selection), the active tool, the keys, the selection tools chosen last + /// and the preferences a press's hit test reads. + fn hover_key(&self, mods: &Mods) -> HoverKey { + let p = &self.prefs; + HoverKey { + doc: self.active().map(|d| (d.uid, d.revision)), + tool: self.tool.id(), + mods: *mods, + last_tools: (self.last_selection_tool, self.last_part_selection_tool), + ctrl_click_selects_behind: p.ctrl_click_selects_behind, + object_selection_by_path_only: p.object_selection_by_path_only, + type_selection_by_path_only: p.type_selection_by_path_only, + selection_tolerance: p.selection_tolerance, + anchor_size: p.anchor_size, + use_preview_bounds: p.use_preview_bounds, + type_glyph_bounds: p.type_glyph_bounds, + show_handles_multiple_anchors: p.show_handles_multiple_anchors, + } + } + + /// The tool whose marks and widgets the canvas draws this frame with `mods` held and the + /// pointer at `p` (None off the canvas): the selection tool a Cmd press there would borrow + /// ([`Self::lent_tool_at`]; off the canvas, the one [`Self::lent_tool_id`] names), else the + /// active tool. [`Self::hover_tool_id`] then answers the same until the pointer or the keys move. + pub fn hover_tool_at(&mut self, p: Option, mods: &Mods, view: ViewInfo) -> &'static str { + let lends = mods.cmd && !mods.space && self.lender.is_none() && !self.tool_editing() && !self.pointer_held; + let lent = match p { + _ if !lends => None, + Some(p) => self.lent_tool_at(p, mods, view), + None => self.lent_tool_id(mods), + }; + let key = self.hover_key(mods); + self.hover_lent = lends.then_some((key, lent)); + lent.unwrap_or(self.tool.id()) + } + + /// The selection tool a press at `p` with `mods` borrows ([`Self::lent_tool`]): none when + /// the Selection tool keeps a Cmd press on a selected object to select the object behind it + /// (Selection & Anchor Display › Command Click to Select Objects Behind). + fn lent_tool_at(&mut self, p: Point, mods: &Mods, view: ViewInfo) -> Option<&'static str> { + let id = self.lent_tool(self.tool.id(), mods)?; + let behind = self.tool.id() == "selection" && self.with_tool_cx(view, |_, cx| vectorcraft_tools::select::selects_behind_at(cx, p)); + (!behind).then_some(id) + } + + /// Is the press `ev` lent a selection tool ([`Self::lend_selection_tool`])? The frontend asks + /// before the press, to tell a gesture of the tool in hand from one of a lent tool. + pub fn press_lends_tool(&mut self, ev: &PointerEvent, view: ViewInfo) -> bool { + ev.kind == PointerKind::Down && ev.mods.cmd && self.lender.is_none() && self.lent_tool_at(ev.pos, &ev.mods, view).is_some() + } + + /// A press with Cmd held (Ctrl elsewhere): the selection tool [`Self::lent_tool_at`] names + /// takes the gesture, pressing without Cmd (a plain click, not Select Behind). The tool lent to + /// stays as it was, unaware, until the release. With a selection tool active, the double-click + /// or triple-click that follows Cmd-clicks goes to the tool the clicks went to, with Cmd kept + /// (Cmd+Shift releases a guide), and that tool is given back after it. → the event for the tool, + /// and the warnings of a preview that keeping the typing applied. + fn lend_selection_tool(&mut self, ev: &PointerEvent, view: ViewInfo) -> Result<(PointerEvent, Vec)> { + let follow_up = + matches!(ev.kind, PointerKind::DoubleClick | PointerKind::TripleClick) && vectorcraft_tools::catalog::is_selection_tool(self.tool.id()); + if ev.kind == PointerKind::Down { + self.press_lent = None; + } + if (ev.kind != PointerKind::Down && !follow_up) || !ev.mods.cmd || self.lender.is_some() { return Ok((*ev, vec![])); } - let Some(id) = self.lent_tool(self.tool.id(), &ev.mods) else { return Ok((*ev, vec![])) }; + // A follow-up goes where the press before it went, whatever that press selected, while the + // document and the active tool are the ones that press found. + let at = (self.active().map(|d| d.uid), self.tool.id()); + let id = if follow_up { + self.press_lent.filter(|(doc, tool, _)| (*doc, *tool) == at).map(|(.., id)| id) + } else { + self.lent_tool_at(ev.pos, &ev.mods, view) + }; + let Some(id) = id else { return Ok((*ev, vec![])) }; + if !follow_up { + self.press_lent = Some((at.0, at.1, id)); + } // Typing in progress is kept as its own step first: the lent tool's drag previews from the // document its interaction started from, which would drop the typing (#1881). When it // can't be kept, the press is not lent. @@ -316,7 +452,8 @@ impl Session { } self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone())); self.lender = Some(std::mem::replace(&mut self.tool, lent)); - Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled)) + let cmd = follow_up && ev.mods.cmd; + Ok((PointerEvent { mods: Mods { cmd, ..ev.mods }, ..*ev }, settled)) } /// The lent selection tool's gesture is over: the tool it was lent to is back as it was (the @@ -341,6 +478,9 @@ impl Session { self.back_to_bucket = outer_bucket; self.keep_tool_settings(); self.tool = lender; + // Back with the Selection or Group Selection tool, a symbol part the lent Direct + // Selection picked gives way to its instance, as choosing the tool does. + self.select_whole_instance(self.tool.id()); if let Some(points) = mesh_points { self.tool.set_option("meshPoints", &points); } @@ -771,7 +911,7 @@ impl Session { } self.leave_draw_inside(ev, view)?; self.tell_tool_history_moved(); - let (ev, settled) = self.lend_selection_tool(ev)?; + let (ev, settled) = self.lend_selection_tool(ev, view)?; let ev = &ev; let lent = self.lender.is_some(); let mut acts = self.with_tool_cx(view, |t, cx| t.pointer(cx, ev)); @@ -795,7 +935,7 @@ impl Session { PointerKind::Up => self.press_point = None, _ => {} } - if ev.kind == PointerKind::Up { + if ev.kind == PointerKind::Up || (lent && matches!(ev.kind, PointerKind::DoubleClick | PointerKind::TripleClick)) { self.give_back_tool(view)?; } r @@ -1305,7 +1445,11 @@ impl Session { /// press would borrow ([`Self::lend_selection_tool`]). pub fn cursor(&mut self, p: Point, mods: Mods, view: ViewInfo) -> Cursor { // While an edit is computed, a Cmd press is held for the active tool, which shows it is busy. - let lent = if mods.cmd && self.lender.is_none() && !self.tool_editing() { self.lent_tool(self.tool.id(), &mods) } else { None }; + // Cmd pressed once a drag is under way lends nothing, so the tool keeps its pointer. + let lends = mods.cmd && self.lender.is_none() && !self.tool_editing() && !self.pointer_held; + let lent = if lends { self.lent_tool_at(p, &mods, view) } else { None }; + let key = self.hover_key(&mods); + self.hover_lent = lends.then_some((key, lent)); match lent { Some(id) => { let lent = self.make_tool(id); diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 1413bb17bb..6664828398 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -93,7 +93,7 @@ fn every_command_without_a_document() { } /// Regression: huge column counts used to panic with `capacity overflow`; in every layout and -/// order (#681), with huge and negative spacing too. +/// order (#681), with huge and negative spacing too, and with `indices` and `at`. #[test] fn artboard_rearrange_huge_columns() { for fx in Fixture::ALL { @@ -106,6 +106,11 @@ fn artboard_rearrange_huge_columns() { } } } + // Listed artboards, out of range, and the grid's top-left at the far ends of the plane. + for (indices, at) in [(json!([0]), json!([1e308, -1e308])), (json!([0, u64::MAX]), json!([0, 0])), (json!([]), json!([-1e308, 1e308]))] { + let p = json!({ "indices": indices, "at": at, "columns": u64::MAX, "spacing": 1e308 }); + assert_eq!(probe(fx, "artboard.rearrange", &p), None); + } } } diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 5a6815f298..1407d10378 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -466,6 +466,160 @@ fn turned_horizontal_dimensions_stay_horizontal() { assert_eq!(text(&s, id), "100.00 pt"); } +/// A dimension of a whole path measures the path's overall width, or its height when vertical, +/// between its outermost points, and follows the path when it turns. Turned 30°, a 100 × 60 +/// rectangle is 100 cos 30° + 60 sin 30° wide, more than either side; a turned ellipse is measured +/// at the outermost points of its curves, which are not anchors. +#[test] +fn a_dimension_of_a_whole_path_measures_its_overall_width_and_height() { + let value = |s: &Session, id: u64| text(s, id).trim_end_matches(" pt").parse::().unwrap(); + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":60}))["id"].as_u64().unwrap(); + let source = json!({"kind":"extent","node":rect}); + let id = run(&mut s, "dimension.create", json!({"source":source,"orientation":"horizontal","offset":-30}))["id"].as_u64().unwrap(); + assert_eq!(text(&s, id), "100.00 pt"); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "object.rotate", json!({"angle":30})); + let wide = 100.0 * 30f64.to_radians().cos() + 60.0 * 30f64.to_radians().sin(); + assert!((value(&s, id) - wide).abs() < 0.01, "{} against {wide}", text(&s, id)); + // The rectangle's box: left, top, right, bottom. + let bounds = |s: &Session| { + let anchors = s.doc().unwrap().doc.node(NodeId(rect)).unwrap().path_data().unwrap().subpaths[0].anchors.clone(); + let (xs, ys): (Vec, Vec) = anchors.iter().map(|a| (a.p.x, a.p.y)).unzip(); + let low = |v: &[f64]| v.iter().copied().fold(f64::INFINITY, f64::min); + let high = |v: &[f64]| v.iter().copied().fold(f64::NEG_INFINITY, f64::max); + (low(&xs), low(&ys), high(&xs), high(&ys)) + }; + // The line stays 30 pt above the turned rectangle's topmost corner, clear of the art. + let (left, top, right, _) = bounds(&s); + let line = recipe(&s, id).line_ends().0.y; + assert!((line - (top - 30.0)).abs() < 0.01, "line at y = {line}, top at {top}"); + run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"vertical"})); + let tall = 100.0 * 30f64.to_radians().sin() + 60.0 * 30f64.to_radians().cos(); + assert!((value(&s, id) - tall).abs() < 0.01, "{} against {tall}", text(&s, id)); + let d = recipe(&s, id); + let (top, bottom) = (d.a.y.min(d.b.y), d.a.y.max(d.b.y)); + assert!(((bottom - top) - tall).abs() < 0.01, "the points are the topmost and bottommost: {:?} {:?}", d.a, d.b); + // The line was 30 pt above the path; turned, it is 30 pt beside it. + let line = d.line_ends().0.x; + assert!((line - (left - 30.0)).abs() < 0.01 || (line - (right + 30.0)).abs() < 0.01, "line at x = {line}, path from {left} to {right}"); + run(&mut s, "edit.undo", json!({})); + assert!((value(&s, id) - wide).abs() < 0.01, "{}", text(&s, id)); + // A linear dimension only. + assert!(s.execute("dimension.create", &json!({"mode":"angular","source":source})).is_err()); + + let ellipse = run(&mut s, "shape.ellipse", json!({"x":300,"y":100,"width":100,"height":50}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":ellipse},"orientation":"horizontal"}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[ellipse]})); + run(&mut s, "object.rotate", json!({"angle":45})); + let anchors = s.doc().unwrap().doc.node(NodeId(ellipse)).unwrap().path_data().unwrap().subpaths[0].anchors.clone(); + let between_anchors = anchors.iter().map(|a| a.p.x).fold(f64::MIN, f64::max) - anchors.iter().map(|a| a.p.x).fold(f64::MAX, f64::min); + // 2 √(50² cos² 45° + 25² sin² 45°) + let across = 2.0 * (2500.0f64 * 0.5 + 625.0 * 0.5).sqrt(); + assert!(value(&s, id) > between_anchors + 1.0, "{} against the anchors' {between_anchors}", text(&s, id)); + assert!((value(&s, id) - across).abs() < 0.1, "{} against {across}", text(&s, id)); +} + +/// A dimension of a whole path measures the segments the path draws: an anchor that starts no +/// segment does not widen it. Its line stays clear of the whole path when only parts other than +/// its measured points move, also when it is aligned or is scaled together with the path, when the +/// path's direction is reversed or the path is reflected onto itself, and when it becomes aligned. +/// A reflection that moves the path puts the line on the reflected side. +#[test] +fn a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws() { + let mut s = session(); + let lone = run(&mut s, "path.create", json!({"d":"M100 300 L110 300 M200 400","closed":false}))["id"].as_u64().unwrap(); + assert_eq!(s.doc().unwrap().doc.node(NodeId(lone)).unwrap().path_data().unwrap().subpaths.len(), 2, "the lone anchor is kept"); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":lone},"orientation":"horizontal"}))["id"].as_u64().unwrap(); + assert_eq!(text(&s, id), "10.00 pt"); + + // A triangle whose top rises while its leftmost and rightmost points stay: the line stays + // 30 pt above the top. + let tri = run(&mut s, "path.create", json!({"d":"M100 200 L150 120 L200 200 Z","closed":true}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":tri},"orientation":"horizontal","offset":-110}))["id"] + .as_u64() + .unwrap(); + assert!((recipe(&s, id).line_ends().0.y - 90.0).abs() < 1e-6); + run(&mut s, "select.set", json!({"ids":[tri]})); + run(&mut s, "object.scale", json!({"sx":100,"sy":150,"origin":[150,200]})); + let line = recipe(&s, id).line_ends().0.y; + assert!((line - 50.0).abs() < 1e-6, "line at y = {line}"); + // The same for an aligned dimension, and for a dimension scaled together with its path. + for (x, orientation, with_dimension) in [(300.0, "aligned", false), (500.0, "horizontal", true)] { + let d = format!("M{x} 200 L{} 120 L{} 200 Z", x + 50.0, x + 100.0); + let tri = run(&mut s, "path.create", json!({"d":d,"closed":true}))["id"].as_u64().unwrap(); + let source = json!({"kind":"extent","node":tri}); + let id = run(&mut s, "dimension.create", json!({"source":source,"orientation":orientation,"offset":-110}))["id"].as_u64().unwrap(); + let ids = if with_dimension { vec![tri, id] } else { vec![tri] }; + run(&mut s, "select.set", json!({"ids":ids})); + run(&mut s, "object.scale", json!({"sx":100,"sy":150,"origin":[x + 50.0, 200]})); + let line = recipe(&s, id).line_ends().0.y; + assert!((line - 50.0).abs() < 1e-6, "{orientation}: line at y = {line}"); + } + // Reversing the path's direction draws the same outline: the line stays above it. + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":400,"width":100,"height":60}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":rect},"orientation":"horizontal","offset":-30}))["id"] + .as_u64() + .unwrap(); + run(&mut s, "path.reverse", json!({"ids":[rect]})); + let line = recipe(&s, id).line_ends().0.y; + assert!((line - 370.0).abs() < 1e-6, "line at y = {line}"); + // So does a reflection onto itself whose coordinates do not come out exactly, while a + // reflection that moves the art puts the line on the reflected side. + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":500.2,"width":100,"height":60}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":rect},"orientation":"horizontal","offset":-30}))["id"] + .as_u64() + .unwrap(); + run(&mut s, "select.set", json!({"ids":[rect]})); + run(&mut s, "object.reflect", json!({"axis":"horizontal","origin":[0,530.2]})); + let line = recipe(&s, id).line_ends().0.y; + assert!((line - 470.2).abs() < 1e-6, "line at y = {line}"); + let tri = run(&mut s, "path.create", json!({"d":"M100 700 L150 620 L200 700 Z","closed":true}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":tri},"orientation":"horizontal","offset":-110}))["id"] + .as_u64() + .unwrap(); + run(&mut s, "select.set", json!({"ids":[tri]})); + run(&mut s, "object.reflect", json!({"axis":"horizontal","origin":[0,700]})); + let line = recipe(&s, id).line_ends().0.y; + assert!((line - 810.0).abs() < 1e-6, "line at y = {line}"); + + // Made aligned, the line runs from the leftmost to the rightmost point, with every corner of + // the rectangle on one side of it and 40 pt from the nearest, as it was 40 pt above the top. + let rect = run(&mut s, "shape.rectangle", json!({"x":300,"y":100,"width":100,"height":60}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":rect},"orientation":"horizontal","offset":-40}))["id"] + .as_u64() + .unwrap(); + run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"aligned"})); + let (a, b) = recipe(&s, id).line_ends(); + let side = |x: f64, y: f64| (b - a).cross(vectorcraft_geom::Point::new(x, y) - a) / (b - a).hypot(); + let sides = [side(300.0, 100.0), side(400.0, 100.0), side(400.0, 160.0), side(300.0, 160.0)]; + assert!(sides.iter().all(|v| *v > 1e-6) || sides.iter().all(|v| *v < -1e-6), "{a:?} to {b:?}: {sides:?}"); + let nearest = sides.iter().map(|v| v.abs()).fold(f64::INFINITY, f64::min); + assert!((nearest - 40.0).abs() < 1e-6, "nearest corner {nearest} pt from the line"); + + // A line across the path, 30 pt below the top, made vertical: it goes 30 pt past the path's + // side rather than onto it. + let rect = run(&mut s, "shape.rectangle", json!({"x":600,"y":100,"width":100,"height":60}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":rect},"orientation":"horizontal","offset":30}))["id"] + .as_u64() + .unwrap(); + run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"vertical"})); + let line = recipe(&s, id).line_ends().0.x; + assert!((line - 570.0).abs() < 1e-6 || (line - 730.0).abs() < 1e-6, "line at x = {line}, path from 600 to 700"); + // When that would put the line farther from its first point than an offset may be, the + // change is refused rather than leaving the line across the path. + let far = run(&mut s, "path.create", json!({"d":"M0 0 L950000 -100 L950000 200000 Z","closed":true}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":far},"orientation":"horizontal","offset":100000}))["id"] + .as_u64() + .unwrap(); + assert!(s.execute("dimension.update", &json!({"ids":[id],"orientation":"vertical"})).is_err()); + assert_eq!(recipe(&s, id).orientation, vectorcraft_doc::dimension::Orientation::Horizontal); + // An offset given with the orientation places the line instead. + run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"vertical","offset":-30})); + let line = recipe(&s, id).line_ends().0.x; + assert!((line - 950030.0).abs() < 1e-6, "line at x = {line}"); +} + /// The line of a linked horizontal dimension keeps its gap from the outermost point on its side /// when the art turns, so it stays clear of the art: after a half turn the line is still 50 pt /// above the upper point, which is now the other anchor. @@ -1091,6 +1245,48 @@ fn free_points_survive_a_native_file() { assert!(near(d.a, before.a + v) && near(d.b, before.b + v), "{before:?} → {d:?}"); } +/// Saved and opened again, a dimension of a whole path still measures the path: turned, the path +/// is wider than before, and so is the dimension. +#[test] +fn a_dimension_of_a_whole_path_survives_a_native_file() { + let value = |s: &Session, id: u64| text(s, id).trim_end_matches(" pt").parse::().unwrap(); + let mut s = session(); + let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":60}))["id"].as_u64().unwrap(); + let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":rect},"orientation":"horizontal","offset":-30}))["id"] + .as_u64() + .unwrap(); + let before = recipe(&s, id); + let doc = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let mut reopened = Session::new(); + reopened.add_document(doc, None); + assert_eq!(recipe(&reopened, id).source, before.source); + run(&mut reopened, "select.set", json!({"ids":[rect]})); + run(&mut reopened, "object.rotate", json!({"angle":30})); + let wide = 100.0 * 30f64.to_radians().cos() + 60.0 * 30f64.to_radians().sin(); + assert!((value(&reopened, id) - wide).abs() < 0.01, "{} against {wide}", text(&reopened, id)); + + // A file whose dimension names a node that is not there: the next edit unlinks it. + let mut v: Value = serde_json::from_slice(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + fn dangle(v: &mut Value) { + match v { + Value::Object(m) => { + if m.get("kind") == Some(&json!("extent")) { + m.insert("node".into(), json!(99999)); + } + m.values_mut().for_each(dangle); + } + Value::Array(a) => a.iter_mut().for_each(dangle), + _ => {} + } + } + dangle(&mut v); + let mut dangling = Session::new(); + dangling.add_document(vectorcraft_format::load(&serde_json::to_vec(&v).unwrap()).unwrap(), None); + assert!(recipe(&dangling, id).source.is_some()); + run(&mut dangling, "shape.rectangle", json!({"x":300,"y":300,"width":10,"height":10})); + assert!(recipe(&dangling, id).source.is_none(), "no longer linked"); +} + /// A linked dimension opened from a file with options it cannot be drawn with keeps its art, as a /// plain group, when the art it measures is deleted. #[test] diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 660433b800..60239864d7 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -43,8 +43,10 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// Reading a file or a folder, a file dialog and a message to the person do not change anything /// outside it. const INSIDE: &[(&str, &str)] = &[ - ("", "$ File Folder alert confirm localize prompt toSource"), + ("", "$ File Folder UnitValue alert confirm localize prompt toSource"), ("Object.prototype.", "toSource"), + ("UnitValue.", "baseUnit baseUnit= length prototype"), + ("UnitValue.prototype.", "as baseUnit baseUnit= constructor convert toString type type= value value="), ("localize.", "length"), ("toSource.", "length"), ( @@ -57,7 +59,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "File.prototype.", "absoluteURI alias changePath close constructor created creator displayName encoding encoding= eof error error= \ - exists fsName fullName getRelativeURI hidden length lineFeed lineFeed= modified name openDlg parent path read \ + exists fsName fullName getRelativeURI hidden length lineFeed lineFeed= localizedName modified name openDlg parent path read \ readch readln readonly relativeURI resolve saveDlg seek tell toString type", ), ( @@ -68,7 +70,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "Folder.prototype.", "absoluteURI alias changePath constructor created displayName error error= exists fsName fullName getFiles \ - getRelativeURI modified name parent path relativeURI resolve selectDlg toString", + getRelativeURI localizedName modified name parent path relativeURI resolve selectDlg toString", ), ]; diff --git a/crates/engine/tests/plugin_fuzz.rs b/crates/engine/tests/plugin_fuzz.rs index 519efdaf43..33bc8bc299 100644 --- a/crates/engine/tests/plugin_fuzz.rs +++ b/crates/engine/tests/plugin_fuzz.rs @@ -1,6 +1,6 @@ -//! Untrusted plug-ins never crash the app: mutated and garbage modules handed to `plugin.install`, -//! and plug-ins returning hostile output (random JSON in the object model's shape: huge or -//! malformed coordinates, unknown ids, broken paints and gradients, junk of every type) as object +//! Untrusted plug-ins never crash the app: mutated and garbage modules, and modules whose +//! `vc_manifest` custom section holds garbage, handed to `plugin.install`, and plug-ins returning +//! hostile output (random JSON in the object model's shape: huge or malformed coordinates, unknown ids, broken paints and gradients, junk of every type) as object //! filters (`plugin.run`) or live effects (`effect.apply`), and plug-ins running bulk memory //! instructions (`memory.fill`, `memory.copy`, `memory.init`, `data.drop`) on ranges in, at and past //! the ends of memory and the data segment, under small and default budgets. Each run must end as @@ -620,7 +620,11 @@ proptest! { } let mut s = rich_session(); s.execute("select.all", &json!({})).unwrap(); - for module in [bytes, [b"\0asm\x01\0\0\0".as_slice(), &garbage].concat(), garbage.clone()] { + // A module whose `vc_manifest` custom section holds the garbage. + let section = tpl::custom_section(vectorcraft_plugins::manifest::MANIFEST_SECTION, &garbage); + let sectioned = tpl::with_field(&tpl::module(&tpl::manifest("fuzz.section", "filter", "{}"), tpl::ECHO, "", 1), §ion).unwrap(); + let sectioned = wat::parse_str(sectioned).unwrap(); + for module in [bytes, [b"\0asm\x01\0\0\0".as_slice(), &garbage].concat(), garbage.clone(), sectioned] { let r = catch_quiet(|| { if let Ok(info) = install(&mut s, &module) { let _ = s.execute("plugin.run", &json!({"id": info["id"]})); @@ -707,9 +711,10 @@ proptest! { } /// Manifests with hostile `commands` (junk of every type, bad and repeated ids, labels with - /// control and bidirectional override characters, a `menu` naming another menu, junk - /// parameters) parse to an error or to commands whose menu labels show no hidden character and - /// that sit under Plug-ins alone; installing one and running each of its commands ends as an + /// control and bidirectional override characters, a `menu` of any shape naming any menu, junk + /// parameters) at API level 1 or 2 parse to an error or to commands whose menu labels show no + /// hidden character and that sit under Plug-ins, or at level 2 in one of the menus a manifest + /// may name, with the plug-in's name; installing one and running each of its commands ends as an /// error or an edit, never a panic, and the document then renders and exports. #[test] fn hostile_manifest_commands_never_crash( @@ -723,7 +728,17 @@ proptest! { 1 => "[a-z\u{0007}\n]{1,8}".prop_map(Value::from), 1 => arb_junk(), ], - prop_oneof![Just(Value::Null), Just(json!("File")), arb_junk()], + prop_oneof![ + Just(Value::Null), + Just(json!("File")), + Just(json!({"path": ["Select"], "after": "Inverse"})), + Just(json!({"path": ["Object", "Path"]})), + Just(json!({"path": ["File"]})), + Just(json!({"path": ["Select"], "after": "\u{202E}Inverse"})), + arb_junk().prop_map(|j| json!({"path": j})), + arb_junk().prop_map(|j| json!({"path": ["Select"], "after": j})), + arb_junk(), + ], prop_oneof![Just(Value::Null), Just(json!({"by": {"type": "number", "min": 0, "max": 10, "default": 2}})), arb_junk()], ) .prop_map(|(id, label, menu, params)| { @@ -742,8 +757,9 @@ proptest! { ), junk in prop::option::weighted(0.1, arb_junk()), given in prop_oneof![Just(json!({})), Just(json!({"by": 3})), arb_junk()], + api in 1u32..=2, ) { - let mut m = json!({"id": "fuzz.commands", "name": "Fuzz \u{202E}Commands", "kind": kind}); + let mut m = json!({"id": "fuzz.commands", "name": "Fuzz \u{202E}Commands", "kind": kind, "api": api}); if matches!(kind, "exporter" | "importer") { m["extensions"] = json!(["fz"]); } @@ -756,6 +772,12 @@ proptest! { let shown = c.shown_label(); prop_assert!(!shown.chars().any(|ch| ch.is_control() || matches!(ch, '\u{202E}' | '\u{2066}' | '\u{200F}')), "{}", shown); prop_assert!(shown.chars().count() <= vectorcraft_plugins::permissions::MAX_SHOWN_NAME); + let placed = c.menu_label(&man.name); + prop_assert!(!placed.chars().any(|ch| ch.is_control() || matches!(ch, '\u{202E}' | '\u{2066}' | '\u{200F}')), "{}", placed); + if let Some(place) = &c.place { + prop_assert!(api >= 2 && vectorcraft_plugins::manifest::MENU_PLACES.contains(&place.path), "{:?}", place); + prop_assert!(placed.ends_with(')') && placed.len() > shown.len(), "a placed item names its plug-in: {}", placed); + } } } let mut s = rich_session(); @@ -774,7 +796,9 @@ proptest! { let ran = r.map_err(|msg| TestCaseError::fail(format!("panicked running {text}: {msg}")))?; prop_assert!(ran.is_empty() || parsed.is_ok(), "a manifest that doesn't parse installed: {}", text); for (id, menu) in &ran { - prop_assert!(menu.len() == 3 && menu[1] == "Plug-ins" && matches!(menu[0], "Object" | "Effect"), "{id}: {menu:?}"); + let submenu = menu.len() == 3 && menu[1] == "Plug-ins" && matches!(menu[0], "Object" | "Effect"); + let place = api >= 2 && vectorcraft_plugins::manifest::MENU_PLACES.contains(&menu.as_slice()); + prop_assert!(submenu || place, "{id}: {menu:?}"); } renders(&s, "after hostile commands")?; vectorcraft_plugins::registry::remove("fuzz.commands"); diff --git a/crates/eps/src/import/ai/read/art.rs b/crates/eps/src/import/ai/read/art.rs index 3887da7f33..030c70aa51 100644 --- a/crates/eps/src/import/ai/read/art.rs +++ b/crates/eps/src/import/ai/read/art.rs @@ -821,7 +821,8 @@ impl<'a> Reader<'a> { } /// Add an image object with the state's transparency, `mask` as its opacity mask and - /// `colorize` as the color that colorizes it. + /// `colorize` as the color that colorizes it, which overprints while the fill overprint (`O`) + /// in force is on. fn add_image_colorized(&mut self, im: ImageObject, mask: Option, colorize: Option, hidden: bool) -> Result<(), String> { let gs = self.gs.clone(); let mut node = self.new_node(NodeKind::Image(Box::new(im)), &gs); @@ -829,6 +830,7 @@ impl<'a> Reader<'a> { node.blend = gs.blend; node.knockout_shape = gs.knockout_shape; node.extras_mut().mask = mask.map(Box::new); + node.extras_mut().colorize_overprint = colorize.is_some() && gs.overprint_fill; node.extras_mut().colorize = colorize.map(Box::new); self.add(node, hidden)?; self.image_tail = self.after_object; diff --git a/crates/eps/src/legacy_ai/prolog.rs b/crates/eps/src/legacy_ai/prolog.rs index 38058e6abd..10c1f65ec1 100644 --- a/crates/eps/src/legacy_ai/prolog.rs +++ b/crates/eps/src/legacy_ai/prolog.rs @@ -96,10 +96,10 @@ VCLegacy begin /_l 256 string def /_s 128 string def /_row {{currentfile _l readline not {exit} if dup length 1 gt {exit} if pop} loop dup length 1 gt {dup length 1 sub 1 exch getinterval /ASCIIHexDecode filter _s readstring pop} {pop ()} ifelse} bd -% An image mask (ImageMask 1) paints its 0 bits in the fill color. +% An image mask (ImageMask 1) paints its 0 bits in the fill color, with the fill overprint. /XI {1 eq /_im exch def pop pop pop /_ic exch def /_ib exch def /_ih exch def /_iw exch def pop pop pop pop [1 0 0 -1 0 0] exch matrix concatmatrix - _on {gsave concat _im {_fc _iw _ih false [1 0 0 1 0 0] /_row load imagemask} + _on {gsave concat _im {_fc _fo setoverprint _iw _ih false [1 0 0 1 0 0] /_row load imagemask} {_iw _ih _ib [1 0 0 1 0 0] /_row load false _ic 1 eq {1} {_ic} ifelse colorimage} ifelse grestore} {pop} ifelse} bd % Type (15) is set by the app that reads the file: its operators take their operands and mark % nothing; encodings (3.3) are skipped. diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index 2f5a528340..e43f2a1227 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -1039,7 +1039,8 @@ fn colorized_images_keep_their_color() { // Each row is a byte: the black pixels are 0 bits. assert_eq!(data, &["%6996"], "{text}"); let at = text.find("%AI5_File:\n").unwrap(); - assert!(text[..at].ends_with("0 0.5 1 0 k\n"), "{text}"); + // Its color, and its fill overprint off. + assert!(text[..at].ends_with("0 0.5 1 0 k\n0 O\n"), "{text}"); assert!(out.warnings.is_empty(), "{:?}", out.warnings); let read = crate::import(&out.bytes).unwrap().document; let mut found = vec![]; @@ -1066,6 +1067,45 @@ fn colorized_images_keep_their_color() { assert_eq!(out.warnings, [IMAGE_ALPHA]); } +/// A colorized image mask takes the fill overprint in force: its own `O`, or without one the +/// last `O` before it, as it takes the fill color. +#[test] +fn a_colorized_image_mask_takes_the_fill_overprint_in_force() { + let opened = |square_overprints: bool, image_overprints: bool, drop_own: bool| { + let mut doc = Document::new(200.0, 100.0); + doc.layers.clear(); + let layer = doc.add_layer(Some("Art")); + let mut square = shape(&mut doc, shapes::rectangle(Rect::new(5.0, 5.0, 45.0, 30.0)), red(), Paint::None); + if let Some(f) = square.appearance.fill_mut() { + f.overprint = square_overprints; + } + doc.insert(Some(layer), usize::MAX, square).unwrap(); + let paint = Paint::solid(Color::cmyk(0.0, 0.5, 1.0, 0.0)); + let mask: Vec = "1001011001101001".bytes().map(|b| if b == b'1' { 0 } else { 255 }).collect(); + let mut bitmap = colorized_image(&mut doc, (8, 2), mask, &paint, (10.0, 10.0)); + bitmap.extras_mut().colorize_overprint = image_overprints; + doc.insert(Some(layer), usize::MAX, bitmap).unwrap(); + let mut text = String::from_utf8(write(&doc).bytes).unwrap(); + if drop_own { + let own = format!("0 0.5 1 0 k\n{} O\n", u8::from(image_overprints)); + assert!(text.contains(&own), "{text}"); + text = text.replace(&own, "0 0.5 1 0 k\n"); + } + let read = crate::import(text.as_bytes()).unwrap().document; + let mut found = vec![]; + read.walk(|n| { + if matches!(n.kind, NodeKind::Image(_)) { + found.push(n.colorize_overprints()); + } + }); + found + }; + assert_eq!(opened(false, true, false), [true]); + assert_eq!(opened(true, false, false), [false]); + assert_eq!(opened(true, false, true), [true], "the square's overprint stays in force"); + assert_eq!(opened(false, true, true), [false], "and so does the square's knockout"); +} + /// The pieces of a colorized warped image work out the image's coverage once, and an image with /// other data works out its own: a black and white image's pieces are written as image masks /// in its color, and a gray image's pieces with its color in their pixels. diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index 2fa0fcb6c2..dfe159cb59 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -362,7 +362,7 @@ impl<'a> Writer<'a> { } None => im.xf, }; - self.image(blob, im.width, im.height, xf, colorize); + self.image(blob, im.width, im.height, xf, colorize.map(|p| (p, n.colorize_overprints()))); } NodeKind::SymbolInstance { symbol, xf } => { self.warn(LIVE); @@ -1129,13 +1129,14 @@ impl<'a> Writer<'a> { /// `%AI5_EndRaster`, then `F`. §8.4's examples have no `F`; without it, an app reading the file /// can leave out an image in a clipping group and the art after it. No path is open there, so /// the `F` paints nothing. `blob` holds the pixels, placed as a grid of `width` × `height` - /// by `xf`, and `colorize` is the solid color the image is colorized with. A colorized image - /// whose pixels are all black or white is written as an image mask (ImageMask 1, §8.1): its - /// color as the fill, then 1-bit samples, a 0 bit for each black pixel, which takes the color, - /// and a 1 bit for each white pixel, which is clear. Another colorized image is written with + /// by `xf`, and `colorize` is the solid color the image is colorized with and whether it + /// overprints. A colorized image whose pixels are all black or white is written as an image + /// mask (ImageMask 1, §8.1): its color as the fill with its fill overprint, then 1-bit + /// samples, a 0 bit for each black pixel, which takes the color, and a 1 bit for each white + /// pixel, which is clear. Another colorized image is written with /// its color in its pixels. In a clipping group, an image whose pixels were written whole /// already is written as the part of them the group shows ([`ai_ops::image_window`]). - fn image(&mut self, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine, colorize: Option<&Paint>) { + fn image(&mut self, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine, colorize: Option<(&Paint, bool)>) { let flip = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 0.0]); let m = self.to_art * xf * flip; if !invertible(m) { @@ -1157,12 +1158,12 @@ impl<'a> Writer<'a> { // The object places the image's own pixel grid (its width × height) wherever the file's is. let fit = Affine::scale_non_uniform(f64::from(width.max(1)) / f64::from(w), f64::from(height.max(1)) / f64::from(h)); let coverage = match colorize { - Some(paint) => { + Some((paint, overprint)) => { let Some((_, _, coverage)) = self.coverage(blob).filter(|(cw, ch, _)| (*cw, *ch) == (w, h)) else { self.warn(UNDECODED); return; }; - Some((paint, coverage)) + Some((paint, overprint, coverage)) } None => None, }; @@ -1179,7 +1180,7 @@ impl<'a> Writer<'a> { let (w, h) = (x1 - x0, y1 - y0); // Over white. let over = |c: u8, a: u8| ((u32::from(c) * u32::from(a) + 255 * (255 - u32::from(a)) + 127) / 255) as u8; - if let Some((paint, coverage)) = coverage { + if let Some((paint, overprint, coverage)) = coverage { let coverage = ai_ops::window_samples(&coverage, img.width(), 1, window); if coverage.iter().all(|&v| v == 0 || v == 255) { let stride = (w as usize).div_ceil(8); @@ -1191,6 +1192,7 @@ impl<'a> Writer<'a> { } } self.color(paint, false); + self.line(if overprint { "1 O" } else { "0 O" }); self.raster(m, &format!("0 0 {w} {h} {w} {h} 1 1 0 0 0 1"), &bits); return; } diff --git a/crates/eps/src/lib.rs b/crates/eps/src/lib.rs index 44d974bd35..4311a54209 100644 --- a/crates/eps/src/lib.rs +++ b/crates/eps/src/lib.rs @@ -54,7 +54,7 @@ pub use import::{ family_style, import, import_ai, import_names, import_trusting, import_with, is_loss, layered_ai, layered_ai_from, page, }; pub use legacy_ai::{HiddenObjects, LegacyAiOptions, LegacyAiOutput, export_legacy_ai, writes_image_mask}; -pub use print::{PrintJob, PrintPage, print}; +pub use print::{PrintFonts, PrintJob, PrintPage, print}; use vectorcraft_doc::Document; use vectorcraft_geom::{Point, Rect}; diff --git a/crates/eps/src/print.rs b/crates/eps/src/print.rs index 1c85e2cf9c..64a981db8e 100644 --- a/crates/eps/src/print.rs +++ b/crates/eps/src/print.rs @@ -2,6 +2,7 @@ //! document walk the EPS writer uses, in one DSC-conforming file: a page per sheet with its paper //! size, the ink and halftone screen of a separation, the flatness, and film negatives. +use std::cell::RefCell; use std::fmt::Write; use kurbo::{Shape, Vec2}; @@ -11,6 +12,11 @@ use vectorcraft_geom::{Affine, Rect}; use crate::scene::{Page, Scene}; use crate::{EpsOptions, EpsOutput, Level, comments, ps}; +pub(crate) mod fonts; + +pub use fonts::PrintFonts; +use fonts::{FontJob, UsedGlyphs}; + /// One sheet of a print job (see the PDF writer's print plan for how the spaces relate). #[derive(Clone, Debug)] pub struct PrintPage<'a> { @@ -47,6 +53,8 @@ pub struct PrintJob { pub created: Option, /// The flatness curves are drawn with (device pixels); `None`: the device's own. pub flatness: Option, + /// How the type is written: as outlines, or shown through fonts. + pub fonts: PrintFonts, } /// Every number of `a` finite? @@ -55,8 +63,9 @@ fn finite(a: Affine) -> bool { } /// The program that draws sheet `p` (its page setup and content, without the DSC page comment), -/// and what its walks found. -fn sheet(p: &PrintPage, job: &PrintJob) -> Result<(String, Vec), String> { +/// and what its walks found. Its type is shown through the job's `fonts`; the page setup defines +/// the fonts it shows, except the ones a Complete job defines in its setup. +fn sheet(p: &PrintPage, job: &PrintJob, fonts: Option<&RefCell>) -> Result<(String, Vec), String> { let (w, h) = p.size; let r = p.area; if !(w.is_finite() && h.is_finite() && w >= 1.0 && h >= 1.0 && [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())) { @@ -70,7 +79,7 @@ fn sheet(p: &PrintPage, job: &PrintJob) -> Result<(String, Vec), String> { } let opts = |region: Rect| EpsOptions { level: job.level, region, ..EpsOptions::default() }; let art_opts = opts(r); - let art = Scene::new(p.doc, &art_opts).on_plate(p.ink.is_some()).run(); + let art = Scene::new(p.doc, &art_opts).on_plate(p.ink.is_some()).with_fonts(fonts).run(); // The marks' area: the drawing space the page shows (within the tile). let paper = Rect::new(0.0, 0.0, w, h); let shown = if p.view.determinant().abs() > 1e-12 { p.view.inverse().transform_rect_bbox(paper) } else { paper }; @@ -79,7 +88,12 @@ fn sheet(p: &PrintPage, job: &PrintJob) -> Result<(String, Vec), String> { // the copies show. let shown = moves.iter().map(|m| shown - *m).reduce(|a, b| a.union(b)).unwrap_or(shown); let marks_opts = opts(shown); - let marks = p.marks.map(|m| Scene::new(p.doc, &marks_opts).run_node(m)); + let marks = p.marks.map(|m| Scene::new(p.doc, &marks_opts).with_fonts(fonts).run_node(m)); + let mut page_fonts = String::new(); + if let Some(f) = fonts.filter(|f| f.borrow().mode != PrintFonts::Complete) { + let used = used_glyphs(std::iter::once(&art).chain(marks.as_ref())); + f.borrow_mut().define(&used, &mut page_fonts)?; + } let mut s = String::with_capacity(art.body.len() + art.setup.len() + 1024); let (wi, hi) = (w.ceil() as i64, h.ceil() as i64); let _ = writeln!(s, "%%PageBoundingBox: 0 0 {wi} {hi}"); @@ -89,6 +103,7 @@ fn sheet(p: &PrintPage, job: &PrintJob) -> Result<(String, Vec), String> { } s.push_str("%%BeginPageSetup\n"); let _ = writeln!(s, "/setpagedevice where {{pop << /PageSize [{} {}] >> setpagedevice}} if", ps::num(w), ps::num(h)); + s.push_str(&page_fonts); s.push_str("%%EndPageSetup\nVCdict begin\nq\n"); if p.negative { // Ink becomes clear and paper black: the inverted transfer paints the paper's white black. @@ -149,8 +164,25 @@ pub fn print(pages: &[PrintPage], order: &[usize], job: &PrintJob) -> Result = vec![]; let mut warnings: Vec = vec![]; - for p in pages { - let (s, found) = sheet(p, job)?; + let fonts = (job.fonts != PrintFonts::Outlines).then(|| RefCell::new(FontJob::new(job.fonts))); + let mut used = UsedGlyphs::new(); + // Only the sheets `order` prints are drawn: the fonts, warnings and colors of the others stay + // out of the file. + let mut printed = vec![false; pages.len()]; + for i in order { + if let Some(p) = printed.get_mut(*i) { + *p = true; + } + } + for (p, printed) in pages.iter().zip(printed) { + if !printed { + drawn.push(String::new()); + continue; + } + let (s, found) = sheet(p, job, fonts.as_ref())?; + for (face, gids) in used_glyphs(&found) { + used.entry(face).or_default().extend(gids); + } for page in found { for c in page.custom { if !custom.iter().any(|(n, _)| *n == c.0) { @@ -165,23 +197,57 @@ pub fn print(pages: &[PrintPage], order: &[usize], job: &PrintJob) -> Result(pages: impl IntoIterator) -> UsedGlyphs { + let mut used = UsedGlyphs::new(); + for page in pages { + for (face, gids) in &page.fonts { + used.entry(*face).or_default().extend(gids); + } + } + used } #[cfg(test)] diff --git a/crates/eps/src/print/fonts.rs b/crates/eps/src/print/fonts.rs new file mode 100644 index 0000000000..a220299131 --- /dev/null +++ b/crates/eps/src/print/fonts.rs @@ -0,0 +1,276 @@ +//! The fonts a print job shows its type in: Type 3 fonts drawn from the faces' own outlines, sent +//! with the pages that use them or once for the whole job, or the printer's own copy of each font, +//! asked for by its PostScript name. +//! +//! A face's glyphs are shown through fonts of at most 256 glyphs each: glyph `gid` is code +//! `gid % 256` of the face's font number `gid / 256`, so every page and the job's setup name each +//! glyph the same way. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::fmt::Write; +use std::sync::Arc; + +use craft_ps::write::{PathOps, push_path}; +use kurbo::{BezPath, Shape}; +use vectorcraft_text::FontFace; +use vectorcraft_text::embed::Embedding; + +use crate::ps; + +/// How a print job writes its type. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum PrintFonts { + /// As glyph outlines in the art: no fonts. + #[default] + Outlines, + /// In the printer's copy of each font, asked for by its PostScript name: no font program is + /// sent, and a printer without the font substitutes another. + Resident, + /// In fonts holding the glyphs each page shows, sent with that page. + Subset, + /// In fonts holding every glyph of each face the job shows, sent once before the first page. + Complete, +} + +/// Most bytes the font definitions of one page, or of a job's setup, may take. +pub(crate) const MAX_FONTS: usize = 64 << 20; + +/// The glyphs a walk showed through fonts: the job's index of each face → its glyph ids. +pub(crate) type UsedGlyphs = BTreeMap>; + +/// One face the job shows type in. +struct JobFace { + face: Arc, + /// Its type is shown through fonts (false: drawn as outlines, for its license). + shown: bool, +} + +/// The fonts of a whole job, shared by the walks of its sheets. +pub(crate) struct FontJob { + pub mode: PrintFonts, + /// Most bytes the font definitions of one page, or of the job's setup, may take + /// ([`MAX_FONTS`]). + pub max: usize, + /// The faces in the order the job first shows them. + faces: Vec, + /// Face id ([`FontFace::id`]) → its index in `faces`. + by_id: HashMap, + /// Glyph names in the faces' `post` or `CFF` tables, read once ([`PrintFonts::Resident`]). + names: HashMap<(usize, u32), Option>, + /// What prints otherwise than the mode asks. + pub warnings: Vec, + /// Notes on the mode: the fonts the printer must have. + pub notes: Vec, +} + +/// The name a job's font number `chunk` of face `face` is defined and shown by. +pub(crate) fn font_name(face: usize, chunk: u32) -> String { + format!("VCft{face}.{chunk}") +} + +/// The face's name as the warnings give it. +fn display_name(face: &FontFace) -> String { + format!("{} {}", face.family, face.style) +} + +/// Is `name` a glyph name a PostScript name literal can carry as it is? +fn plain_name(name: &str) -> bool { + !name.is_empty() && name.len() <= 127 && name.bytes().all(|b| b.is_ascii_graphic() && !b"[](){}<>/%".contains(&b)) +} + +fn push_unique(v: &mut Vec, s: String) { + if !v.contains(&s) { + v.push(s); + } +} + +impl FontJob { + pub fn new(mode: PrintFonts) -> Self { + Self { mode, max: MAX_FONTS, faces: vec![], by_id: HashMap::new(), names: HashMap::new(), warnings: vec![], notes: vec![] } + } + + /// The job's index of the face of glyph `gid` of face `id`, and the face's units per em, when + /// the glyph is shown through a font; `None` when it is drawn as an outline. `elements` is the + /// number of path elements of the glyph's outline in the layout: an outline the layout changed + /// from the face's own is drawn as it is. + pub fn glyph(&mut self, id: u32, gid: u32, elements: usize) -> Option<(usize, f64)> { + let i = self.face(id)?; + let face = self.faces.get(i)?.face.clone(); + if vectorcraft_text::FontDb::global().outline(&face, gid).elements().len() != elements { + return None; + } + if self.mode == PrintFonts::Resident && self.glyph_name(i, gid).is_none() { + push_unique( + &mut self.warnings, + format!("some glyphs of the font “{}” have no names to ask the printer's copy for: they print as outlines", display_name(&face)), + ); + return None; + } + Some((i, face.units_per_em())) + } + + /// The job's index of face `id` when its type is shown through fonts. + fn face(&mut self, id: u32) -> Option { + if let Some(i) = self.by_id.get(&id) { + return self.faces.get(*i).filter(|f| f.shown).map(|_| *i); + } + let face = vectorcraft_text::FontDb::global().face_by_id(id)?; + let name = display_name(&face); + let shown = match (self.mode, face.embedding()) { + (PrintFonts::Outlines, _) => false, + (PrintFonts::Resident, _) => { + push_unique(&mut self.notes, format!("Fonts: None: the printer needs the font “{}” ({})", face.postscript_name(), name)); + true + } + (PrintFonts::Subset | PrintFonts::Complete, Embedding::Forbidden) => { + push_unique( + &mut self.warnings, + format!("the license of the font “{name}” doesn't allow sending it to the printer: its type prints as outlines"), + ); + false + } + (PrintFonts::Subset, Embedding::Whole) => { + push_unique( + &mut self.warnings, + format!("the font “{name}” may only be sent whole, and Fonts is Subset: its type prints as outlines (Complete sends it)"), + ); + false + } + (PrintFonts::Subset | PrintFonts::Complete, _) => face.units_per_em() > 0.0, + }; + let i = self.faces.len(); + self.faces.push(JobFace { face, shown }); + self.by_id.insert(id, i); + shown.then_some(i) + } + + /// The name of glyph `gid` of the job's face `i` that a PostScript name literal can carry. + fn glyph_name(&mut self, i: usize, gid: u32) -> Option { + if let Some(n) = self.names.get(&(i, gid)) { + return n.clone(); + } + let name = self.faces.get(i).and_then(|f| f.face.glyph_name(gid)).filter(|n| plain_name(n) && n != ".notdef"); + self.names.insert((i, gid), name.clone()); + name + } + + /// Every glyph of every face the job shows through fonts ([`PrintFonts::Complete`]). + pub fn every_glyph(&self, used: &UsedGlyphs) -> UsedGlyphs { + used.keys().filter_map(|i| Some((*i, (0..self.faces.get(*i)?.face.glyph_count()).collect()))).collect() + } + + /// The fonts `used` names, as DSC resource names: the printer's fonts with + /// [`PrintFonts::Resident`], else the fonts the job defines. + pub fn resources(&self, used: &UsedGlyphs) -> Vec { + let mut out = vec![]; + for (i, gids) in used { + match self.faces.get(*i) { + Some(f) if self.mode == PrintFonts::Resident => push_unique(&mut out, f.face.postscript_name()), + Some(_) => { + for chunk in gids.iter().map(|g| g >> 8).collect::>() { + push_unique(&mut out, font_name(*i, chunk)); + } + } + None => {} + } + } + out + } + + /// Append the definitions of the fonts that show `used` to `s`: Type 3 fonts holding those + /// glyphs, or, with [`PrintFonts::Resident`], the printer's fonts with an encoding naming them. + /// An error, before `s` holds any of them, when they would take more than [`Self::max`] bytes. + pub fn define(&mut self, used: &UsedGlyphs, s: &mut String) -> Result<(), String> { + let mut out = String::new(); + self.define_into(used, &mut out)?; + s.push_str(&out); + Ok(()) + } + + fn define_into(&mut self, used: &UsedGlyphs, s: &mut String) -> Result<(), String> { + for (i, gids) in used { + let Some(face) = self.faces.get(*i).map(|f| f.face.clone()) else { continue }; + let mut chunks: BTreeMap> = BTreeMap::new(); + for g in gids { + chunks.entry(g >> 8).or_default().push(*g); + } + let ps_name = face.postscript_name(); + if self.mode == PrintFonts::Resident { + let _ = writeln!(s, "%%IncludeResource: font {ps_name}"); + } + for (chunk, gids) in chunks { + let name = font_name(*i, chunk); + if self.mode == PrintFonts::Resident { + // The printer's font, with an encoding that gives each glyph its code. + let _ = writeln!(s, "/{ps_name} findfont dup length dict begin\n{{1 index /FID ne {{def}} {{pop pop}} ifelse}} forall"); + s.push_str("/Encoding 256 array def 0 1 255 {Encoding exch /.notdef put} for\n"); + for g in gids { + if let Some(n) = self.glyph_name(*i, g) { + let _ = writeln!(s, "Encoding {} /{n} put", g & 0xff); + } + } + let _ = writeln!(s, "currentdict end /{name} exch definefont pop"); + } else if !type3(s, &name, &face, &gids, self.max.saturating_sub(s.len())) { + return Err(too_large(&face, self.max)); + } + if s.len() > self.max { + return Err(too_large(&face, self.max)); + } + } + } + Ok(()) + } +} + +fn too_large(face: &FontFace, max: usize) -> String { + let size = if max >= 1 << 20 { format!("{} MB", max >> 20) } else { format!("{} KB", max >> 10) }; + format!("the fonts to send take more than {size} (the font “{}” has {} glyphs): choose Fonts: Subset", display_name(face), face.glyph_count()) +} + +/// Append Type 3 font `name` holding glyphs `gids` of `face` (one font number: codes `gid % 256`) +/// to `s`, drawn from the face's outlines in its font units, y up. False, with nothing added to +/// `s`, when its glyph procedures take more than `room` bytes. +fn type3(s: &mut String, name: &str, face: &FontFace, gids: &[u32], room: usize) -> bool { + let db = vectorcraft_text::FontDb::global(); + let upem = face.units_per_em(); + let flip = kurbo::Affine::FLIP_Y; + let mut procs = String::new(); + let mut bbox: Option = None; + for g in gids { + let outline: BezPath = flip * (*db.outline(face, *g)).clone(); + let b = if outline.elements().is_empty() { kurbo::Rect::ZERO } else { outline.bounding_box() }; + if !outline.elements().is_empty() { + bbox = Some(bbox.map_or(b, |r| r.union(b))); + } + let _ = write!(procs, "/g{g} {{{} 0 ", ps::num(face.advance(*g))); + ps::push_nums(&mut procs, &[b.x0, b.y0, b.x1, b.y1]); + procs.push_str("setcachedevice\n"); + if !outline.elements().is_empty() { + push_path(&mut procs, &outline, PathOps::STANDARD); + procs.push_str("fill\n"); + } + procs.push_str("} bind def\n"); + if procs.len() > room { + return false; + } + } + let b = bbox.unwrap_or(kurbo::Rect::ZERO); + let _ = writeln!(s, "%%BeginResource: font {name}"); + let _ = writeln!(s, "/{name} 10 dict begin\n/FontType 3 def"); + s.push_str("/FontMatrix ["); + ps::push_num_places(s, 1.0 / upem, 9); + s.push_str(" 0 0 "); + ps::push_num_places(s, 1.0 / upem, 9); + s.push_str(" 0 0] def\n/FontBBox ["); + ps::push_nums(s, &[b.x0, b.y0, b.x1, b.y1]); + s.push_str("] def\n/Encoding 256 array def 0 1 255 {Encoding exch /.notdef put} for\n"); + for g in gids { + let _ = writeln!(s, "Encoding {} /g{g} put", g & 0xff); + } + let _ = writeln!(s, "/CharProcs {} dict def\nCharProcs begin\n/.notdef {{0 0 0 0 0 0 setcachedevice}} bind def", gids.len() + 1); + s.push_str(&procs); + s.push_str("end\n/BuildGlyph {exch /CharProcs get exch 2 copy known not {pop /.notdef} if get exec} bind def\n"); + s.push_str("/BuildChar {1 index /Encoding get exch get 1 index /BuildGlyph get exec} bind def\n"); + s.push_str("currentdict end definefont pop\n%%EndResource\n"); + true +} diff --git a/crates/eps/src/print/tests.rs b/crates/eps/src/print/tests.rs index 7600435c79..e560f7ab8d 100644 --- a/crates/eps/src/print/tests.rs +++ b/crates/eps/src/print/tests.rs @@ -416,3 +416,251 @@ fn an_overprinting_freeform_gradient_leaves_out_the_cells_its_samples_write_with let cyan = Paint::solid(Color::cmyk(1.0, 0.0, 0.0, 0.0)); assert_keeps_the_ink_below(&[("faint", overprinting(Paint::Gradient(Box::new(freeform)), Paint::None), cyan, "Cyan")]); } + +/// A 200 × 100 pt document with `words` at 24 pt in black, in family `family`. +fn typed(words: &str, family: &str) -> Document { + let mut d = Document::new(200.0, 100.0); + let layer = d.layers[0].id; + let style = CharStyle { font_family: family.into(), size: 24.0, fill: Paint::solid(Color::BLACK), ..CharStyle::default() }; + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 60.0), words, style)))); + d.insert(Some(layer), 0, n).unwrap(); + d +} + +/// The regular face of `family`. +fn face_of(family: &str) -> std::sync::Arc { + vectorcraft_text::FontDb::global().face(family, "Regular").unwrap() +} + +/// The bundled fallback face as another family `family` (13 characters, like the bundled name), +/// whose license flags (OS/2 `fsType`) are `fs`. +fn licensed(family: &str, fs: u16) -> String { + let fallback = vectorcraft_text::FALLBACK_FAMILY; + let mut bytes = face_of(fallback).file_data().to_vec(); + let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::>(); + for (from, to) in [(utf16(fallback), utf16(family)), (fallback.as_bytes().to_vec(), family.as_bytes().to_vec())] { + assert_eq!(from.len(), to.len()); + let mut at = 0; + while let Some(i) = bytes[at..].windows(from.len()).position(|w| w == from) { + bytes[at + i..at + i + from.len()].copy_from_slice(&to); + at += i + from.len(); + } + } + let tables = u16::from_be_bytes([bytes[4], bytes[5]]) as usize; + let os2 = (0..tables).map(|i| 12 + 16 * i).find(|r| &bytes[*r..*r + 4] == b"OS/2").unwrap(); + let off = u32::from_be_bytes(bytes[os2 + 8..os2 + 12].try_into().unwrap()) as usize; + bytes[off + 8..off + 10].copy_from_slice(&fs.to_be_bytes()); + vectorcraft_text::FontDb::global().add_font(bytes); + assert!(vectorcraft_text::FontDb::global().has_family(family)); + family.into() +} + +/// The job's setup and each page's program. +fn sections(ps: &str) -> (&str, Vec<&str>) { + let setup = ps.split_once("%%BeginSetup\n").and_then(|(_, rest)| rest.split_once("%%EndSetup")).map_or("", |(setup, _)| setup); + (setup, ps.split("%%Page: ").skip(1).collect()) +} + +/// How many glyph procedures the Type 3 fonts in `ps` define. +fn procs(ps: &str) -> usize { + ps.lines().filter(|l| l.starts_with("/g") && l.ends_with("setcachedevice")).count() +} + +fn fonts_job(fonts: PrintFonts) -> PrintJob { + PrintJob { fonts, ..PrintJob::default() } +} + +#[test] +fn type_prints_as_outlines_unless_the_job_sends_fonts() { + assert_eq!(PrintJob::default().fonts, PrintFonts::Outlines); + let d = typed("AAB", vectorcraft_text::FALLBACK_FAMILY); + let ps = text(&print(&[page(&d, None)], &[0], &PrintJob::default()).unwrap()); + assert!(!ps.contains("FontType") && !ps.contains("> show") && !ps.contains("Resources:"), "{ps}"); +} + +#[test] +fn subset_downloads_used_glyphs_once_per_page() { + let d = typed("AAB", vectorcraft_text::FALLBACK_FAMILY); + let sheets = [page(&d, None), PrintPage { ink: Some(("Black", 60.0, 45.0)), ..page(&d, None) }]; + for level in [Level::Two, Level::Three] { + let out = print(&sheets, &[0, 1, 0], &PrintJob { level, ..fonts_job(PrintFonts::Subset) }).unwrap(); + let ps = text(&out); + assert!(ps.contains("%%DocumentSuppliedResources: font VCft0.0\n"), "{ps}"); + let (setup, pages) = sections(&ps); + assert!(!setup.contains("FontType"), "{setup}"); + assert_eq!(pages.len(), 3); + for p in pages { + // Each printed page, copies and plates included, defines the font with A and B alone. + let (page_setup, body) = p.split_once("%%EndPageSetup").unwrap(); + assert_eq!(page_setup.matches("/FontType 3 def").count(), 1, "{page_setup}"); + assert_eq!(procs(page_setup), 2, "{page_setup}"); + assert_eq!(body.matches("> show").count(), 3, "{body}"); + assert!(body.contains("/VCft0.0 findfont"), "{body}"); + assert_eq!(procs(body), 0); + } + assert!(out.warnings.is_empty() && out.setting_notes.is_empty(), "{:?} {:?}", out.warnings, out.setting_notes); + } + // Read back, the type the font shows draws where its outlines do. + let area = Rect::new(36.0, 36.0, 236.0, 136.0); + let drawn = |fonts| { + let out = print(&sheets[..1], &[0], &fonts_job(fonts)).unwrap(); + render_region(&crate::import(&out.bytes).unwrap().document, area, 2.0) + }; + let (outlined, shown) = (drawn(PrintFonts::Outlines), drawn(PrintFonts::Subset)); + assert!(outlined.ink() > 200, "{}", outlined.ink()); + let (a, b) = (outlined.ink() as f64, shown.ink() as f64); + assert!((a - b).abs() < a * 0.05, "outlines {a} px, fonts {b} px"); + vectorcraft_testkit::raster::assert_similar(&outlined, &shown, 24.0, 0.002); +} + +#[test] +fn complete_downloads_whole_font_once_before_pages() { + let d = typed("AAB", vectorcraft_text::FALLBACK_FAMILY); + let glyphs = face_of(vectorcraft_text::FALLBACK_FAMILY).glyph_count() as usize; + assert!(glyphs > 256, "{glyphs}"); + let out = print(&[page(&d, None)], &[0, 0], &fonts_job(PrintFonts::Complete)).unwrap(); + let ps = text(&out); + let (setup, pages) = sections(&ps); + // Every glyph of the face, in fonts of 256 glyphs, before the first page. + assert_eq!(procs(setup), glyphs); + assert_eq!(setup.matches("/FontType 3 def").count(), glyphs.div_ceil(256)); + let header = ps.split_once("%%EndComments").unwrap().0; + let supplied = header.lines().filter(|l| l.starts_with("%%DocumentSuppliedResources: font ") || l.starts_with("%%+ font VCft")).count(); + assert_eq!(supplied, glyphs.div_ceil(256), "{header}"); + assert_eq!(pages.len(), 2); + for p in pages { + assert!(!p.contains("FontType") && procs(p) == 0, "{p}"); + assert_eq!(p.matches("> show").count(), 3); + } + assert!(out.warnings.is_empty() && out.setting_notes.is_empty(), "{:?} {:?}", out.warnings, out.setting_notes); + // A sheet the order doesn't print sends no font, in any mode. + let plain = doc(); + for fonts in [PrintFonts::Complete, PrintFonts::Subset, PrintFonts::Resident] { + let out = print(&[page(&plain, None), page(&d, None)], &[0], &fonts_job(fonts)).unwrap(); + let ps = text(&out); + assert!(!ps.contains("FontType") && !ps.contains("Resources:") && !ps.contains("findfont"), "{fonts:?}: {ps}"); + assert!(out.setting_notes.is_empty(), "{fonts:?}: {:?}", out.setting_notes); + } +} + +#[test] +fn none_references_font_without_downloading_it() { + let face = face_of(vectorcraft_text::FALLBACK_FAMILY); + let name = face.postscript_name(); + let d = typed("AAB", vectorcraft_text::FALLBACK_FAMILY); + let out = print(&[page(&d, None)], &[0, 0], &fonts_job(PrintFonts::Resident)).unwrap(); + let ps = text(&out); + assert!(!ps.contains("FontType") && !ps.contains("setcachedevice") && !ps.contains("%%BeginResource"), "{ps}"); + assert!(ps.contains(&format!("%%DocumentNeededResources: font {name}\n")), "{ps}"); + let (_, pages) = sections(&ps); + assert_eq!(pages.len(), 2); + for p in pages { + let (page_setup, body) = p.split_once("%%EndPageSetup").unwrap(); + assert!(page_setup.contains(&format!("%%IncludeResource: font {name}\n")), "{page_setup}"); + // The printer's font, re-encoded with the names of the glyphs the page shows. + assert!(page_setup.contains(&format!("/{name} findfont dup length dict begin")), "{page_setup}"); + assert!(page_setup.contains(" /A put\n") && page_setup.contains(" /B put\n"), "{page_setup}"); + assert_eq!(body.matches("> show").count(), 3, "{body}"); + } + assert!(out.warnings.is_empty(), "{:?}", out.warnings); + assert_eq!(out.setting_notes.len(), 1, "{:?}", out.setting_notes); + assert!(out.setting_notes[0].contains(&name), "{:?}", out.setting_notes); +} + +#[test] +fn forbidden_font_stays_art_with_a_note() { + let locked = licensed("Locked Sans 3", 0x0002); + let whole = licensed("Entire Sans 3", 0x0100); + let fonts_of = |family: &str, fonts| { + let d = typed("AB", family); + let out = print(&[page(&d, None)], &[0], &fonts_job(fonts)).unwrap(); + (text(&out), out.warnings) + }; + for fonts in [PrintFonts::Subset, PrintFonts::Complete] { + let (ps, warnings) = fonts_of(&locked, fonts); + assert!(!ps.contains("FontType") && !ps.contains("> show"), "{ps}"); + assert!(warnings.iter().any(|w| w.contains(&locked) && w.contains("doesn't allow")), "{warnings:?}"); + } + // A font that may only be sent whole prints as outlines in a subset job and is sent complete. + let (ps, warnings) = fonts_of(&whole, PrintFonts::Subset); + assert!(!ps.contains("FontType") && !ps.contains("> show"), "{ps}"); + assert!(warnings.iter().any(|w| w.contains(&whole) && w.contains("whole")), "{warnings:?}"); + let (ps, warnings) = fonts_of(&whole, PrintFonts::Complete); + assert!(sections(&ps).0.contains("/FontType 3 def") && ps.contains("> show"), "{ps}"); + assert!(warnings.is_empty(), "{warnings:?}"); + // None sends no font program, so the license doesn't keep it from naming the font. + let (ps, warnings) = fonts_of(&locked, PrintFonts::Resident); + assert!(ps.contains("> show") && !ps.contains("FontType"), "{ps}"); + assert!(warnings.is_empty(), "{warnings:?}"); +} + +#[test] +fn complete_large_font_fails_before_partial_output() { + let face = face_of(vectorcraft_text::FALLBACK_FAMILY); + let gid = face.glyph_for('A'); + let elements = vectorcraft_text::FontDb::global().outline(&face, gid).elements().len(); + let mut job = fonts::FontJob::new(PrintFonts::Complete); + let (i, _) = job.glyph(face.id(), gid, elements).unwrap(); + let used = job.every_glyph(&fonts::UsedGlyphs::from([(i, std::collections::BTreeSet::from([gid]))])); + job.max = 64 << 10; + let mut s = String::from("before\n"); + let e = job.define(&used, &mut s).unwrap_err(); + assert!(e.contains("64 KB") && e.contains("Subset"), "{e}"); + assert_eq!(s, "before\n"); + // With room, every glyph is defined. + job.max = fonts::MAX_FONTS; + job.define(&used, &mut s).unwrap(); + assert_eq!(procs(&s), face.glyph_count() as usize); +} + +#[test] +fn type_left_out_for_the_page_limit_sends_none_of_its_glyphs() { + let family = vectorcraft_text::FALLBACK_FAMILY; + let face = face_of(family); + let kept = typed("A", family); + let mut both = kept.clone(); + let layer = both.layers[0].id; + let style = CharStyle { font_family: family.into(), size: 24.0, fill: Paint::solid(Color::BLACK), ..CharStyle::default() }; + let n = Node::new(both.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(20.0, 90.0), "BCDEFGH", style)))); + both.insert(Some(layer), 1, n).unwrap(); + let o = EpsOptions { region: kept.artboards[0].rect, ..EpsOptions::default() }; + let walk = |d: &Document, max: usize| { + let job = RefCell::new(fonts::FontJob::new(PrintFonts::Subset)); + crate::scene::Scene::new(d, &o).with_fonts(Some(&job)).with_max_body(max).run() + }; + let alone = walk(&kept, usize::MAX); + assert_eq!(alone.fonts.values().map(|g| g.len()).sum::(), 1, "{:?}", alone.fonts); + // The second object passes the limit and is left out: only the glyph of the first is used. + let page = walk(&both, alone.body.len() + 10); + assert!(page.warnings.iter().any(|w| w.contains("too large")), "{:?}", page.warnings); + assert_eq!(page.body, alone.body); + assert_eq!(page.fonts, alone.fonts); + assert!(page.fonts.values().all(|g| g.contains(&face.glyph_for('A'))), "{:?}", page.fonts); +} + +#[test] +fn ruby_prints_as_outlines_where_the_canvas_draws_it() { + let family = vectorcraft_text::FALLBACK_FAMILY; + let mut d = Document::new(200.0, 100.0); + let layer = d.layers[0].id; + let style = CharStyle { font_family: family.into(), size: 24.0, fill: Paint::solid(Color::BLACK), ..CharStyle::default() }; + let mut t = TextObject::point(Point::new(20.0, 60.0), "AB", style); + t.ruby = vec![vectorcraft_doc::RubySpan::new(0, 2, "xy")]; + let n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + d.insert(Some(layer), 0, n).unwrap(); + let area = Rect::new(36.0, 36.0, 236.0, 136.0); + let drawn = |fonts| { + let out = print(&[page(&d, None)], &[0], &fonts_job(fonts)).unwrap(); + (text(&out), render_region(&crate::import(&out.bytes).unwrap().document, area, 2.0)) + }; + let (_, outlined) = drawn(PrintFonts::Outlines); + for fonts in [PrintFonts::Subset, PrintFonts::Complete] { + let (ps, shown) = drawn(fonts); + // The base text shows through the font; its reading is drawn as outlines, in place. + assert_eq!(ps.matches("> show").count(), 2, "{fonts:?}: {ps}"); + if fonts == PrintFonts::Subset { + assert_eq!(procs(&ps), 2, "{ps}"); + } + vectorcraft_testkit::raster::assert_similar(&outlined, &shown, 24.0, 0.002); + } +} diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index 35a68371b1..1193839d0b 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -2,6 +2,7 @@ //! space (the page's first operator maps it onto PostScript's y-up space). Mirrors the PDF //! writer's walk, without transparency. +use std::cell::RefCell; use std::collections::HashMap; use std::fmt::Write; use std::sync::Arc; @@ -14,6 +15,7 @@ use vectorcraft_doc::{ use vectorcraft_effects::stroke::{self, WrittenShape}; use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, Vec2}; +use crate::print::fonts::{FontJob, UsedGlyphs, font_name}; use crate::ps::{self, clip_op, fill_op, push_nums, push_path}; use crate::{EpsOptions, Level, Overprint}; @@ -149,6 +151,8 @@ pub(crate) struct Page { pub body: String, pub custom: Vec<(String, [f32; 4])>, pub warnings: Vec, + /// The glyphs shown through the print job's fonts ([`Scene::with_fonts`]). + pub fonts: UsedGlyphs, } /// The colour spaces process colours are written in. @@ -215,6 +219,13 @@ enum Ink { Spot { space: usize, tint: f32 }, } +/// One drawing of an overprinting colorized image: the name of the color space it is drawn in +/// and the amount of each of that space's inks ([`Scene::overprint_passes`]). +struct InkPass { + space: String, + values: Vec, +} + fn unit(v: f32) -> f32 { if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 } } @@ -287,6 +298,14 @@ pub(crate) struct Scene<'a> { /// The gradient being painted overprints on a plate: where it is paper white it puts none of /// the plate's ink down, and the plate below it is left as it is ([`Self::inked_spans`]). keep_below: bool, + /// The print job's fonts: type in a solid fill is shown through them (`None`: drawn as + /// outlines). + fonts: Option<&'a RefCell>, + /// The glyphs shown through `fonts`. + used: UsedGlyphs, + /// The glyphs `used` gained, in the order it gained them: an object left out for the page + /// limit takes its own back out of `used` ([`Self::forget_glyphs`]). + used_order: Vec<(usize, u32)>, } impl<'a> Scene<'a> { @@ -317,9 +336,18 @@ impl<'a> Scene<'a> { nest: 0, plate: false, keep_below: false, + fonts: None, + used: UsedGlyphs::new(), + used_order: vec![], } } + /// This scene showing type through the print job's fonts `fonts`. + pub fn with_fonts(mut self, fonts: Option<&'a RefCell>) -> Self { + self.fonts = fonts; + self + } + /// This scene drawing a separation's plate when `plate` is true: an overprinting gradient /// paints only where it puts the plate's ink down, as an overprinting solid color that puts /// none down is drawn as nothing on it. @@ -400,7 +428,7 @@ impl<'a> Scene<'a> { .filter(|(n, ..)| n != vectorcraft_color::swatch::REGISTRATION) .map(|(_, colorant, cmyk)| (colorant.clone(), *cmyk)) .collect(); - Page { setup: self.setup, body: self.body, custom, warnings: self.warnings } + Page { setup: self.setup, body: self.body, custom, warnings: self.warnings, fonts: self.used } } fn warn(&mut self, w: &str) { @@ -544,7 +572,7 @@ impl<'a> Scene<'a> { _ => {} } self.note_losses(n); - let (was, placed, codes) = (self.body.len(), self.placements.len(), self.codes.len()); + let (was, placed, codes, glyphs) = (self.body.len(), self.placements.len(), self.codes.len(), self.used_order.len()); match &n.kind { NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => { children.iter().for_each(|c| self.node(c, false)); @@ -568,8 +596,23 @@ impl<'a> Scene<'a> { let im = &*shown; let blob = self.doc.image_blob(im); match n.extras().colorize.as_deref() { + // On a plate, an overprinting image whose color puts none of the plate's ink + // down is drawn as nothing, as such a solid color is ([`Self::on_plate`]). + Some(p) + if self.plate + && self.o.overprint == Overprint::Preserve + && n.colorize_overprints() + && vectorcraft_doc::overprint::is_white(p) => {} + // Off a plate, a white process color knocks out with Discard White Overprint + // (a plate's colors come from the separator, which has applied it already); a + // spot ink with a white color still overprints, as it is written as that ink. Some(p @ Paint::Solid { .. }) if blob.is_none_or(|b| b.gray_source().is_some()) => { - self.colorized_image(&im.key, blob, im.width, im.height, im.xf, p); + let discarded = !self.plate + && vectorcraft_doc::overprint::is_white(p) + && vectorcraft_doc::overprint::DiscardWhite::of(self.doc).discards(p); + let on = self.overprint_on(n.colorize_overprints() && !discarded); + self.colorized_image(im, blob, p, on); + self.overprint_off(on); } _ => self.image(&im.key, blob, im.width, im.height, im.xf), } @@ -605,10 +648,23 @@ impl<'a> Scene<'a> { self.body.truncate(was); self.unplace(placed); self.forget_codes(codes); + self.forget_glyphs(glyphs); self.warn(TOO_LARGE); } } + /// Take the glyphs `used` gained after its first `n` back out of it. + fn forget_glyphs(&mut self, n: usize) { + for (face, gid) in self.used_order.drain(n.min(self.used_order.len())..) { + if let Some(gids) = self.used.get_mut(&face) { + gids.remove(&gid); + if gids.is_empty() { + self.used.remove(&face); + } + } + } + } + /// How long the page body will be: what is written and what its image placements add. fn size(&self) -> usize { self.body.len().saturating_add(self.pending) @@ -901,8 +957,18 @@ impl<'a> Scene<'a> { let _ = writeln!(self.body, "{} cm", ps::matrix(t.xf)); for (i, run) in t.runs.iter().enumerate() { let mut bp = BezPath::new(); + // With the job's fonts, a run in a solid fill shows its glyphs through them; `art` + // holds the outlines of those it draws as art. + let fonts = if matches!(run.style.fill, Paint::Solid { .. }) { self.fonts } else { None }; + let mut shown = vec![]; + let mut art = BezPath::new(); for g in layout.glyphs.iter().filter(|g| g.run == i) { bp.extend(g.outline.iter()); + match fonts.and_then(|f| self.font_of(f, g)) { + Some((face, upem)) => shown.push((face, upem, g)), + None if fonts.is_some() => art.extend(g.outline.iter()), + None => {} + } // Colour bitmap glyphs (emoji): their images, which the run's paint doesn't paint. if let Some((image, to_text)) = g.placed_image() { let key = format!("\u{0}glyph\u{0}{}", image.blob.content_key()); @@ -916,11 +982,21 @@ impl<'a> Scene<'a> { // Ruby (furigana) glyphs in their base text's run's paint, as the canvas draws them. for g in layout.ruby.iter().filter(|g| g.run == i) { bp.extend(g.outline.iter()); + if fonts.is_some() { + art.extend(g.outline.iter()); + } } if bp.elements().is_empty() { continue; } - self.fill(&bp, FillRule::NonZero, &run.style.fill, layout.bounds, run.style.overprint_fill); + if fonts.is_none() { + self.fill(&bp, FillRule::NonZero, &run.style.fill, layout.bounds, run.style.overprint_fill); + } else { + self.show(&shown, &run.style.fill, run.style.overprint_fill); + if !art.elements().is_empty() { + self.fill(&art, FillRule::NonZero, &run.style.fill, layout.bounds, run.style.overprint_fill); + } + } if run.style.has_stroke() { // Character strokes are drawn in text space, with their cap, join and dashes. self.stroke(&bp, FillRule::NonZero, &run.style.stroke_layer(), layout.bounds); @@ -948,6 +1024,52 @@ impl<'a> Scene<'a> { } } + /// The job's index of the face of glyph `g` and its units per em when `g` is shown through + /// the job's fonts `fonts` (recorded in `used`); `None` when it is drawn as an outline: a glyph + /// with no outline, a color glyph, one bent along a path, or one its face's fonts don't show. + fn font_of(&mut self, fonts: &RefCell, g: &vectorcraft_text::PositionedGlyph) -> Option<(usize, f64)> { + if g.outline.elements().is_empty() || g.bend.is_some() || g.image.is_some() || g.colour.is_some() || !invertible(g.xf) { + return None; + } + let (face, upem) = fonts.borrow_mut().glyph(g.font_id, g.gid, g.outline.elements().len())?; + if self.used.entry(face).or_default().insert(g.gid) { + self.used_order.push((face, g.gid)); + } + Some((face, upem)) + } + + /// Show `glyphs` (the job's index of each one's face, its units per em, the glyph) through the + /// job's fonts in solid paint `p`: each glyph at its own place, through a font made for its + /// size and slant. + fn show(&mut self, glyphs: &[(usize, f64, &vectorcraft_text::PositionedGlyph)], p: &Paint, overprint: bool) { + let Paint::Solid { color, swatch, tint } = p else { return }; + if glyphs.is_empty() { + return; + } + let on = self.overprint_on(overprint); + let ink = self.solid(color, swatch.as_deref(), *tint); + self.set_ink(ink); + let mut current: Option<(String, [f64; 4])> = None; + for (face, upem, g) in glyphs { + // Font units (y up) → text space: the glyph's own map after the flip to y down. + let [a, b, c, d, e, f] = (g.xf * Affine::scale_non_uniform(*upem, -*upem)).as_coeffs(); + let name = font_name(*face, g.gid >> 8); + let key = (name, [a, b, c, d]); + if current.as_ref() != Some(&key) { + let _ = write!(self.body, "/{} findfont [", key.0); + for v in [a, b, c, d] { + ps::push_num_places(&mut self.body, v, 6); + self.body.push(' '); + } + self.line("0 0] makefont setfont"); + current = Some(key); + } + push_nums(&mut self.body, &[e, f]); + let _ = writeln!(self.body, "moveto <{:02x}> show", g.gid & 0xff); + } + self.overprint_off(on); + } + // ---------- gradients ---------- /// The colour space a gradient's stops are written in, and its stops in it from offset 0 to 1 @@ -1775,14 +1897,90 @@ impl<'a> Scene<'a> { i } - /// Gray coverage in the selected process or Separation ink. Binary coverage is a stencil; - /// continuous coverage leaves zero pixels untouched at Level 3 and writes them as paper at Level 2. - fn colorized_image(&mut self, key: &str, blob: Option<&ImageBlob>, width: u32, height: u32, xf: Affine, paint: &Paint) { - let place = xf * Affine::scale_non_uniform(f64::from(width.max(1)), f64::from(height.max(1))); + /// Image `im` (its pixels `blob`) as gray coverage in the selected process or Separation ink. + /// Binary coverage is a stencil; continuous coverage leaves zero pixels untouched at Level 3 + /// and writes them as paper at Level 2. With `overprint` a CMYK or gray color is written in only the + /// process inks it puts down ([`Self::overprint_passes`]), since a zero sample in an image + /// replaces the ink below it. + fn colorized_image(&mut self, im: &vectorcraft_doc::ImageObject, blob: Option<&ImageBlob>, paint: &Paint, overprint: bool) { + let place = im.xf * Affine::scale_non_uniform(f64::from(im.width.max(1)), f64::from(im.height.max(1))); if !invertible(place) { return; } - let cache = (key.to_string(), format!("{paint:?}")); + match overprint.then(|| self.overprint_passes(paint)).flatten() { + Some(passes) => { + // A pass turned away (at the page limit) takes back the passes before it, so the + // image is never written with some of its inks. + let (was, placed, codes) = (self.body.len(), self.placements.len(), self.codes.len()); + for pass in &passes { + let before = self.placements.len(); + self.colorized_pass(&im.key, blob, place, paint, Some(pass)); + if self.placements.len() == before { + self.body.truncate(was); + self.unplace(placed); + self.forget_codes(codes); + return; + } + } + } + None => self.colorized_pass(&im.key, blob, place, paint, None), + } + } + + /// The color spaces an overprinting colorized image of `paint` is drawn in, each with the + /// amounts of its inks, when `paint` is a CMYK or gray process color (gray is black ink): at + /// Level 3 one DeviceN space of the process inks it puts down, at Level 2 a Separation space + /// for each of them. No pass when it puts no ink down. `None` for another paint, which is drawn + /// as it is without overprinting. + fn overprint_passes(&mut self, paint: &Paint) -> Option> { + let Paint::Solid { color, swatch, tint } = paint else { return None }; + let c = match self.solid(color, swatch.as_deref(), *tint) { + Ink::Process(Space::Cmyk, c) => c, + // PostScript's gray is lightness. + Ink::Process(Space::Gray, [lightness, ..]) => [0.0, 0.0, 0.0, unit(1.0 - lightness)], + _ => return None, + }; + let process: Vec = (0..4).filter(|&i| c[i] > 0.0).collect(); + if process.is_empty() { + return Some(vec![]); + } + if self.o.level == Level::Three { + let GradientSpace::Inks(space, _) = self.device_n_space(&process, &[])? else { return None }; + return Some(vec![InkPass { space, values: process.iter().map(|&i| c[i]).collect() }]); + } + Some(process.iter().map(|&i| InkPass { space: self.process_separation(i), values: vec![c[i]] }).collect()) + } + + /// The name of a Separation color space of process ink `i` (an index into CMYK) alone, + /// defined in the setup the first time. + fn process_separation(&mut self, i: usize) -> String { + const SEPARATIONS: [&str; 4] = [ + "/Cyan /DeviceCMYK {0 0 0}", + "/Magenta /DeviceCMYK {0 exch 0 0}", + "/Yellow /DeviceCMYK {0 0 3 -1 roll 0}", + "/Black /DeviceCMYK {0 0 0 4 -1 roll}", + ]; + let def = format!("[/Separation {}]", SEPARATIONS[i.min(3)]); + let i = match self.device_n.iter().position(|d| *d == def) { + Some(i) => i, + None => { + let i = self.device_n.len(); + let _ = writeln!(self.setup, "/VCdn{i} {def} def"); + self.device_n.push(def); + i + } + }; + format!("VCdn{i}") + } + + /// One drawing of a colorized image on the unit square mapped by `place`: in `paint`, or with + /// `pass` in that pass's inks alone ([`Self::overprint_passes`]). + fn colorized_pass(&mut self, key: &str, blob: Option<&ImageBlob>, place: Affine, paint: &Paint, pass: Option<&InkPass>) { + let mut look = format!("{paint:?}"); + if let Some(pass) = pass { + let _ = write!(look, "\u{0}{} {:?}", pass.space, pass.values); + } + let cache = (key.to_string(), look); let encoded = match self.colorized_images.get(&cache) { Some(e) => *e, None => { @@ -1798,7 +1996,7 @@ impl<'a> Scene<'a> { { self.encodes += 1; } - let code = self.encode_colorized(blob, paint); + let code = self.encode_colorized(blob, paint, pass); // An image that can't be placed isn't kept. if let Some(c) = &code && self.size().saturating_add(c.inline_len).saturating_add(64) > self.max_body @@ -1817,7 +2015,8 @@ impl<'a> Scene<'a> { } } - fn encode_colorized(&mut self, blob: Option<&ImageBlob>, paint: &Paint) -> Option { + /// The operators and data of a colorized image of `paint`, or with `pass` of that pass's inks. + fn encode_colorized(&mut self, blob: Option<&ImageBlob>, paint: &Paint, pass: Option<&InkPass>) -> Option { let Some((w, h, coverage)) = blob.and_then(ImageBlob::coverage) else { self.warn(UNDECODED); return None; @@ -1837,13 +2036,20 @@ impl<'a> Scene<'a> { if !binary && clear && !keyed { self.warn(IMAGE_ALPHA_L2); } - // Zero tint is uncommon for covered spot pixels; process uses the same rare key as - // ordinary images. Nudge a covered collision so only clear pixels match the mask. + // Zero tint is uncommon for covered spot pixels (and those of a pass's inks); process + // uses the same rare key as ordinary images. Nudge a covered collision so only clear + // pixels match the mask. let key = match ink { + _ if pass.is_some() => [0, 0, 0, 0], Ink::Spot { .. } => [0, 0, 0, 0], Ink::Process(Space::Gray, ..) => [0, 0, 0, 0], Ink::Process(..) => [255, 0, 255, 0], }; + let n = match (pass, ink) { + (Some(pass), _) => pass.values.len(), + (None, Ink::Spot { .. }) => 1, + (None, Ink::Process(space, ..)) => space.n(), + }; let mut data = Vec::new(); if binary { let stride = (w as usize).div_ceil(8); @@ -1858,14 +2064,21 @@ impl<'a> Scene<'a> { } else { for &v in &coverage { if v == 0 && keyed { - let n = match ink { - Ink::Spot { .. } => 1, - Ink::Process(space, ..) => space.n(), - }; data.extend(key.iter().take(n)); continue; } let a = f32::from(v) / 255.0; + if let Some(pass) = pass { + let mut samples: Vec = pass.values.iter().map(|&v| (255.0 * v * a).round() as u8).collect(); + if keyed + && samples.iter().all(|&s| s == 0) + && let Some(first) = samples.first_mut() + { + *first = 1; + } + data.extend(samples); + continue; + } match ink { Ink::Spot { tint, .. } => { let mut sample = (255.0 * tint * a).round() as u8; @@ -1899,7 +2112,17 @@ impl<'a> Scene<'a> { } }; let mut prelude = String::new(); - if binary { + if let Some(pass) = pass { + let _ = write!(prelude, "{} setcolorspace", pass.space); + if binary { + // imagemask takes its current ink from the graphics state. + for v in &pass.values { + let _ = write!(prelude, " {}", ps::num(f64::from(*v))); + } + prelude.push_str(" setcolor"); + } + prelude.push('\n'); + } else if binary { // imagemask takes its current ink from the graphics state. prelude.push_str(&self.ink_code(ink)); } else { @@ -1912,10 +2135,6 @@ impl<'a> Scene<'a> { } } } - let n = match ink { - Ink::Spot { .. } => 1, - Ink::Process(space, ..) => space.n(), - }; let decode = if binary { "1 0".to_string() } else { "0 1 ".repeat(n).trim_end().to_string() }; let mut dict = format!( "<< /ImageType {} /Width {w} /Height {h} /BitsPerComponent {} /Decode [{decode}] /ImageMatrix [{w} 0 0 {h} 0 0]", diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index e6161da23d..f505dbc0ec 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -1163,6 +1163,130 @@ fn continuous_colorized_coverage_without_clear_pixels_only_warns_for_midtones() assert_eq!(&pixels[6..], &[255, 0, 255]); } +/// A CMYK document holding [`colorized_doc`]'s image of `gray` colorized with `color`, its color +/// overprinting or not. +fn overprinting_colorized_doc(gray: Vec, color: Color, overprint: bool) -> Document { + let mut d = colorized_doc(gray, Some(Paint::solid(color))); + d.color_mode = vectorcraft_doc::ColorMode::Cmyk; + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().extras_mut().colorize_overprint = overprint; + d +} + +/// At the page limit the Level 2 passes of an overprinting colorized image are left out +/// together: the image is never written with some of its inks. +#[test] +fn an_overprinting_colorized_image_at_the_page_limit_keeps_all_its_inks_or_none() { + let gray: Vec = (0..2000u32).map(|i| (i * 37 % 251) as u8).collect(); + let one = overprinting_colorized_doc(gray.clone(), Color::cmyk(0.0, 0.0, 0.0, 1.0), true); + let two = overprinting_colorized_doc(gray, Color::cmyk(0.4, 0.0, 0.0, 1.0), true); + let o = EpsOptions { level: Level::Two, ..opts(&two) }; + let (one, all) = (crate::scene::Scene::new(&one, &o).run().body.len(), crate::scene::Scene::new(&two, &o).run().body.len()); + assert!(all > one + 1000, "{one} {all}"); + let page = crate::scene::Scene::new(&two, &o).with_max_body(one + (all - one) / 2).run(); + assert!(page.warnings.iter().any(|w| w.contains("too large")), "{:?}", page.warnings); + assert!(!page.body.contains("image") && !page.body.contains("VCdn"), "{}", page.body); +} + +/// An overprinting colorized image in a CMYK color is written in only the process inks it puts +/// down, so the plates it leaves at zero keep the inks below: one DeviceN image at Level 3, a +/// Separation image for each ink at Level 2. Not overprinting, it stays one CMYK image. +#[test] +fn an_overprinting_colorized_image_writes_only_its_process_inks() { + let doc = overprinting_colorized_doc; + let ink = Color::cmyk(0.4, 0.0, 0.0, 1.0); + let d = doc(vec![0, 128, 255], ink, true); + + let (ps, pixels, _) = colorized_samples(&d, Level::Three); + assert!(ps.contains("/VCdn0 [/DeviceN [/Cyan /Black ] /DeviceCMYK") && ps.contains("VCdn0 setcolorspace"), "{ps}"); + assert!(!ps.contains("/DeviceCMYK setcolorspace") && ps.contains("/MaskColor [0 0 0 0]"), "{ps}"); + assert_eq!(pixels, vec![102, 255, 51, 127, 0, 0]); + + let (ps, pixels, _) = colorized_samples(&d, Level::Two); + assert!(ps.contains("/VCdn0 [/Separation /Cyan /DeviceCMYK {0 0 0}] def"), "{ps}"); + assert!(ps.contains("/VCdn1 [/Separation /Black /DeviceCMYK {0 0 0 4 -1 roll}] def"), "{ps}"); + assert!(ps.contains("VCdn0 setcolorspace") && ps.contains("VCdn1 setcolorspace") && !ps.contains("/DeviceN"), "{ps}"); + assert_eq!(pixels, vec![102, 51, 0], "the cyan pass first"); + assert_eq!(ps.matches("/ImageType 1").count(), 2, "one image per ink: {ps}"); + + // A gray color is black ink alone. + let gray = doc(vec![0, 128, 255], Color::Gray { k: 0.6 }, true); + for level in Level::ALL { + let (ps, ..) = colorized_samples(&gray, level); + assert!(ps.contains("/Black") && !ps.contains("/DeviceGray setcolorspace") && !ps.contains("/Cyan"), "{ps}"); + } + + // A stencil sets the pass's inks as its color. + let (ps, ..) = colorized_samples(&doc(vec![0, 255, 0], ink, true), Level::Three); + assert!(ps.contains("VCdn0 setcolorspace 0.4 1 setcolor") && ps.contains("imagemask"), "{ps}"); + + // Without overprinting, and with overprints discarded, one CMYK image as before. + let off = doc(vec![0, 128, 255], ink, false); + let discarded = |d: &Document, level| text(&export(d, &EpsOptions { level, overprint: Overprint::Discard, ..opts(d) }, None, None).unwrap()); + for level in Level::ALL { + for ps in [colorized_samples(&off, level).0, discarded(&d, level)] { + assert!(ps.contains("/DeviceCMYK setcolorspace") && !ps.contains("VCdn"), "{ps}"); + } + } + + // Paper white that overprints (Discard White Overprint off) puts no ink down. + let mut white = doc(vec![0, 128, 255], Color::cmyk(0.0, 0.0, 0.0, 0.0), true); + white.setup.discard_white_overprint = false; + for level in Level::ALL { + let ps = page_of(&white, &EpsOptions { level, ..opts(&white) }); + assert!(!ps.contains("image"), "{ps}"); + } + // With Discard White Overprint on, it knocks out: one CMYK image, drawn without overprinting. + white.setup.discard_white_overprint = true; + for level in Level::ALL { + let ps = text(&export(&white, &EpsOptions { level, ..opts(&white) }, None, None).unwrap()); + assert!(ps.contains("/DeviceCMYK setcolorspace") && !ps.contains("VCdn") && !ps.contains("true op"), "{ps}"); + } + + // The same image and color placed overprinting and not keeps two encodings. + let mut both = d.clone(); + let mut n = (*both.layers[0].children().unwrap()[0]).clone(); + n.id = both.alloc_id(); + n.extras_mut().colorize_overprint = false; + both.insert(both.default_layer(), usize::MAX, n).unwrap(); + let ps = text(&export(&both, &EpsOptions { level: Level::Three, ..opts(&both) }, None, None).unwrap()); + assert!(ps.contains("VCdn0 setcolorspace") && ps.contains("/DeviceCMYK setcolorspace"), "{ps}"); +} + +/// On a separation plate, an overprinting colorized image whose color puts none of the plate's ink +/// down is drawn as nothing, so the ink below stays; one that knocks out, or whose overprint is +/// discarded, is drawn as paper. (The plate's colors come from the separator, which has already +/// applied Discard White Overprint.) +#[test] +fn a_plate_leaves_out_an_overprinting_image_without_its_ink() { + let body = |overprint: bool, preserve: bool| { + let mut d = colorized_doc(vec![0, 128, 255], Some(Paint::solid(Color::WHITE))); + d.setup.discard_white_overprint = false; + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().extras_mut().colorize_overprint = overprint; + let o = EpsOptions { overprint: if preserve { Overprint::Preserve } else { Overprint::Discard }, ..opts(&d) }; + crate::scene::Scene::new(&d, &o).on_plate(true).run().body + }; + assert!(!body(true, true).contains("image"), "{}", body(true, true)); + assert!(body(false, true).contains("image"), "{}", body(false, true)); + assert!(body(true, false).contains("image"), "{}", body(true, false)); +} + +/// With Discard White Overprint on, an overprinting colorized image in a tint of a spot ink whose +/// color is white still overprints: it is written as that ink, which is not paper white. +#[test] +fn a_white_spot_ink_colorized_image_overprints_with_discard_white_overprint() { + let mut d = overprinting_colorized_doc(vec![0, 128, 255], Color::WHITE, true); + d.swatches.push(Swatch { name: "White Ink".into(), paint: Paint::solid(Color::WHITE), global: true, spot: true }); + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().extras_mut().colorize = Some(Box::new(Paint::Solid { color: Color::WHITE, swatch: Some("White Ink".into()), tint: 0.5 })); + d.setup.discard_white_overprint = true; + for level in Level::ALL { + let ps = text(&export(&d, &EpsOptions { level, ..opts(&d) }, None, None).unwrap()); + assert!(ps.contains("(White Ink) cvn") && ps.contains("true op"), "{ps}"); + } +} + #[test] fn uncolorized_image_stays_on_original_eps_path() { let d = colorized_doc(vec![0, 128, 255], None); diff --git a/crates/js/src/ast.rs b/crates/js/src/ast.rs index 8d9ffc06c0..92cf258da2 100644 --- a/crates/js/src/ast.rs +++ b/crates/js/src/ast.rs @@ -69,6 +69,8 @@ pub enum BinaryOp { pub enum LogicalOp { And, Or, + /// `??`: the right side only when the left is `undefined` or `null`. + Coalesce, } /// `=` (`None`) or a compound assignment's operator (`+=` is `Some(BinaryOp::Add)`). @@ -200,6 +202,46 @@ pub enum Expr { object: ExprId, predicate: ExprId, }, + /// An arrow function. + Arrow(FunctionId), + /// A template literal: its pieces (one more than its substitutions) and its substitutions, + /// in source order. + Template { + quasis: Vec, + exprs: Vec, + }, + /// A tagged template (`` tag`a${b}c` ``): `tag` called with the template object and the + /// substitutions. + TaggedTemplate { + tag: ExprId, + quasis: Vec, + exprs: Vec, + }, + /// `...expression` in an array literal or an argument list, and as the last of an arrow + /// function's parenthesized parameters while they are read. + Spread(ExprId), + /// An optional chain (`a?.b.c`, `a?.[k]`, `f?.()`): its accesses and calls, the + /// [`Expr::Optional`] steps among them included. It is `undefined` when one of those steps + /// finds `undefined` or `null`, and the rest of the chain is skipped. + OptionalChain(ExprId), + /// The object or function before `?.` in an [`Expr::OptionalChain`]. + Optional(ExprId), +} + +/// A piece of a template literal's text between its substitutions. +#[derive(Clone, Debug, PartialEq)] +pub struct TemplatePiece { + /// The text with its escapes read. + pub cooked: Vec, + /// The text as written. + pub raw: Vec, +} + +/// Which lexical declaration a name has. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LexKind { + Let, + Const, } /// A piece of an XML literal, in source order. @@ -247,12 +289,17 @@ pub enum ForInTarget { /// `for (var x in o)`, with the declaration's initializer if it has one. Var(VarDecl), Expr(ExprId), + /// `for (let x in o)` or `for (const x in o)`: a new binding for each name. + Lexical(LexKind, Name), } #[derive(Clone, Debug, PartialEq)] pub enum ForInit { Var(Vec), Expr(ExprId), + /// `let` or `const` declarations, in a scope of the loop's own with a new copy of each `let` + /// binding for each iteration. + Lexical(LexKind, Vec), } #[derive(Clone, Debug, PartialEq)] @@ -272,6 +319,8 @@ pub struct CatchClause { #[derive(Clone, Debug, PartialEq)] pub enum Stmt { Var(Vec), + /// `let` or `const` declarations (a `const` always has an initializer). + Lexical(LexKind, Vec), FunctionDecl(FunctionId), Expr(ExprId), Block(Vec), @@ -334,13 +383,20 @@ pub enum FunctionKind { Expression, Getter, Setter, + /// An arrow function; one with an expression body has a body of one `return` statement. + Arrow, } #[derive(Clone, Debug, PartialEq)] pub struct Function { pub kind: FunctionKind, pub name: Option, + /// The parameters before a rest parameter. pub params: Vec, + /// Each parameter's default value, in the order of `params` (empty when none has one). + pub defaults: Vec>, + /// The rest parameter (`...name`). + pub rest: Option, pub body: Vec, /// The function's code is strict mode code: its own directive prologue holds `"use strict"`, /// or the code around it is strict. @@ -348,6 +404,13 @@ pub struct Function { pub span: Span, } +impl Function { + /// The parameters are plain names: no default value and no rest parameter. + pub fn simple_params(&self) -> bool { + self.rest.is_none() && self.defaults.iter().all(Option::is_none) + } +} + /// The arenas of a parsed script. #[derive(Clone, Debug, Default, PartialEq)] pub struct Ast { @@ -412,6 +475,8 @@ pub struct Program { /// Its preprocessor lines, in source order. pub directives: Vec, pub(crate) lines: crate::LineTable, + /// It was read with [`crate::Options::es2015`]. + pub(crate) es2015: bool, } impl Program { diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 380d161ecf..f2c02bdf4c 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -503,7 +503,7 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe Err(CompileFail::Internal(m)) => return Err(Abrupt::Internal(m)), }; interp.charge_code(&code, 0)?; - let env = interp.global_env; + let env = interp.global_scope(); interp.make_closure(code, env).map(Value::Object) } diff --git a/crates/js/src/builtins/extensions.rs b/crates/js/src/builtins/extensions.rs index 94ee226d57..3c58fc64a1 100644 --- a/crates/js/src/builtins/extensions.rs +++ b/crates/js/src/builtins/extensions.rs @@ -410,12 +410,16 @@ const STACK_FRAMES: usize = 64; const STACK_NAME_UNITS: usize = 64; /// The script's frames, outermost first, one a line: the function's name and the line it is at, -/// as `name:line`, or as `name@file:line` with the file the realm's locator names. +/// as `name:line`, or as `name@file:line` with the file the realm's locator names. A first line +/// `[script]` names the running script when the realm has its name. fn stack(interp: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { let frames: Vec<(Rc, usize, bool)> = interp.script_frames().map(|(c, pc, f)| (c.clone(), pc, f)).collect(); let skip = frames.len().saturating_sub(STACK_FRAMES); let locator = interp.locator.clone(); let mut text = String::new(); + if let Some(script) = &interp.script_name { + text.push_str(&format!("[{script}]\n")); + } if skip > 0 { text.push_str("…\n"); } diff --git a/crates/js/src/bytecode.rs b/crates/js/src/bytecode.rs index 6992fd5606..c805ad48e0 100644 --- a/crates/js/src/bytecode.rs +++ b/crates/js/src/bytecode.rs @@ -105,6 +105,15 @@ pub(crate) enum Op { /// Jumps, keeping the top value, when it is falsy; otherwise pops it. JumpIfFalseKeep(u32), JumpIfTrueKeep(u32), + /// Jumps, keeping the top value, when it is neither `undefined` nor `null`; otherwise pops + /// it (`??`). + JumpIfNotNullishKeep(u32), + /// When the top value is `undefined` or `null`, pops `drop` values (the top one among them) + /// and jumps; otherwise goes on with the stack as it was (a step of an optional chain). + JumpIfNullish { + target: u32, + drop: u32, + }, Return, /// Returns the value of the last expression statement (script and eval code). ReturnCompletion, @@ -178,6 +187,49 @@ pub(crate) enum Op { ForEachValue(u32), /// `value` → nothing: sets the default XML namespace of the running code. SetDefaultNamespace, + /// Enters a block's environment: the `let` and `const` names of `scopes[i]`, not yet + /// initialized, and its function declarations. + PushBlock(u32), + /// Replaces the current environment with a copy of it, for a `for` loop's next iteration. + CopyEnv, + /// `value` → nothing: initializes the nearest binding of `names[i]`, a `let`, a `const` or + /// a parameter of a function with default or rest parameters. + InitVar(u32), + /// Pushes the value of the parameter `names[i]` of the running function, initialized or not. + LoadParam(u32), + /// Ends the parameters of a function with default or rest parameters: enters the environment + /// of its body's variables and function declarations, and of its `let` and `const` names. + BodyEnv, + /// `value` → nothing: assigns the function declared in a block outside strict mode code to + /// the variable `names[i]` of the running code (ECMA-262 2015 Annex B.3.3). + AnnexB(u32), + /// `array value` → `array`, with the elements of the value appended (spread). + ArraySpread, + /// `function this array` → result: a call with the array's elements as its arguments, a + /// direct eval when `eval` is true and the function is the global `eval`. + CallSpread(bool), + /// `function array` → the new object, constructed with the array's elements as arguments. + NewSpread, + /// `value` → its string (a template literal's substitution). + ToStr, + /// Pushes the template object of `templates[i]`, the same object for each evaluation. + TemplateObject(u32), +} + +/// The names a block declares, entered with [`Op::PushBlock`]. +#[derive(Debug, Default)] +pub(crate) struct BlockScope { + /// The `let` and `const` names, each with whether it is a `const`. + pub(crate) lets: Vec<(Key, bool)>, + /// The function declarations: their names and indices in `functions`. + pub(crate) funcs: Vec<(Key, u32)>, +} + +/// A tagged template's strings: as read and as written. +#[derive(Debug)] +pub(crate) struct Template { + pub(crate) cooked: Vec, + pub(crate) raw: Vec, } /// What code is: a function body, a script, or eval code. @@ -239,6 +291,23 @@ pub(crate) struct Code { pub(crate) source: Rc, /// Where the function's text starts and ends in the source. pub(crate) span: (u32, u32), + /// The block scopes [`Op::PushBlock`] enters. + pub(crate) scopes: Vec, + /// The scope of the `let` and `const` names at the top of the body, script or eval code. + pub(crate) top_scope: Option, + /// The tagged templates [`Op::TemplateObject`] makes objects of. + pub(crate) templates: Vec